/*
  This work is licensed under Creative Commons GNU GPL License
  http://creativecommons.org/licenses/GPL/2.0/
  Copyright (C) 2006 Russel Lindsay
  www.weetbixthecat.com
  version 0.5 (no TEXTAREA support, so it's only half complete)
*/


/**
  sets the index of the cursor and optionally selects text inside a text input
  element must be a reference to an INPUT (textarea not yet supported)
  if end omitted then cursor is positioned but no text is selected
*/
function setSelectionRange(element, start, end)
{
  if(end === undefined) end = start;
  
  // firefox
  if("selectionStart" in element)
  {
    element.setSelectionRange(start, end);
    element.focus(); // to make behaviour consistent with IE
  }
  // ie win
  else if(document.selection)
  {
    var range = element.createTextRange();
    range.collapse(true);
    range.moveStart("character", start);
    range.moveEnd("character", end - start);
    range.select();
  }
}

/**
  calculates the index of the cursor inside a text input
  element must be a reference to an INPUT (textarea not yet supported)
  returns a simple object {start:<int>, end:<int>} where <int> is -1 if cursor 
  is not in input field or functionality is not supported
*/
function getSelectionRange(element)
{
  var result = {start:-1, end:-1};
  
  // firefox
  if("selectionStart" in element)
    result = {start: element.selectionStart, end: element.selectionEnd};
  // ie win
  else if(document.selection)
  {
    // inputs only
    var range = document.selection.createRange();
    if(range.parentElement() == element)
    {
      var rangeS = range.duplicate();
      rangeS.moveEnd("textedit", 1);
      var rangeE = range.duplicate();
      rangeE.moveStart("textedit", -1);
      result = {start: element.value.length - rangeS.text.length, end: rangeE.text.length};
    }
  }
  
  return result;
}