﻿/*
Javascript to Get or set current Caret position (cursor location) in textarea/input, to get selected value under textarea/input and replace selected value.
author: Vipul Limbachiya
http://vipulilmbachiya.com
*/

/* 
 * This program is free software. It comes without any warranty, to the extent permitted by applicable law. 
 * You can redistribute it and/or modify it without any terms.
 * Save developers, use Firefox http://firefox.com
*/

/*
    $textArea.GetCaretPos(element) -> Returns no as current cursor position at characters
    
    $textArea.SetCaretPos(element, position) -> Sets cursor position to mentioned character index
    
    $textArea.GetSelectedVal(element) -> Returns text selected value
    
    $textArea.ReplaceSelectedVal(element,text) -> Replaces selected text with text supplied
*/


var $textArea = {
    GetCaretPos: function (elm) {
        var currentPos = 0;
        if (document.selection) {
            elm.focus();
            var curRange = document.selection.createRange();
            curRange.moveStart('character', -elm.value.length);
            currentPos = curRange.text.length;
        } else if (elm.selectionStart || elm.selectionStart == '0') {
            currentPos = elm.selectionStart;
        }
        return currentPos;
    },

    SetCaretPos: function (elm, position) {
        if (elm.setSelectionRange) {
            elm.focus();
            elm.setSelectionRange(position, position);
        } else if (elm.createTextRange) {
            var curRange = elm.createTextRange();
            curRange.collapse(true);
            curRange.moveEnd('character', position);
            curRange.moveStart('character', position);
            curRange.select();
        }
    },

    GetSelectedVal: function (elm) {
        var selectedText = "";

        if (elm.setSelectionRange) {
            selectedText = elm.value.substring(elm.selectionStart, elm.selectionEnd)
        } else {
            selectedText = document.selection.createRange().text;
        }

        elm.focus();

        return selectedText;
    },

    ReplaceSelectedVal: function (elm, text) {
        var selectedText = "";

        if (elm.setSelectionRange) {
            elm.value = (elm.value.substring(0, elm.selectionStart) + text + elm.value.substring(elm.selectionEnd, elm.value.length));
        } else {
            document.selection.createRange().text = text;
        }
    }
};


