// JScript source code

//contains calls to silverlight.js, example below loads Page.xaml
function createSilverlight()
{
	Silverlight.createObjectEx({
		source: "Page.xaml",
		parentElement: document.getElementById("SilverlightControlHost"),
		id: "SilverlightControl",
		properties: {
			width: "100%",
			height: "100%",
			version: "1.1",
			enableHtmlAccess: "true"
		},
		
		events: {
		    onLoad: OnLoaded
		}		
	});
	   
	// Give the keyboard focus to the Silverlight control by default
    document.body.onload = function() {
      var silverlightControl = document.getElementById('SilverlightControl');
      if (silverlightControl)
      silverlightControl.focus();
    }

}

function OnLoaded(sender, args)
{
    sender.Content.SLPage.GetCursorPosition = onManagedCallback;
    //sender.Content.SLPage.SetCursorPosition = onManagedCallback2;
}

function onManagedCallback(sender, args)
{
	var oField = document.getElementById("txtChat");
	if (oField != null)
    {
	    // Initialize
	    var iCaretPos = 0;

	    // IE Support
	    if (document.selection) 
	    {
		    // Set focus on the element
		    oField.focus ();

		    // To get cursor position, get empty selection range
		    var oSel = document.selection.createRange();

		    // Move selection start to 0 position
		    oSel.moveStart ('character', -oField.value.length);

		    // The caret position is selection length
		    iCaretPos = oSel.text.length;
	    }
	    // Firefox support
	    else if (oField.selectionStart || oField.selectionStart == '0')
	    {
		    iCaretPos = oField.selectionStart;
	    }

	    // Return results
	    var control = document.getElementById('SilverlightControl');
	    if (!control)
            return;
        
        control.Content.SLPage.SetCursorPosition(iCaretPos);
    }   	
}


function onManagedCallback2 () 
{
    var control = document.getElementById('SilverlightControl');
    if (!control)
        return;
    
    var iCaretPos = control.Content.SLPage.GetCursorPosition();
    
	var oField = document.getElementById("txtChat");
	

    // IE Support
    if (document.selection) {

    // Set focus on the element
    oField.focus ();

    // Create empty selection range
    var oSel = document.selection.createRange ();

    // Move selection start and end to 0 position
    oSel.moveStart ('character', -oField.value.length);

    // Move selection start and end to desired position
    oSel.moveStart ('character', iCaretPos);
    oSel.moveEnd ('character', 0);
    oSel.select ();
    }

    // Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0') {
    oField.selectionStart = iCaretPos;
    oField.selectionEnd = iCaretPos;
    oField.focus ();
    }
}
