// selection.js - GetSelection function

function GetSelectionType( w)
{
	var nType = null;
	if ( w.getSelection)
		nType = 1;
	else 
	if ( w.document.getSelection)
		nType = 2;
	else 
	if ( w.document.selection)
		nType = 3;
	return nType;
}

function GetSelectionInWindow( w, nType)
{
	var sel = '';
	try
	{
		// Opera can work bad with frames: "Security error: attempted to read protected variable"
		switch ( nType)
		{
			case 1:
			{
				sel = w.getSelection();
				break;
			}
			case 2:
			{
				sel = w.document.getSelection();
				break;
			}
			case 3:
			{
				sel = w.document.selection.createRange().text;
				break;
			}
		}
	}
	catch ( e)
	{
	}
	if ( sel == null)
		sel = '';
	return sel;
}

function GetSelection( w, nType)
{
	if ( !w)
		w = window;
	if ( !nType)
		nType = GetSelectionType( w);

	var sel = GetSelectionInWindow( w, nType);

	if ( !IsSelection( sel))
	{
		var i = 0;
		try
		{
			i = w.frames.length;
		}
		catch ( e)
		{
			i = 0;
		}

		while( !IsSelection( sel) && ( i--))
		{
			sel = GetSelection( w.frames[i], nType);
		}
	}
	return sel;
}

function IsSelection( sel)
{
	if (( sel == '') || ( sel == null))
		return false;
	return true;
}

function ClearSelectionRange( sel)
{
	if ( IsSelection( sel))
	{
		if ( sel.getRangeAt)
		{
			var i = 0;
			for ( i = 0; i < sel.rangeCount; i++)
			{
				var range = sel.getRangeAt(i);
				range.collapse( false);
				//range.detach();
				////range.deleteContents();
			}
		}
		else 
		{ 
			// It is not working in Safari
			// range = document.createRange();
			// range.setStart( sel.anchorNode, sel.anchorOffset);
			// range.setEnd( sel.focusNode, sel.focusOffset);
		}
	}
}
function ClearSelectionInWindow( w, nType)
{
	try
	{
		// Opera can work bad with frames: "Security error: attempted to read protected variable"
		switch ( nType)
		{
			case 1:
			case 2:
			{
				var sel = GetSelectionInWindow( w, nType);
				ClearSelectionRange( sel);
				break;
			}
			case 3:
			{
				w.document.selection.clear();
				break;
			}
		}
	}
	catch ( e)
	{
	}
}

function ClearSelection( w, nType)
{
	if ( !w)
		w = window;
	if ( !nType)
		nType = GetSelectionType( w);
	
	ClearSelectionInWindow( w, nType);

	var i = 0;
	try
	{
		i = w.frames.length;
	}
	catch ( e)
	{
		i = 0;
	}

	while( i--)
	{
		ClearSelectionInWindow( w.frames[i], nType);
	}
}
