﻿/*
* jQuery Caret Range plugin
* Copyright (c) 2009 Matt Zabriskie
* Released under the MIT and GPL licenses.
*/
;
(function($) {
    $.extend($.fn, {
    	caret: function (zz_Start, zz_End) {
            var elem = this[0];

            if (elem) {
                // get caret range
            	if (typeof zz_Start == "undefined") {
                    if (elem.selectionStart) {
                    	zz_Start = elem.selectionStart;
                    	zz_End = elem.selectionEnd;
                    }
                    else if (document.selection) {
                        var val = this.val();
                        var range = document.selection.createRange().duplicate();
                        range.moveEnd("character", val.length)
                        zz_Start = (range.text == "" ? val.length : val.lastIndexOf(range.text));

                        range = document.selection.createRange().duplicate();
                        range.moveStart("character", -val.length);
                        zz_End = range.text.length;
                    }
                }
                // set caret range
                else {
                    var val = this.val();

                    if (typeof zz_Start != "number") zz_Start = -1;
                    if (typeof zz_End != "number") zz_End = -1;
                    if (zz_Start < 0) zz_Start = 0;
                    if (zz_End > val.length) zz_End = val.length;
                    if (zz_End < zz_Start) zz_End = zz_Start;
                    if (zz_Start > zz_End) zz_Start = zz_End;

                    elem.focus();

                    if (elem.selectionStart) {
                    	elem.selectionStart = zz_Start;
                    	elem.selectionEnd = zz_End;
                    }
                    else if (document.selection) {
                        var range = elem.createTextRange();
                        range.collapse(true);
                        range.moveStart("character", zz_Start);
                        range.moveEnd("character", zz_End - zz_Start);
                        range.select();
                    }
                }

                return { start: zz_Start, end: zz_End };
            }
        }
    });
})(jQuery);
