﻿

(function($) {
	var selInfo = {
		TextSelectionStrategy: {
			W3C: "W3C standard",
			MS: "Microsoft proprietary",
			OTHER: "Unknown"
		},
		selectionStrategy: null,
		getStrategy: function(target) {
			if (this.selectionStrategy == null) {
				if (target.createTextRange) {
					this.selectionStrategy = this.TextSelectionStrategy.MS;
				}
				else if (target.setSelectionRange) {
					this.selectionStrategy = this.TextSelectionStrategy.W3C;
				}
				else {
					this.selectionStrategy = this.TextSelectionStrategy.OTHER;
				};
			};
			return this.selectionStrategy;
		}
	};

	jQuery.fn.getSelectionInfo = function() {
		if (this.length == 0) return null;
		var target = this[0];
		var info = {};
		info.strategy = selInfo.getStrategy(target);
		if (info.strategy == selInfo.TextSelectionStrategy.MS) {
			var userRange = document.selection.createRange();
			info.selStart = 0;
			info.selEnd = target.value.length;
			while (userRange.moveStart('character', -1) != 0) {
				info.selStart++;
			}
			while (userRange.moveEnd('character', 1) != 0) {
				info.selEnd--;
			}
		}
		else if (info.strategy = selInfo.TextSelectionStrategy.W3C) {
			info.selStart = target.selectionStart;
			info.selEnd = target.selectionEnd;
		};
		info.value = target.value;
		info.selPrefix = info.value.length >= info.selStart ? info.value.substring(0, info.selStart) : "";
		info.selText = info.value.length >= info.selEnd ? info.value.substring(info.selStart, info.selEnd) : "";
		info.selSuffix = info.value.length >= info.selEnd ? info.value.substring(info.selEnd, info.value.length) : "";
		return info;
	};

	jQuery.fn.setSelectionRange = function(start, end) {
		if (this.length == 0) return null;
		var target = this[0];
		strategy = selInfo.getStrategy(target);
		if (strategy == selInfo.TextSelectionStrategy.MS) {
			var range = target.createTextRange();
			range.collapse(true);
			range.moveEnd('character', end);
			range.moveStart('character', start);
			range.select();

			if (Sys.Browser.agent == Sys.Browser.Opera) {
				target.setSelectionRange(start, end);
			};
		}
		else if (strategy == selInfo.TextSelectionStrategy.W3C) {
			target.setSelectionRange(start, end);
		};
	};

	jQuery.fn.sel = function() {
		return this.getSelectionInfo().sel;
	};

	jQuery.fn.selOrVal = function() {
		var x;
		return (x = this.sel()) ? x : this.val();
	};

	jQuery.fn.selPrefix = function() {
		return this.getSelectionInfo().selPrefix;
	};

	jQuery.fn.selPrefixOrVal = function() {
		var x;
		return (x = this.selPrefix()) ? x : this.val();
	};

	jQuery.fn.selSuffix = function() {
		return this.getSelectionInfo().selSuffix;
	};
})(jQuery);

