
/**
 * NameFinder namespace
 *
 * Everything is pretty much accessed statically
 */
NameFinder = {
	searchResultsDiv: null,
	statusDiv: null,
	currentSearchRequest: null,
	lastQuery: "",
	lastRole: "",
	lastOrigin: "",
	queryid: 0,
	workspaceDiv: null,
	dscLeftDiv: null,
	dscRightDiv: null,
	workspace: [  ],
	workspaceDDObjs: [],
	partid: 0,
	userid: 0,
	scrollIntervalId: null,
	scrollAtRight: false,
	dragging: false,
	
	//moreInfoHTML: '<div style="text-align:center"><a class="nmmore" href="%HREF%" title="More information about this name...">&nbsp;</a></div>'
	moreInfoHTML: '<a class="nmore" href="%HREF%" title="More information about this name...">More</a><img src="/img/namelab/transparent.gif" width="68" height="1" border="0" />'
}

/**
 * Main init function, should only be called once per page load
 */
NameFinder.init = function() {
	//NameLab.init();   // this is already done in interior.js!  This caused the search input box to stay its label
	NameLab.preloadImages( '/img/namelab/trash_over.gif',
			'/img/namelab/clear_wrkspce_over.gif', '/img/namelab/save_wrkspce_over.gif',
			'/img/namelab/circlearrow_lft_over.gif', '/img/namelab/circlearrow_rt_over.gif',
			'/img/namelab/grabber_over.gif', '/img/namelab/grabber_dn.gif',
			'/img/namelab/help_icon_over.gif' );
	
	var cache = NameLab.getCookieValue( "workspace" );
	if ( cache && cache.length > 0 ) {
		NameFinder.workspace = eval( cache );
		for ( var n = 0; n < NameFinder.workspace.length; n++ ) {
			if ( NameFinder.workspace[n].id > NameFinder.partid ) {
				NameFinder.partid = NameFinder.workspace[n].id;
			}
		}
	}
	NameFinder.renderWorkspace();
	
	var role = "";
	if ( document.forms.browse_f.rm.checked != document.forms.browse_f.rf.checked ) {
		if ( document.forms.browse_f.rm.checked )
			role = "M";
		else if ( document.forms.browse_f.rf.checked )
			role = "F";
	}
	if ( role != NameFinder.lastRole )
		NameFinder.lastRole = role;
	
	var el = document.getElementById( "searchinput" );
	if ( el ) {
		if ( el.value != "" && !el.showingInstruction )
			NameFinder.checkSearchInputValue( el.value );
	}
	
	if ( NameFinder.userid && NameFinder.userid != 0 ) {
		NameFinder.loadSavedNames();
	}
}


NameFinder.doAddName = function() {
	var el = document.getElementById( "searchinput" );
	if ( el ) {
		if ( el.value != "" && !el.showingInstruction )
			NameFinder.addName( el.value, null, null, true );
	}
	return false;
}


/**
 * Check if the value of the search input field has changed
 * If it has, then a lookup is performed
 */
NameFinder.checkSearchInputValue = function( query ) {
	if ( query != NameFinder.lastQuery ) {
		NameFinder.lastQuery = query;
		NameFinder.doLookup( query );
	}
}

/**
 * Called when the gender or origin values have changed.
 */
NameFinder.filtersChanged = function() {
	var role = "";
	if ( document.forms.browse_f.rm.checked != document.forms.browse_f.rf.checked ) {
		if ( document.forms.browse_f.rm.checked )
			role = "M";
		else if ( document.forms.browse_f.rf.checked )
			role = "F";
	}
	var origin = document.forms.browse_f.o.value;
	if ( role != NameFinder.lastRole || origin != NameFinder.lastOrigin ) {
		NameFinder.lastRole = role;
		NameFinder.lastOrigin = origin;
		NameFinder.doLookup( NameFinder.lastQuery );
	}
}

NameFinder.showMoreResults = function( offset ) {
	NameFinder.doLookup( NameFinder.lastQuery, offset );
}

/**
 * Called when the value of the search input field has changed
 *
 * An ajax request is initiated to get the list of matching names
 */
NameFinder.doLookup = function( query, offset ) {
	YAHOO.log( "NameFinder.doLookup", "info" );
	
	// cancel out any pending requests:
	if ( NameFinder.currentSearchRequest != null ) {
		YAHOO.util.Connect.abort( NameFinder.currentSearchRequest );
		NameFinder.currentSearchRequest = null;
	}
	
	// cache the divs:
	if ( NameFinder.searchResultsDiv == null )
		NameFinder.searchResultsDiv = document.getElementById( 'searchresults' );
	if ( NameFinder.statusDiv == null )
		NameFinder.statusDiv = document.getElementById( 'searchsummary' );
	
	if ( query == "" ) {
		NameFinder.searchResultsDiv.innerHTML = "";
		NameFinder.statusDiv.innerHTML = "No matches";
		return;
	}
	
	// success callback:
	var handleSuccess = function( o ) {
		YAHOO.log( "NameFinder.doLookup success", "info" );
		var result = {};
		
		// build the list:
		if ( o.responseText != undefined ) {
			result = eval( '(' + o.responseText + ')' );
		}
		if ( result.names ) {
			var ihtml = "";
			if ( result.f > 0 ) {
				var moreDiv = document.getElementById( 'lookmore' );
				if ( moreDiv ) {
					moreDiv.parentNode.removeChild( moreDiv );
				}
			}
			for ( var n = 0; n < result.names.length; n++ ) {
				ihtml += "<p class='norm' id=\'look" + (result.f + n) + "\'>" + result.names[n] + "</p>";
			}
			if ( result.total > result.f + result.names.length ) {
				ihtml += "<p class='norm' id='lookmore'><a href='javascript:NameFinder.showMoreResults(" + (result.f + result.names.length) + ")'>Show More...</a></p>";
			}
			if ( result.f > 0 ) {
				var itemsDiv = document.createElement( "div" );
				NameFinder.searchResultsDiv.appendChild( itemsDiv );
				itemsDiv.innerHTML = ihtml;
			}
			else {
				NameFinder.searchResultsDiv.innerHTML = ihtml;
			}
			
			// hook-up drag-n-drop:
			for ( var n = 0; n < result.names.length; n++ ) {
				var resultId = "look" + (result.f + n);
				var dd = new NameFinder.DDSearchResult( result.names[n], resultId );
				var resultEl = document.getElementById( resultId );
				resultEl.ondblclick = function() { NameFinder.addName(this.innerHTML, null, null, true); };
				if ( NameLab.needManualHover ) {
					resultEl.onmouseover = function() { if (!NameFinder.dragging) this.className = "hover"; };
					resultEl.onmouseout = function() { if (!NameFinder.dragging) this.className = "norm"; };
				}
			}
		}
		else {
			NameFinder.searchResultsDiv.innerHTML = o.responseText;
		}
		
		if ( result.total ) {
			NameFinder.statusDiv.innerHTML = "Showing first <em>" + (result.f + result.names.length) + "</em> of <em>" + result.total + "</em> results";
		}
		else {
			NameFinder.statusDiv.innerHTML = "No matches";
		}
		
		NameFinder.currentSearchRequest = null;
	}
	
	// failure callback:
	var handleFailure = function( o ) {
		YAHOO.log( "NameFinder.doLookup failed", "warn" );
		NameFinder.searchResultsDiv.innerHTML = "";
		NameFinder.currentSearchRequest = null;
	}
	
	var callback = { success:handleSuccess, failure:handleFailure };
	
	var vars = "q=" + query + "&seq=" + NameFinder.queryid;
	if ( NameFinder.lastRole.length > 0 )
		vars += "&r=" + NameFinder.lastRole;
	if ( NameFinder.lastOrigin.length > 0 )
		vars += "&o=" + NameFinder.lastOrigin;
	if ( offset )
		vars += "&f=" + offset;
	
	NameFinder.currentSearchRequest = YAHOO.util.Connect.asyncRequest( 'POST', '/servlet2/lookup', callback, vars );
}

/**
 * Called to get the meaning of a name
 */
NameFinder.getMeaning = function( part ) {
	YAHOO.log( "NameFinder.getMeaning", "info" );
	
	// success callback:
	var handleSuccess = function( o ) {
		YAHOO.log( "NameFinder.getMeaning success", "info" );
		var result = {};
		
		// build the list:
		if ( o.responseText != undefined ) {
			YAHOO.log( "NameFinder.getMeaning raw response: " + o.responseText, "debug" );
			result = eval( '(' + o.responseText + ')' );
		}
		var div = null;
		var part = null;
		for ( var n = 0; div == null && n < NameFinder.workspace.length; n++ ) {
			part = NameFinder.workspace[ n ];
			if ( part.id == result.id ) {
				if ( result.def )
					part.def = result.def;
				else
					part.def = "";
                                //if not  mixed case, display the database name
                                if ( result.name ) {
                                     if (result.name.substr(1,result.name.length) == result.name.toLowerCase().substr(1,result.name.length)) {
                                         part.name = result.name;
                                     }
                                }
				part.loading = false;
				NameFinder.cacheWorkspaceLocally();
				div = document.getElementById( 'wkspcslot' + n );
			}
		}
		if ( div != null && part != null ) {
			var ihtml = ""
			ihtml += '<div class="fullname">' + part.name + '</div>';
			if ( result.def ) {
				var def = result.def;
/*@cc_on
	if ( false ) {
@*/
				/* Inserting a zero-width-space to force firefox to wrap hyphenated words.
				 *	This entity isn't recognized on IE, so it is conditionally compiled out there.
				 */
				def = def.replace( '-', '-&#8203;' );
/*@cc_on
	}
@*/
				ihtml += '<div class="defn">' + def + '</div>' + NameFinder.moreInfoHTML.replace('%HREF%', 'name-meaning/' + escape(part.name));
			}
			div.innerHTML = ihtml;
		}
	}
	
	// failure callback:
	var handleFailure = function( o ) {
		YAHOO.log( "NameFinder.getMeaning failed", "warn" );
		var div = null;
		var part = null;
		for ( var n = 0; div == null && n < NameFinder.workspace.length; n++ ) {
			part = NameFinder.workspace[ n ];
			if ( part.id == o.argument ) {
				part.def = "";
				part.loading = false;
				NameFinder.cacheWorkspaceLocally();
				div = document.getElementById( 'wkspcslot' + n );
			}
		}
		if ( div != null && part != null ) {
			var ihtml = ""
			ihtml += '<div class="fullname">' + part.name + '</div>';
			div.innerHTML = ihtml;
		}
	}
	
	var callback = { success:handleSuccess, failure:handleFailure, argument:part.id };
	
	var vars = "n=" + part.name + "&id=" + part.id;
	if ( part.role.length > 0 )
		vars += "&r=" + part.role;
	if ( part.origin.length > 0 )
		vars += "&o=" + part.origin;
	
	NameFinder.currentSearchRequest = YAHOO.util.Connect.asyncRequest( 'POST', '/servlet2/meaning', callback, vars );
}

NameFinder.loadSavedNames = function( inMsg, inVars, inClearWorkspace ) {
	YAHOO.log( "NameFinder.loadSavedNames", "info" );
	
	var statusDiv = document.getElementById( 'savednamestat' );
	if ( inMsg && inMsg.length > 0 )
		statusDiv.innerHTML = inMsg;
	else
		statusDiv.innerHTML = "loading...";
	
	// success callback:
	var handleSuccess = function( o ) {
		YAHOO.log( "NameFinder.loadSavedNames success", "info" );
		var result = [];
		
		var namesDiv = document.getElementById( 'savednames' );
		var statusDiv = document.getElementById( 'savednamestat' );
		
		// build the list:
		if ( o.responseText != undefined ) {
			result = eval( '(' + o.responseText + ')' );
		}
		if ( result.length > 0 ) {
			var ihtml = "<table border='0' width='448' cellspacing='0' cellpadding='0'>";
			for ( var n = 0; n < result.length; n++ ) {
				var row = result[ n ];
				ihtml += "<tr><td valign='middle' width='20'><input type='checkbox' name='sn" + n + "' value='" + row.id + "' /></td><td valign='top'>";
				ihtml += "<div class='norm' id='snl" + n + "'>";
				for ( var p = 0; p < row.names.length; p++ ) {
					var part = row.names[ p ];
					ihtml += "<span class='norm' id='sn" + n + "p" + p + "'>" + part.name + "</span>";
					if ( p < row.names.length - 1 )
						ihtml += ' ';
				}
				if ( row.names.length > 1 )
					ihtml += "<span class='grab' id='gsn" + n + "'><img src='/img/namelab/transparent.gif' width='20' height='18' border='0' /></span>";
				ihtml += "</div></td></tr>";
			}
			ihtml += "</table>";
			
			namesDiv.innerHTML = ihtml;
			
			// hook-up drag-n-drop:
			for ( var n = 0; n < result.length; n++ ) {
				var row = result[ n ];
				for ( var p = 0; p < row.names.length; p++ ) {
					var part = row.names[ p ];
					var partid = "sn" + n + "p" + p;
					var dd = new NameFinder.DDSearchResult( part.name, partid );
					dd.nameRole = part.role;
					dd.nameOrigin = part.origin;
					if ( NameLab.needManualHover ) {
						var partEl = document.getElementById( partid );
						partEl.onmouseover = function() { if (!NameFinder.dragging) this.className = "hover"; };
						partEl.onmouseout = function() { if (!NameFinder.dragging) this.className = "norm"; };
					}
				}
				if ( row.names.length > 1 ) {
					var grabber = document.getElementById( "gsn" + n );
					grabber.lineDiv = document.getElementById( "snl" + n );
					grabber.onmouseover = function() { if (!NameFinder.dragging) this.lineDiv.className = "hover"; };
					grabber.onmouseout = function() { if (!NameFinder.dragging) this.lineDiv.className = "norm"; };
					var dd = new NameFinder.DDSavedSpace( row, n );
				}
			}
			if ( o.argument && o.argument.clearWksp )
				NameFinder.clearWorkspace();
			/*
			for ( var n = 0; n < result.names.length; n++ ) {
				var dd = new NameFinder.DDSearchResult( result.names[n], "look" + n );
			}*/
		}
		else {
			namesDiv.innerHTML = "";
		}
		
		var stat = "You have <em>" + (result.length) + "</em> saved name";
		if ( result.length != 1 )
			stat += "s";
		statusDiv.innerHTML = stat;
	}
	
	// failure callback:
	var handleFailure = function( o ) {
		YAHOO.log( "NameFinder.loadSavedNames failed", "warn" );
		var namesDiv = document.getElementById( 'savednames' );
		var statusDiv = document.getElementById( 'savednamestat' );
		if ( o.argument && o.argument.cleanSlate ) {
			namesDiv.innerHTML = "";
			statusDiv.innerHTML = "You have <em>0</em> saved names";
		}
		else {
			statusDiv.innerHTML = "operation failed";
		}
	}
	
	var callback = { success:handleSuccess, failure:handleFailure, argument:{clearWksp:false,cleanSlate:true} };
	
	if ( inClearWorkspace ) {
		callback.argument.clearWksp = true;
	}
	
	var vars = "u=" + NameFinder.userid;
	if ( inVars && inVars.length > 0 ) {
		vars += "&" + inVars;
		callback.argument.cleanSlate = false;
	}
	
	NameFinder.currentSearchRequest = YAHOO.util.Connect.asyncRequest( 'POST', '/servlet/savednames', callback, vars );
}

NameFinder.moveName = function( frIndex, toIndex ) {
	var part = NameFinder.workspace[ frIndex ];
	NameFinder.workspace.splice( frIndex, 1 );
	if ( frIndex < toIndex )
		toIndex--;
	NameFinder.workspace.splice( toIndex, 0, part );
	NameFinder.renderWorkspace();
	NameFinder.cacheWorkspaceLocally();
}

NameFinder.deleteName = function( index ) {
	NameFinder.workspace.splice( index, 1 );
	NameFinder.renderWorkspace();
	NameFinder.cacheWorkspaceLocally();
}

/**
 * drop handler - insert a name into the workspace
 */
NameFinder.insertName = function( name, index, role, origin ) {
	var newPart = NameFinder.createNamePartObj( name );
	if ( index >= NameFinder.workspace.length )
		NameFinder.workspace[ index ] = newPart;
	else
		NameFinder.workspace.splice( index, 0, newPart );
	NameFinder.renderWorkspace();
	NameFinder.cacheWorkspaceLocally();
	NameFinder.getMeaning( newPart );
}

/**
 * drop handler - add a name at the end of the workspace
 */
NameFinder.addName = function( name, role, origin, scrollToEnd ) {
	var newPart = NameFinder.createNamePartObj( name, role, origin );
	NameFinder.workspace.push( newPart );
	NameFinder.renderWorkspace( scrollToEnd );
	NameFinder.cacheWorkspaceLocally();
	NameFinder.getMeaning( newPart );
}

/**
 * drop handler - replace a name in the workspace
 */
NameFinder.replaceName = function( name, index, role, origin ) {
	var newPart = NameFinder.createNamePartObj( name, role, origin );
	NameFinder.workspace[ index ] = newPart;
	NameFinder.renderWorkspace();
	NameFinder.cacheWorkspaceLocally();
	NameFinder.getMeaning( newPart );
}

/**
 * creates a name part object intended for the workspace
 * attaches any gender and/or origin filtering criteria
 */
NameFinder.createNamePartObj = function( name, role, origin ) {
	YAHOO.log( "NameFinder.createNamePartObj: " + name + ", " + role + ", " + origin, "info" );
	NameFinder.partid++;
	var part = { name:name, id:NameFinder.partid, role:"", origin:"", loading:true };
	if ( role ) {
		part.role = role;
		part.origin = origin;
	}
	else {
		if ( NameFinder.lastRole.length > 0 )
			part.role = NameFinder.lastRole;
		if ( NameFinder.lastOrigin.length > 0 )
			part.origin = NameFinder.lastOrigin;
	}
	return part;
}

/**
 * Saves the workspace as a cookie
 */
NameFinder.cacheWorkspaceLocally = function() {
	document.cookie = "workspace=" + escape( NameFinder.workspace.toJSONString() );
}

/**
 * Empties the workspace
 */
NameFinder.clearWorkspace = function() {
	NameFinder.workspace = [];
	NameFinder.cacheWorkspaceLocally();
	if(NameFinder.workspaceDiv!=null) NameFinder.workspaceDiv.scrollLeft = 0;
	NameFinder.renderWorkspace();
	return false;
}

/**
 * saves the workspace on the server
 */
NameFinder.saveWorkspace = function() {
	if ( NameFinder.userid && NameFinder.userid != 0 ) {
		if ( NameFinder.workspace.length > 0 ) {
			var w = new Array();
			for ( var n = 0; n < NameFinder.workspace.length; n++ ) {
				var p = NameFinder.workspace[ n ];
				w.push( { name:p.name, role:p.role, origin:p.origin } );
			}
			NameFinder.loadSavedNames( "saving...", "w=" + escape(w.toJSONString()), true );
			/*
			document.forms.savewkspc_f.w.value = w.toJSONString();
			document.forms.savewkspc_f.submit();
			*/
		}
	}
	else {
		alert( "Please log in to enable saving your workspace." );
	}
	return false;
}

/**
 * saves a single name from the workspace on the server
 */
NameFinder.saveOneNameFromWorkspace = function( index ) {
	if ( NameFinder.userid && NameFinder.userid != 0 ) {
		if ( index < NameFinder.workspace.length ) {
			var p = NameFinder.workspace[ index ];
			var w = new Array();
			w.push( { name:p.name, role:p.role, origin:p.origin } );
			NameFinder.loadSavedNames( "saving...", "w=" + escape(w.toJSONString()), false );
			/*
			document.forms.savewkspc_f.w.value = w.toJSONString();
			document.forms.savewkspc_f.cl.value = '0';
			document.forms.savewkspc_f.submit();
			*/
		}
	}
}

/**
 * deletes all selected names
 */
NameFinder.deleteSelectedSavedNames = function() {
	var ids = [];
	var n = 0;
	while ( document.forms.savednamelist_f["sn"+n] ) {
		if ( document.forms.savednamelist_f["sn"+n].checked )
			ids.push( document.forms.savednamelist_f["sn"+n].value );
		n++;
	}
	if ( ids.length > 0 ) {
		var msg = "Are you sure you want to delete the selected name";
		if ( ids.length != 1 )
			msg += "s";
		msg += "?";
		if ( confirm(msg) == 1 ) {
			NameFinder.loadSavedNames( "deleting...", "del=" + ids.join( "," ), false );
			/*
			document.forms.savednamelist_f.del.value = ids.join( "," );
			document.forms.savednamelist_f.submit();
			*/
		}
	}
	else {
		alert( "Please select the names you wish to delete by using the checkboxes in the Saved Names list." );
	}
	return false;
}

/**
 * replace the workspace with a set of saved names
 */
NameFinder.replaceWorkspace = function( newSpace ) {
	YAHOO.log( "NameFinder.replaceWorkspace", "info" );
	NameFinder.workspace = [];
	for ( var p = 0; p < newSpace.names.length; p++ ) {
		var part = newSpace.names[ p ];
		var newPart = NameFinder.createNamePartObj( part.name, part.role, part.origin );
		NameFinder.workspace.push( newPart );
	}
	NameFinder.workspaceDiv.scrollLeft = 0;
	NameFinder.renderWorkspace();
	NameFinder.cacheWorkspaceLocally();
	for ( var n = 0; n < NameFinder.workspace.length; n++ ) {
		NameFinder.getMeaning( NameFinder.workspace[n] );
	}
}

/**
 * Re-generates the html for the workspace
 */
NameFinder.renderWorkspace = function( scrollToEnd ) {
	
	while ( NameFinder.workspaceDDObjs.length > 0 ) {
		var obj = NameFinder.workspaceDDObjs.shift();
		obj.unreg();
	}
	
	if ( NameFinder.workspace.length > 0 ) {
		for ( var n = 0; n < NameFinder.workspace.length; n ) {
			var part = NameFinder.workspace[ n ];
			if ( part && part.name && part.name.length > 0 )
				n++;
			else
				NameFinder.workspace.splice( n, 1 );
		}
	}
	
	var html = '<table cellspacing="0" cellpadding="0" border="0"><tr>';
	
	if ( NameFinder.workspace.length >= 0 )
		html += '<td valign="top"><div class="wkspcdiv"><div id="wkspcdiv0" class="hilite_up"></div></div></td>';
	
	for ( var n = 0; n < NameFinder.workspace.length; n++ ) {
		var part = NameFinder.workspace[ n ];
		html += '<td valign="top"><div class="wkspcslot"><div id="wkspcslot' + n + '" class="hilite_up">';
		if ( part && part.name && part.name.length > 0 ) {
			html += '<div id="wkspchova" class="fullname">' + part.name + '</div>';
			if ( part.def && part.def.length > 0 ) {
				var def = part.def;
/*@cc_on
	if ( false ) {
@*/
				/* Inserting a zero-width-space to force firefox to wrap hyphenated words.
				 *	This entity isn't recognized on IE, so it is conditionally compiled out there.
				 */
				def = def.replace( '-', '-&#8203;' );
/*@cc_on
	}
@*/
				html += '<div class="defn">' + def + '</div>' + NameFinder.moreInfoHTML.replace('%HREF%', 'name-meaning/' + escape(part.name));
			}
			else if ( part.loading )
				html += '<img src="/img/namelab/loading.gif" width="16" height="16" border="0" />';
		}
		else
			html += '<div class="emptyname"></div>';
		html += '</div></div></td>';
		if ( n < NameFinder.workspace.length - 1 )
			html += '<td valign="top"><div class="wkspcdiv"><div id="wkspcdiv' + (n+1) + '" class="hilite_up">&nbsp;</div></div></td>';
	}
	html += '<td valign="top"><div class="wkspcdivfinal"><div id="wkspcend" class="hilite_up">&nbsp;</div></div></td>';
	
	if ( NameFinder.workspace.length > 1 )
		html += '<td valign="top" width="20"><div class="grab" id="gwk"><img src="/img/namelab/transparent.gif" width="20" height="18" border="0" /></div></td>';
	
	html += '</tr></table>';
	
	
	if ( NameFinder.workspaceDiv == null )
		NameFinder.workspaceDiv = document.getElementById( 'workspace' );
	
	NameFinder.workspaceDiv.innerHTML = html;
	
	for ( var n = 0; n < NameFinder.workspace.length; n++ ) {
		NameFinder.workspaceDDObjs.push( new NameFinder.DDWorkspaceName(n, 'wkspcslot' + n) );
	}
	
	if ( NameFinder.workspace.length > 1 ) {
		var grabber = document.getElementById( "gwk" );
		grabber.onmouseover = function() { if (!NameFinder.dragging) NameFinder.workspaceDiv.className = "wkspc_hiall"; };
		grabber.onmouseout = function() { if (!NameFinder.dragging) NameFinder.workspaceDiv.className = "wkspc_norm"; };
		NameFinder.workspaceDDObjs.push( new NameFinder.DDAllWorkspace() );
	}
	
	NameFinder.dscLeftDiv = document.getElementById( 'dsc_left' );
	NameFinder.dscRightDiv = document.getElementById( 'dsc_right' );
	
	if ( scrollToEnd )
		NameFinder.workspaceDiv.scrollLeft = NameFinder.workspaceDiv.scrollWidth;
		
	if ( NameFinder.workspaceDiv.scrollWidth > NameFinder.workspaceDiv.clientWidth ) {
		if ( NameFinder.workspaceDiv.scrollLeft > 0 ) {
			NameFinder.dscLeftDiv.className = "on";
		}
		else {
			NameFinder.dscLeftDiv.className = "dis";
		}
		NameFinder.dscLeftDiv.onmousedown = function() { NameFinder.startScroll(true); }
		NameFinder.dscLeftDiv.onmouseup = function() { NameFinder.stopScroll(); }
		
		NameFinder.scrollAtRight = false;
		NameFinder.dscRightDiv.className = "on";
		NameFinder.dscRightDiv.onmousedown = function() { NameFinder.startScroll(false); }
		NameFinder.dscRightDiv.onmouseup = function() { NameFinder.stopScroll(); }
	}
	else {
		NameFinder.dscLeftDiv.className = "off";
		NameFinder.dscRightDiv.className = "off";
		NameFinder.dscLeftDiv.onmousedown = null;
		NameFinder.dscLeftDiv.onmouseup = null;
		NameFinder.dscRightDiv.onmousedown = null;
		NameFinder.dscRightDiv.onmouseup = null;
		NameFinder.workspaceDiv.scrollLeft = 0;
	}
	
	NameFinder.initDropTargets();
	
	
}

/**
 * Called to set up the drop targets for the search result items
 */
NameFinder.initDropTargets = function() {
	var n = 0;
	var wkspcslotDiv = document.getElementById( 'wkspcslot' + n );
	while ( wkspcslotDiv ) {
		NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('wkspcslot' + n) );
		n++;
		wkspcslotDiv = document.getElementById( 'wkspcslot' + n );
	}
	
	n = 0;
	var wkspcdivDiv = document.getElementById( 'wkspcdiv' + n );
	while ( wkspcdivDiv || n == 0 ) {
		NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('wkspcdiv' + n) );
		n++;
		wkspcdivDiv = document.getElementById( 'wkspcdiv' + n );
	}
	
	NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('workspace') );
	NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('trashcan') );
	NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('dsc_left') );
	NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('dsc_right') );
	NameFinder.workspaceDDObjs.push( new YAHOO.util.DDTarget('savednames') );
}


NameFinder.onScroll = function() {
	if ( (NameFinder.scrollAmount < 0 && NameFinder.workspaceDiv.scrollLeft > 0)
			|| (NameFinder.scrollAmount > 0 && !NameFinder.scrollAtRight) ) {
		
		var oldScrollVal = NameFinder.workspaceDiv.scrollLeft;
		
		// scroll:
		NameFinder.workspaceDiv.scrollLeft = NameFinder.workspaceDiv.scrollLeft + NameFinder.scrollAmount;
		
		// checck scroll left disabled:
		if ( NameFinder.workspaceDiv.scrollLeft > 0 && oldScrollVal == 0 ) {
			NameFinder.dscLeftDiv.className = "on";
		}
		else if ( NameFinder.workspaceDiv.scrollLeft == 0 && oldScrollVal > 0 ) {
			NameFinder.dscLeftDiv.className = "dis";
		}
		
		// checck scroll right disabled:
		if ( oldScrollVal == NameFinder.workspaceDiv.scrollLeft && oldScrollVal > 0 && !NameFinder.scrollAtRight ) {
			NameFinder.scrollAtRight = true;
			NameFinder.dscRightDiv.className = "dis";
		}
		else if ( oldScrollVal != NameFinder.workspaceDiv.scrollLeft && oldScrollVal > 0 && NameFinder.scrollAtRight ) {
			NameFinder.scrollAtRight = false;
			NameFinder.dscRightDiv.className = "on";
		}
	}
}
NameFinder.startScroll = function( toTheLeft ) {
	NameFinder.stopScroll();
	if ( NameFinder.workspaceDiv.scrollWidth > NameFinder.workspaceDiv.clientWidth ) {
		NameFinder.scrollAmount = toTheLeft ? -10 : 10;
		NameFinder.scrollIntervalId = window.setInterval( NameFinder.onScroll, 40 );
	}
}
NameFinder.stopScroll = function() {
	if ( NameFinder.scrollIntervalId != null ) {
		window.clearInterval( NameFinder.scrollIntervalId );
		NameFinder.scrollIntervalId = null;
		YAHOO.util.DragDropMgr.refreshCache();
	}
}


/**
 * shows the help in a popup window
 */
NameFinder.showHelp = function() {
	window.open( "namefinder_help", "_blank", "width=620,height=600,scrollbars=yes" );
}


/**
 * DDSearchResult class, extends YAHOO.util.DDProxy
 *
 * represents a single name in the search results
 * can be dropped onto the workspace, either in between items
 *	(via NameFinder.insertName) or on top of an existing one
 *	(via NameFinder.replaceName).
 */
NameFinder.DDSearchResult = function(name, id, sGroup, config) {
    this.searchResultInit(name, id, sGroup, config);
};

YAHOO.extend(NameFinder.DDSearchResult, YAHOO.util.DDProxy);

NameFinder.DDSearchResult.prototype.searchResultInit = function(name, id, sGroup, config) {
    if (!id) { return; }

    this.init(id, sGroup, config);
    this.initFrame();
    this.logger = this.logger || YAHOO;
    this.els = [];
    this.name = name;
    this.overItem = false;
};

NameFinder.DDSearchResult.prototype.onDragDrop = function(e, id) {
    this.logger.log(this.id + " dragDrop " + id);

	if ( id.indexOf("wkspcslot") != -1 && this.overItem ) {
		NameFinder.replaceName( this.name, parseInt(id.substr(9)), this.nameRole, this.nameOrigin );
	}
	else if ( id.indexOf("wkspcdiv") != -1 && this.overItem ) {
		NameFinder.insertName( this.name, parseInt(id.substr(8)), this.nameRole, this.nameOrigin );
	}
	else if ( id == "workspace" && !this.overItem ) {
		NameFinder.addName( this.name, this.nameRole, this.nameOrigin );
	}
};

NameFinder.DDSearchResult.prototype.startDrag = function(e) {
    this.logger.log(this.id + " startDrag");
    
    this.overItem = false;
    YAHOO.util.DDM.getElement(this.id).className = "sel";
    NameFinder.dragging = true;
};

NameFinder.DDSearchResult.prototype.endDrag = function(e) {
    this.logger.log(this.id + " endDrag");
    this.resetStyles();
	NameFinder.stopScroll();
    NameFinder.dragging = false;
};

NameFinder.DDSearchResult.prototype.onDragEnter = function(e, id) {
    this.logger.log(this.id + " dragEnter " + id);
	
    if ( id == "workspace" )
    	id = "wkspcend";
    
	if ( id.indexOf("wkspc") != -1 ) {
		// store a ref so we can restore the style later
		this.els[id] = true;
	
		// set the mouseover style
		var el = YAHOO.util.DDM.getElement(id);
		if ( el.className != "hilite_over" ) {
			el.className = "hilite_over";
		}
		
		if ( id != "wkspcend" && this.els.wkspcend ) {
			YAHOO.util.DDM.getElement("wkspcend").className = "hilite_up";
			this.overItem = true;
		}
	}
	
	else if ( id == "dsc_left" ) {
		NameFinder.startScroll( true );
	}
	else if ( id == "dsc_right" ) {
		NameFinder.startScroll( false );
	}
};

NameFinder.DDSearchResult.prototype.onDragOut = function(e, id) {
    this.logger.log(this.id + " dragOut " + id);

    // restore the style
    if ( id == "workspace" )
    	id = "wkspcend";
    
	if ( id.indexOf("wkspc") != -1 ) {
		this.els[id] = false;
		YAHOO.util.DDM.getElement(id).className = "hilite_up";
		
		if ( id != "wkspcend" && this.els.wkspcend ) {
			YAHOO.util.DDM.getElement("wkspcend").className = "hilite_over";
			this.overItem = false;
		}
	}
	
	else if ( id.indexOf("dsc_") != -1 ) {
		NameFinder.stopScroll();
	}
};

NameFinder.DDSearchResult.prototype.onDrag = function(e) { };

NameFinder.DDSearchResult.prototype.onDragOver = function(e) { };

NameFinder.DDSearchResult.prototype.resetStyles = function() {
    
    YAHOO.util.DDM.getElement(this.id).className = "norm";
    
    // restore all element styles
    for (var i in this.els) {
        var el = YAHOO.util.DDM.getElement(i);
        if (el) { el.className = "hilite_up"; }
    }
};



/**
 * DDWorkspaceName class, extends YAHOO.util.DDProxy
 *
 */
NameFinder.DDWorkspaceName = function(index, id, sGroup, config) {
    this.workspaceNameInit(index, id, sGroup, config);
};

YAHOO.extend(NameFinder.DDWorkspaceName, YAHOO.util.DDProxy);

NameFinder.DDWorkspaceName.prototype.workspaceNameInit = function(ndx, id, sGroup, config) {
    if (!id) { return; }

    this.init(id, sGroup, config);
    this.initFrame();
    this.logger = this.logger || YAHOO;
    this.ndx = ndx;
    this.dropIndex = -1;
    this.inWorkspace = false;
    this.trash = false;
    this.inSaved = false;
};

NameFinder.DDWorkspaceName.prototype.onDragDrop = function(e, id) {
    this.logger.log(this.id + " dragDrop " + id);
};

NameFinder.DDWorkspaceName.prototype.startDrag = function(e) {
    this.logger.log(this.id + " startDrag");
    YAHOO.util.DDM.getElement(this.id).className = "hilite_sel";
    NameFinder.dragging = true;
};

NameFinder.DDWorkspaceName.prototype.endDrag = function(e) {
    this.logger.log(this.id + " endDrag");
    this.resetStyles();

	if ( this.dropIndex != -1 ) {
    	this.logger.log( "moving " + this.ndx + " to " + this.dropIndex );
    	if ( this.dropIndex < this.ndx || this.dropIndex > this.ndx + 1 )
    		NameFinder.moveName( this.ndx, this.dropIndex )
		this.dropIndex = -1;
	}
	else if ( this.trash ) {
		NameFinder.deleteName( this.ndx );
	}
	else if ( this.inSaved ) {
		NameFinder.saveOneNameFromWorkspace( this.ndx );
	}
	NameFinder.stopScroll();
    NameFinder.dragging = false;
};

NameFinder.DDWorkspaceName.prototype.onDragEnter = function(e, id) {
    this.logger.log(this.id + " dragEnter " + id);
	
	if ( id == "workspace" )
		this.inWorkspace = true;
	
	var i = this.getDropIndex( id );
	
	if ( i != this.dropIndex ) {
    	this.logger.log( "new drop index: " + i );
		if ( this.dropIndex != -1 ) {
			if ( this.dropIndex < NameFinder.workspace.length )
				YAHOO.util.DDM.getElement("wkspcdiv" + this.dropIndex).className = "hilite_up";
			else
				YAHOO.util.DDM.getElement("wkspcend").className = "hilite_up";
		}
		this.dropIndex = i;
		if ( this.dropIndex != -1 ) {
			if ( this.dropIndex < NameFinder.workspace.length )
				YAHOO.util.DDM.getElement("wkspcdiv" + this.dropIndex).className = "hilite_over";
			else
				YAHOO.util.DDM.getElement("wkspcend").className = "hilite_over";
		}
	}
	
	if ( id == "trashcan" ) {
		this.trash = true;
		YAHOO.util.DDM.getElement("trashcan").className = "trash_over";
	}
	
	else if ( id == "dsc_left" ) {
		NameFinder.startScroll( true );
	}
	else if ( id == "dsc_right" ) {
		NameFinder.startScroll( false );
	}
	
	else if ( id == "savednames" ) {
		this.inSaved = true;
		YAHOO.util.DDM.getElement("savednames").className = "saved_sel";
	}
};

NameFinder.DDWorkspaceName.prototype.onDragOut = function(e, id) {
    this.logger.log(this.id + " dragOut " + id);
	
	if ( id == "workspace" )
		this.inWorkspace = false;

	var index = this.getDropIndex( id );
    
	if ( index == this.dropIndex ) {
		if ( this.inWorkspace )
			this.onDragEnter( e, "workspace" );
		else {
			this.logger.log( "expire drop index: " + this.dropIndex );
			if ( this.dropIndex > -1 && this.dropIndex < NameFinder.workspace.length )
				YAHOO.util.DDM.getElement("wkspcdiv" + this.dropIndex).className = "hilite_up";
			else
				YAHOO.util.DDM.getElement("wkspcend").className = "hilite_up";
			this.dropIndex = -1;
		}
	}
	
	if ( id == "trashcan" ) {
		this.trash = false;
		YAHOO.util.DDM.getElement("trashcan").className = "trash_up";
	}
	
	else if ( id.indexOf("dsc_") != -1 ) {
		NameFinder.stopScroll();
	}
	
	else if ( id == "savednames" ) {
		this.inSaved = false;
		YAHOO.util.DDM.getElement("savednames").className = "saved_norm";
	}
};

NameFinder.DDWorkspaceName.prototype.getDropIndex = function(id) {
	var index = -1;
	if ( id != this.id ) {
		if ( id == "workspace" )
			index = NameFinder.workspace.length;
		else if ( id.indexOf("wkspcslot") == 0 )
			index = parseInt( id.substring(9) ) + 1;
		else if ( id.indexOf("wkspcdiv") == 0 )
			index = parseInt( id.substring(8) );
	}
	return index;
}

NameFinder.DDWorkspaceName.prototype.onDrag = function(e) { };

NameFinder.DDWorkspaceName.prototype.onDragOver = function(e) { };

NameFinder.DDWorkspaceName.prototype.resetStyles = function() {
    
    YAHOO.util.DDM.getElement(this.id).className = "hilite_up";
    
	if ( this.dropIndex != -1 ) {
		if ( this.dropIndex < NameFinder.workspace.length )
			YAHOO.util.DDM.getElement("wkspcdiv" + this.dropIndex).className = "hilite_up";
		else
			YAHOO.util.DDM.getElement("wkspcend").className = "hilite_up";
	}
	if ( this.trash )
		YAHOO.util.DDM.getElement("trashcan").className = "trash_up";
	if ( this.inSaved )
		YAHOO.util.DDM.getElement("savednames").className = "saved_norm";
};



/**
 * DDAllWorkspace class, extends YAHOO.util.DDProxy
 *
 */
NameFinder.DDAllWorkspace = function(wkspc, n, sGroup, config) {
    this.allWorkspaceInit(sGroup, config);
};

YAHOO.extend(NameFinder.DDAllWorkspace, YAHOO.util.DDProxy);

NameFinder.DDAllWorkspace.prototype.allWorkspaceInit = function(sGroup, config) {
    this.init("gwk", sGroup, config);
    this.initFrame();
    this.logger = this.logger || YAHOO;
    this.inSave = false;
};

NameFinder.DDAllWorkspace.prototype.onDragDrop = function(e, id) {
    this.logger.log(this.id + " dragDrop " + id);
};

NameFinder.DDAllWorkspace.prototype.startDrag = function(e) {
    this.logger.log(this.id + " startDrag");
    YAHOO.util.DDM.getElement( "workspace" ).className = "wkspc_selall";
    NameFinder.dragging = true;
    this.inSave = false;
};

NameFinder.DDAllWorkspace.prototype.endDrag = function(e) {
    this.logger.log(this.id + " endDrag");
    
    if ( this.inSave ) {
    	NameFinder.saveWorkspace();
    }
    
    this.resetStyles();
    NameFinder.dragging = false;
};

NameFinder.DDAllWorkspace.prototype.onDragEnter = function(e, id) {
    this.logger.log(this.id + " dragEnter " + id);
	
	if ( id == "savednames" ) {
		this.inSave = true;
		YAHOO.util.DDM.getElement("savednames").className = "saved_sel";
	}
};

NameFinder.DDAllWorkspace.prototype.onDragOut = function(e, id) {
    this.logger.log(this.id + " dragOut " + id);
	
	if ( id == "savednames" ) {
		this.inSave = false;
		YAHOO.util.DDM.getElement("savednames").className = "saved_norm";
	}
};

NameFinder.DDAllWorkspace.prototype.onDrag = function(e) { };

NameFinder.DDAllWorkspace.prototype.onDragOver = function(e) { };

NameFinder.DDAllWorkspace.prototype.resetStyles = function() {
    YAHOO.util.DDM.getElement( "workspace" ).className = "wkspc_norm";
	if ( this.inSave ) {
		YAHOO.util.DDM.getElement("savednames").className = "saved_norm";
	}
};



/**
 * DDSavedSpace class, extends YAHOO.util.DDProxy
 *
 */
NameFinder.DDSavedSpace = function(wkspc, n, sGroup, config) {
    this.savedSpaceInit(wkspc, n, sGroup, config);
};

YAHOO.extend(NameFinder.DDSavedSpace, YAHOO.util.DDProxy);

NameFinder.DDSavedSpace.prototype.savedSpaceInit = function(wkspc, n, sGroup, config) {
    this.init("gsn"+n, sGroup, config);
    this.initFrame();
    this.logger = this.logger || YAHOO;
    this.workspace = wkspc;
    this.num = n;
    this.inWorkspace = false;
};

NameFinder.DDSavedSpace.prototype.onDragDrop = function(e, id) {
    this.logger.log(this.id + " dragDrop " + id);
};

NameFinder.DDSavedSpace.prototype.startDrag = function(e) {
    this.logger.log(this.id + " startDrag");
    YAHOO.util.DDM.getElement( "snl" + this.num ).className = "sel";
    NameFinder.dragging = true;
    this.inWorkspace = false;
};

NameFinder.DDSavedSpace.prototype.endDrag = function(e) {
    this.logger.log(this.id + " endDrag");
    
    if ( this.inWorkspace ) {
    	NameFinder.replaceWorkspace( this.workspace );
    }
    
    this.resetStyles();
    NameFinder.dragging = false;
};

NameFinder.DDSavedSpace.prototype.onDragEnter = function(e, id) {
    this.logger.log(this.id + " dragEnter " + id);
	
	if ( id == "workspace" ) {
		this.inWorkspace = true;
		YAHOO.util.DDM.getElement("workspace").className = "wkspc_sel";
	}
};

NameFinder.DDSavedSpace.prototype.onDragOut = function(e, id) {
    this.logger.log(this.id + " dragOut " + id);
	
	if ( id == "workspace" ) {
		this.inWorkspace = false;
		YAHOO.util.DDM.getElement("workspace").className = "wkspc_norm";
	}
};

NameFinder.DDSavedSpace.prototype.onDrag = function(e) { };

NameFinder.DDSavedSpace.prototype.onDragOver = function(e) { };

NameFinder.DDSavedSpace.prototype.resetStyles = function() {
    YAHOO.util.DDM.getElement( "snl" + this.num ).className = "norm";
	if ( this.inWorkspace ) {
		YAHOO.util.DDM.getElement("workspace").className = "wkspc_norm";
	}
};

YAHOO.util.Event.addListener(window, "load", NameFinder.init, window, false);
