/*
  This work is licensed under Creative Commons GNU GPL License
  http://creativecommons.org/licenses/GPL/2.0/
  Copyright (C) 2006 Russel Lindsay
  last updated 2006-09-28
  www.weetbixthecat.com
*/
 
 
/**
  Sorts an array of integers
  This is very fast over large arrays - around 10 times faster than the common
  myArray.sort(function(a, b){return a - b});
  doesn't do negative numbers
*/
Array.prototype.integerSort = function()
{
  var i = this.length,
      mask = Array.integerSortMask,
      length = mask.length;
  while(i--)
  {
    this[i] = "" + this[i];
    this[i] = (this[i].length < length ? mask[length - this[i].length] : "") + this[i];
  }

  this.sort();

  i = this.length;
  while(i--)
    this[i] = parseInt(this[i], 10);
}
// if you wish to sort numbers greater than 10 digits extend this array in like
Array.integerSortMask = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000"];
 
 
/**
   Sorts an array of objects or an array of arrays
   Very fast over large arrays, around 100 times faster in IE (firefox has no probs) than
   array.sort(function(a, b){return (b < a) - (a < b)});

   Please note that this method is DEFEATED when an object or array implements
   a custom toString() method. The scope of this code is designed for, say, json.

   Given an array of objects {firstname, surname, age, sex}, here is an example
   of sorting on the surname property:
     var index = function(){return this.surname};
     myArray.propertySort(index);
   In this case, because the function is so simple, we could simply pass the
   proterty to the sort function directly:
     myArray.propertySort("literal");
   To sort by surname first and firstname second:
     var index = function(){return this.surname + this.firstname};
     myArray.propertySort(index);
   A note on the index function: While IE only calls the toString() method once
   for each object in the array, Firefox seems to call it multiple times,
   slowing the sort down for complex functions. It would be wise then to create
   a new property for each object with the calculated sort string and then sort
   on that (pretend myArray is already defined):
     var i = myArray.length;
     while(i--)
       myArray[i].sort = myArray[i].surname + myArray[i].firstname;
     myArray.propertySort("sort");
*/
Array.prototype.propertySort = function(index)
{
  var objectToString = Object.prototype.toString,
      arrayToString = Array.prototype.toString;
 
  if(typeof index != "function")
  {
    var property = index;
    index = function(){return this[property]};
  }
  Object.prototype.toString = index;
  Array.prototype.toString = index;

  this.sort();

  Object.prototype.toString = objectToString;
  Array.prototype.toString = arrayToString;
}

