﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
if (typeof Array.prototype.sortObjectArray !== 'function') {
	Array.prototype.sortObjectArray = function (firstSort) {
		var 
			sortBy = []
			, compareNumbers = function (a, b, dir) {
				dir = (dir.toUpperCase() === 'DESC' ? -1 : 1);
				return (a - b) * dir;
			}
			, compareDates = function (a, b, dir) { /* Not Tested*/
				var 
					  dateA = new Date(a.year, a.month, a.date)
					, dateB = new Date(b.year, b.month, b.date)
				;
				
				dir = (dir.toUpperCase() === 'DESC' ? -1 : 1);
				return (dateA - dateB) * dir;
			}
			, compareStrings = function (a, b, dir) {
				var 
					  sortValue = 0
					, stringA = a.toLowerCase()
					, stringB = b.toLowerCase()
				;

				dir = (dir.toUpperCase() === 'DESC' ? -1 : 1);

				(stringA < stringB) && (sortValue = -1 * dir);
				(stringA > stringB) && (sortValue = 1 * dir);
				return sortValue;
			}
			, convertObjectArgstoArray = function (args) {
				for (var i = 0; i < args.length; i++) {
					sortBy.push(args[i]);
				}
			}
			, convertStringArgstoArray = function (args) {
				for (var i = 0; i < args.length; i++) {
					sortBy.push({ name: args[i] });
				}
			}
		;

		(typeof firstSort === 'object') && convertObjectArgstoArray(arguments);
		(typeof firstSort === 'string') && convertStringArgstoArray(arguments);

		this.sort(function (a, b) {
			var property, sortDir
				, sortValue = 0
			;

			for (var i = 0; i < sortBy.length; i++) {
				property = sortBy[i];
				if (sortValue === 0) {
					sortDir = (property.dir || 'ASC');
					(typeof a[property.name] === 'string') && (sortValue = compareStrings(a[property.name], b[property.name], sortDir));
					(typeof a[property.name] === 'date') && (sortValue = compareDates(a[property.name], b[property.name], sortDir));
					(!isNaN(a[property.name])) && (sortValue = compareNumbers(a[property.name], b[property.name], sortDir));
				}
			}
			return sortValue;
		});
	};
}

if (typeof String.prototype.ltrim !== 'function') {
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/,"");
	}
}

if (typeof String.prototype.rtrim !== 'function') {
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/,"");
	}
}

if (typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
		return this.ltrim().rtrim();
	};
}
