
// MacJams Song List Sorting
// v9
// you are free to do anything you wish with this code
// Bill Grundmann http://www.macjams.com/artist/SmokeyVW
//
// allow users to sort their songlist on each column

// see http://blog.roberthahn.ca/articles/2007/02/02/how-to-use-window-onload-the-right-way
// each script that directly uses window.onload should instead use this code.
//
function makeDoubleDelegate(function1, function2) {
    return function() {
        if (function1) function1();
        if (function2) function2();
    }
}
window.onload = makeDoubleDelegate(window.onload, installSongSort );

function installSongSort()
{
    var font=document.getElementsByTagName("font");
    var i,tr,tbody;

    // find the song table
    tbody=null;
    for (i=0; i<font.length; i++) {
        if ((font[i].color=="green" || font[i].color=="#008000") && font[i].firstChild.nodeValue!=null && font[i].firstChild.nodeValue.toLowerCase()=="active") {
            tr=font[i].parentNode.parentNode;
            tbody=tr.parentNode;
            break;
        }
    }
    // if user has no songs, the table can't be found
    // could try looking harder, perhaps at column headers

    // couldn't find the songlist
    if (tbody==null) return;

    sorttable.makeSortable(tbody);
}

/*
  modified by Bill Grundmann
  SortTable
  version 2
  7th April 2007
  Stuart Langridge, http://www.kryogenix.org/code/browser/sorttable/
                    http://www.kryogenix.org/code/browser/sorttable/sorttable.js

  Thanks to many, many people for contributions and suggestions.
  Licenced as X11: http://www.kryogenix.org/code/browser/licence.html
  This basically means: do what you want with it.
*/

var stIsIE = /*@cc_on!@*/false;

sorttable = {
  init: function() {
    // quit if this function has already been called
    if (arguments.callee.done) return;
    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;
    // kill the timer
    if (_timer) clearInterval(_timer);

    if (!document.createElement || !document.getElementsByTagName) return;

    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
    sorttable.clean = 0;
  },

  makeSortable: function(table) {
    // find the real row with headers
    // it's usually at row 0
    // but if newComments() has run, it has been shifted down
    rows=table.rows;
    head=0;
    for (j=0; j<15 && j<rows.length; j++) {
        colHeader=rows[j].cells[0].textContent;
        if (typeof colHeader == 'undefined') {
            colHeader=rows[j].cells[0].text;
            if (typeof colHeader == 'undefined') {
                colHeader=rows[j].cells[0].innerText;
                if (typeof colHeader == 'undefined') {
                    colHeader="";
                }
            }
        }
        if (colHeader=="Date") {
            head = j;
            break;
        }
    }

    // work through each column and add click events
    headrow = table.rows[head].cells;

    for (var i=0; i<headrow.length; i++) {

      // manually override the type with a sorttable_type attribute
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col

        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
        if (mtch) { override = mtch[1]; }
          if (mtch && typeof sorttable["sort_"+override] == 'function') {
            headrow[i].sorttable_sortfunction = sorttable["sort_"+override];
          } else {
            switch (i) {
                case 0:
                case 5:
                    headrow[i].sorttable_sortfunction = sorttable.sort_date;
                    headrow[i].style.color="#0000ff";
                    headrow[i].style.cursor="pointer";
                    headrow[i].style.cursor="hand";
                    break;
                case 1:
                case 4:
                    headrow[i].sorttable_sortfunction = sorttable.sort_alpha;
                    headrow[i].style.color="#0000ff";
                    headrow[i].style.cursor="pointer";
                    headrow[i].style.cursor="hand";
                    break;
                case 2:
                    headrow[i].sorttable_sortfunction = sorttable.sort_paren_pair0;
                    headrow[i].style.color="#0000ff";
                    headrow[i].style.cursor="pointer";
                    headrow[i].style.cursor="hand";
                    break;
                case 3:
                    headrow[i].sorttable_sortfunction = sorttable.sort_paren_pair2;
                    headrow[i].style.color="#0000ff";
                    headrow[i].style.cursor="pointer";
                    headrow[i].style.cursor="hand";
                    break;
                case 6:
                    headrow[i].sorttable_sortfunction = sorttable.sort_heat;
                    headrow[i].style.color="#0000ff";
                    headrow[i].style.cursor="pointer";
                    headrow[i].style.cursor="hand";
                    break;
                default:
                    // skip this column
                    continue;
            }
          }
          // make it clickable to sort
          headrow[i].sorttable_columnindex = i;
          headrow[i].sorttable_tbody = table;

          // add click action
          dean_addEvent(headrow[i],"click", function(e) {

            if (this.className.search(/\bsorttable_sorted\b/) != -1) {
              // if we're already sorted by this column, just
              // reverse the table, which is quicker
              sorttable.reverse(this.sorttable_tbody);
              this.className = this.className.replace('sorttable_sorted',
                                                      'sorttable_sorted_reverse');
              this.removeChild(document.getElementById('sorttable_sortfwdind'));
              sortrevind = document.createElement('span');
              sortrevind.id = "sorttable_sortrevind";
              sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
              this.appendChild(sortrevind);
              return;
            }
            if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {
              // if we're already sorted by this column in reverse, just
              // re-reverse the table, which is quicker
              sorttable.reverse(this.sorttable_tbody);
              this.className = this.className.replace('sorttable_sorted_reverse',
                                                      'sorttable_sorted');
              this.removeChild(document.getElementById('sorttable_sortrevind'));
              sortfwdind = document.createElement('span');
              sortfwdind.id = "sorttable_sortfwdind";
              sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
              this.appendChild(sortfwdind);
              return;
            }

            // remove sorttable_sorted classes
            theadrow = this.parentNode;

            forEach(theadrow.childNodes, function(cell) {
              if (cell.nodeType == 1) { // an element
                cell.className = cell.className.replace('sorttable_sorted_reverse','');
                cell.className = cell.className.replace('sorttable_sorted','');
              }
            });

            if (sorttable.clean==0) {
              // need to do only once, regardless of which column
              sorttable.clean=1;
              // remove extra stuff from table (like song totals, album infos)
              for (var i=0; i<table.rows.length; i++) {
                  if (table.rows[i].cells.length<3) {
                      table.deleteRow(i);
                      i--;
                      continue;
                  }
                  lastComm=rows[i].cells[5].textContent;
                  if (typeof lastComm == 'undefined') {
                      lastComm=rows[i].cells[5].text;
                      if (typeof lastComm == 'undefined') {
                          lastComm=rows[i].cells[5].innerText;
                          if (typeof lastComm == 'undefined') {
                              lastComm="";
                          }
                      }
                  }
                  if (lastComm=="00.00.00") {
                      // this is a collaboration row from mjAlbums
                      table.deleteRow(i);
                      i--;
                      continue;
                  }
              }
            }

            sortfwdind = document.getElementById('sorttable_sortfwdind');
            if (sortfwdind) { sortfwdind.parentNode.removeChild(sortfwdind); }
            sortrevind = document.getElementById('sorttable_sortrevind');
            if (sortrevind) { sortrevind.parentNode.removeChild(sortrevind); }
            sort4wayind = document.getElementById('sorttable_sort4wayind');
            if (sort4wayind) { sort4wayind.parentNode.removeChild(sort4wayind); }

            switch (this.sorttable_sortfunction) {
                case sorttable.sort_paren_pair0:
                    sort4wayind = document.createElement('span');
                    sort4wayind.id = "sorttable_sort4wayind";
                    sort4wayind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
                    this.appendChild(sort4wayind);
                    break;
                case sorttable.sort_paren_pair1:
                    sort4wayind = document.createElement('span');
                    sort4wayind.id = "sorttable_sort4wayind";
                    sort4wayind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';
                    this.appendChild(sort4wayind);
                    break;
                case sorttable.sort_paren_pair2:
                    sort4wayind = document.createElement('span');
                    sort4wayind.id = "sorttable_sort4wayind";
                    sort4wayind.innerHTML = stIsIE ? '&nbsp(<font face="webdings">6</font>)' : '&nbsp;(&#x25BE;)';
                    this.appendChild(sort4wayind);
                    break;
                case sorttable.sort_paren_pair3:
                    sort4wayind = document.createElement('span');
                    sort4wayind.id = "sorttable_sort4wayind";
                    sort4wayind.innerHTML = stIsIE ? '&nbsp(<font face="webdings">5</font>)' : '&nbsp;(&#x25B4;)';
                    this.appendChild(sort4wayind);
                    break;
                default:
                    this.className += ' sorttable_sorted';
                    sortfwdind = document.createElement('span');
                    sortfwdind.id = "sorttable_sortfwdind";
                    sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';
                    this.appendChild(sortfwdind);
                    break;
            }

            // build an array to sort. This is a Schwartzian transform thing,
            // i.e., we "decorate" each row with the actual sort key,
            // sort based on the sort keys, and then put the rows back in order
            // which is a lot faster because you only do getInnerText once per row
            row_array = [];
            col = this.sorttable_columnindex;
            rows = this.sorttable_tbody.rows;
            for (var j=1; j<rows.length; j++) {
              row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
            }
            /* If you want a stable sort, uncomment the following line */
            sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
            /* and comment out this one */
            //row_array.sort(this.sorttable_sortfunction);

            tb = this.sorttable_tbody;
            for (var j=1; j<row_array.length; j++) {
              tb.appendChild(row_array[j][1]);
            }

            switch (this.sorttable_sortfunction) {
                case sorttable.sort_paren_pair0:
                    this.sorttable_sortfunction=sorttable.sort_paren_pair1;
                    break;
                case sorttable.sort_paren_pair1:
                    this.sorttable_sortfunction=sorttable.sort_paren_pair2;
                    break;
                case sorttable.sort_paren_pair2:
                    this.sorttable_sortfunction=sorttable.sort_paren_pair3;
                    break;
                case sorttable.sort_paren_pair3:
                    this.sorttable_sortfunction=sorttable.sort_paren_pair0;
                    break;
                default:
                    break;
            }

            delete row_array;
            });
        }
    }
  },

  getInnerText: function(node) {
    // gets the text we want to use for sorting for a cell.
    // strips leading and trailing whitespace.
    // this is *not* a generic getInnerText function; it's special to sorttable.
    // for example, you can override the cell text with a customkey attribute.
    // it also gets .value for <input> fields.

    hasInputs = (typeof node.getElementsByTagName == 'function') &&
                 node.getElementsByTagName('input').length;

    if (node.getAttribute("sorttable_customkey") != null) {
      return node.getAttribute("sorttable_customkey");
    }
    else if (typeof node.textContent != 'undefined' && !hasInputs) {
      return node.textContent.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.innerText != 'undefined' && !hasInputs) {
      return node.innerText.replace(/^\s+|\s+$/g, '');
    }
    else if (typeof node.text != 'undefined' && !hasInputs) {
      return node.text.replace(/^\s+|\s+$/g, '');
    }
    else {
      switch (node.nodeType) {
        case 3:
          if (node.nodeName.toLowerCase() == 'input') {
            return node.value.replace(/^\s+|\s+$/g, '');
          }
        case 4:
          return node.nodeValue.replace(/^\s+|\s+$/g, '');
          break;
        case 1:
        case 11:
          var innerText = '';
          for (var i = 0; i < node.childNodes.length; i++) {
            innerText += sorttable.getInnerText(node.childNodes[i]);
          }
          return innerText.replace(/^\s+|\s+$/g, '');
          break;
        default:
          return '';
      }
    }
  },

  reverse: function(tbody) {
    // reverse the rows in a tbody
    newrows = [];
    for (var i=1; i<tbody.rows.length; i++) {
      newrows[newrows.length] = tbody.rows[i];
    }
    for (var i=newrows.length-1; i>=0; i--) {
       tbody.appendChild(newrows[i]);
    }
    delete newrows;
  },

  /* sort functions
     each sort function takes two parameters, a and b
     you are comparing a[0] and b[0] */

  sort_alpha: function(a,b) {
    aa = a[0].toLowerCase();
    bb = b[0].toLowerCase();
    if (aa<bb) return -1;
    if (aa==bb) return 0;
    return 1;
  },

  /* special sort of number1(number2) */
  /* sort on number1 */
  sort_paren_pair0: function(a,b) {
    aa = parseFloat(a[0].replace(/\([-0-9]*\)/,''));
    bb = parseFloat(b[0].replace(/\([-0-9]*\)/,''));
    if (isNaN(aa)) aa = -1;
    if (isNaN(bb)) bb = -1;
    if (aa==bb) {
      // tie, use sort of number2
      aa = parseFloat(a[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
      bb = parseFloat(b[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
      if (isNaN(aa)) aa = -1;
      if (isNaN(bb)) bb = -1;
    }
    return bb-aa;
  },
  /* sort on number1 of number1(number2) reverse */
  sort_paren_pair1: function(a,b) {
    aa = parseFloat(a[0].replace(/\([-0-9]*\)/,''));
    bb = parseFloat(b[0].replace(/\([-0-9]*\)/,''));
    if (isNaN(aa)) aa = 999999;
    if (isNaN(bb)) bb = 999999;
    if (aa==bb) {
      // tie, use sort of number2 reverse
      aa = parseFloat(a[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
      bb = parseFloat(b[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
      if (isNaN(aa)) aa = 999999;
      if (isNaN(bb)) bb = 999999;
    }
    return aa-bb;
  },
  /* sort on number2 of number1(number2) */
  sort_paren_pair2: function(a,b) {
    aa = parseFloat(a[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
    bb = parseFloat(b[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
    if (isNaN(aa)) aa = -1;
    if (isNaN(bb)) bb = -1;
    if (aa==bb) {
      // tie, use sort of number1
      aa = parseFloat(a[0].replace(/\([-0-9]*\)/,''));
      bb = parseFloat(b[0].replace(/\([-0-9]*\)/,''));
      if (isNaN(aa)) aa = -1;
      if (isNaN(bb)) bb = -1;
    }
    return bb-aa;
  },
  /* sort on number2 of number1(number2) reverse */
  sort_paren_pair3: function(a,b) {
    aa = parseFloat(a[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
    bb = parseFloat(b[0].replace(/[-0-9.]*/,'').replace(/[-\(\)]/g,'').substring(1,99));
    if (isNaN(aa)) aa = 999999;
    if (isNaN(bb)) bb = 999999;
    if (aa==bb) {
      // tie, use sort of number1 reverse
      aa = parseFloat(a[0].replace(/\([-0-9]*\)/,''));
      bb = parseFloat(b[0].replace(/\([-0-9]*\)/,''));
      if (isNaN(aa)) aa = 999999;
      if (isNaN(bb)) bb = 999999;
    }
    return aa-bb;
  },
  /* special sort on "heat" level from newComment script */
  sort_heat: function(a,b) {
    aa = a[0].toLowerCase();
    bb = b[0].toLowerCase();
    if (aa=="on fire") aa="0"+aa;
    else if (aa=="hot"    ) aa="1"+aa;
    else if (aa=="warmer" ) aa="2"+aa;
    else if (aa=="warm"   ) aa="3"+aa;
    else if (aa=="cool"   ) aa="4"+aa;
    else if (aa=="cooler" ) aa="5"+aa;
    if (bb=="on fire") bb="0"+bb;
    else if (bb=="hot"    ) bb="1"+bb;
    else if (bb=="warmer" ) bb="2"+bb;
    else if (bb=="warm"   ) bb="3"+bb;
    else if (bb=="cool"   ) bb="4"+bb;
    else if (bb=="cooler" ) bb="5"+bb;
    if (aa<bb) return -1;
    if (aa==bb) return 0;
    return 1;
  },

  sort_date: function(b,a) {
    mtch = a[0].match(sorttable.DATE_RE);
    if (mtch==null) {
      dt1 = '999999';
    } else {
      y = mtch[3]; d = mtch[2]; m = mtch[1];
      if (m.length == 1) m = '0'+m;
      if (d.length == 1) d = '0'+d;
      dt1 = y+m+d;
    }
    mtch = b[0].match(sorttable.DATE_RE);
    if (mtch==null) {
      dt2 = '999999';
    } else {
      y = mtch[3]; d = mtch[2]; m = mtch[1];
      if (m.length == 1) m = '0'+m;
      if (d.length == 1) d = '0'+d;
      dt2 = y+m+d;
    }
    if (dt1<dt2) return -1;
    if (dt1==dt2) return 0;
    return 1;
  },

  shaker_sort: function(list, comp_func) {
    // A stable sort function to allow multi-level sorting of data
    // see: http://en.wikipedia.org/wiki/Cocktail_sort
    // thanks to Joseph Nahmias
    var b = 0;
    var t = list.length - 1;
    var swap = true;

    while(swap) {
        swap = false;
        for(var i = b; i < t; ++i) {
            if (comp_func(list[i], list[i+1]) > 0) {
                var q = list[i]; list[i] = list[i+1]; list[i+1] = q;
                swap = true;
            }
        } // for
        t--;

        if (!swap) break;

        for(var i = t; i > b; --i) {
            if (comp_func(list[i], list[i-1]) < 0) {
                var q = list[i]; list[i] = list[i-1]; list[i-1] = q;
                swap = true;
            }
        } // for
        b++;

    } // while(swap)
  }
}

/* ******************************************************************
   Supporting functions: bundled here to avoid depending on a library
   ****************************************************************** */

// Dean Edwards/Matthias Miller/John Resig

/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", sorttable.init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            sorttable.init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            sorttable.init(); // call the onload handler
        }
    }, 10);
}

// written by Dean Edwards, 2005
// with input from Tino Zijdel, Matthias Miller, Diego Perini

// http://dean.edwards.name/weblog/2005/10/add-event/

function dean_addEvent(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else {
        // assign each event handler a unique ID
        if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
        // create a hash table of event types for the element
        if (!element.events) element.events = {};
        // create a hash table of event handlers for each element/event pair
        var handlers = element.events[type];
        if (!handlers) {
            handlers = element.events[type] = {};
            // store the existing event handler (if there is one)
            if (element["on" + type]) {
                handlers[0] = element["on" + type];
            }
        }
        // store the event handler in the hash table
        handlers[handler.$$guid] = handler;
        // assign a global event handler to do all the work
        element["on" + type] = handleEvent;
    }
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;

function removeEvent(element, type, handler) {
    if (element.removeEventListener) {
        element.removeEventListener(type, handler, false);
    } else {
        // delete the event handler from the hash table
        if (element.events && element.events[type]) {
            delete element.events[type][handler.$$guid];
        }
    }
};

function handleEvent(event) {
    var returnValue = true;
    // grab the event object (IE uses a global event object)
    event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        if (this.$$handleEvent(event) === false) {
            returnValue = false;
        }
    }
    return returnValue;
};

function fixEvent(event) {
    // add W3C standard event methods
    event.preventDefault = fixEvent.preventDefault;
    event.stopPropagation = fixEvent.stopPropagation;
    return event;
};
fixEvent.preventDefault = function() {
    this.returnValue = false;
};
fixEvent.stopPropagation = function() {
  this.cancelBubble = true;
}

// Dean's forEach: http://dean.edwards.name/base/forEach.js
/*
    forEach, version 1.0
    Copyright 2006, Dean Edwards
    License: http://www.opensource.org/licenses/mit-license.php
*/

// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
    Array.forEach = function(array, block, context) {
        for (var i = 0; i < array.length; i++) {
            block.call(context, array[i], i, array);
        }
    };
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
    for (var key in object) {
        if (typeof this.prototype[key] == "undefined") {
            block.call(context, object[key], key, object);
        }
    }
};

// character enumeration
String.forEach = function(string, block, context) {
    Array.forEach(string.split(""), function(chr, index) {
        block.call(context, chr, index, string);
    });
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
    if (object) {
        var resolve = Object; // default
        if (object instanceof Function) {
            // functions have a "length" property
            resolve = Function;
        } else if (object.forEach instanceof Function) {
            // the object implements a custom forEach method so use that
            object.forEach(block, context);
            return;
        } else if (typeof object == "string") {
            // the object is a string
            resolve = String;
        } else if (typeof object.length == "number") {
            // the object is array-like
            resolve = Array;
        }
        resolve.forEach(object, block, context);
    }
};
