//Inspired from http://www.geocities.com/sc_hanyu/javascript/sorttable.html
//This javascript is more specialized for the portal context.
//It will require more information to be initialized, but will also
//provide more sorting flexibility.

//initTable : prepares the table for futur sorting
//@param tableID : a string representing the id tag of the table to init
//@param types : an array representing the types of the different columns
//               use to decide how to compare when sorting.
//@param keepFormating : a boolean indicating if we should move only the content
//                       or also its formating when sorting
//@param allowedArray : an optional array of boolean telling the script
//                      what columns is sorting allowed on.
//Our goal here is to attach new information to the table object.
//This script will only work in specific conditions
// 1. No colspans in the table
// 2. Title row is allways the first row
function initTable(tableID, types, keepFormatting, allowedArray){
    table = FIND(tableID);
    
    //If the table was not found or the id does not correspond to a table.
    if(table == null || table.tagName != "TABLE"){
        return;
    }
    
    table.portalAllowedArray = allowedArray;
    table.portalKeepFormating = keepFormatting;
    table.portalTypes = types;
    
    table.portalSorted = false;
    
    //Table must have at least one row
    if (table.rows.length < 1){
        return;
    }
    
    //Table must have at lest one column
    if (table.rows[0].cells.length < 1){
        return;
    }
    
    //Prepare the title cells
    table.portalOriginalTitleCells = new Array(table.rows[0].cells.length);

    for(i = 0; i < table.rows[0].cells.length; i ++){
        table.portalOriginalTitleCells[i] = table.rows[0].cells[i].innerHTML;
    }
    
    redrawTitles(table);
}

function sortTable(tableID, colNum){
    table = FIND(tableID);
    
    //If the table was not found or the id does not correspond to a table.
    if(table == null || table.tagName != "TABLE"){
        return;
    }
    
    var sortCol = colNum;
    var sortDir = "down";
    
    if(table.portalSorted && colNum == table.portalSortedCol){
        if(table.portalSortedDir == "up"){
            sortDir = "down";
        } else {
            sortDir = "up";
        }
    }
    
    table.portalSortedCol = sortCol;
    table.portalSortedDir = sortDir;
    table.portalSorted = true;
    
    type = table.portalTypes[sortCol];
    
    //Now that everything is known, do the sorting
    for(i = 1; i < table.rows.length; i ++){
        for(j = i; j > 1; j --){
            if(sortDir == "down"){
                if(portalCompare(table.rows[j].cells[sortCol].innerHTML, table.rows[j - 1].cells[sortCol].innerHTML, type) < 0 ){
                    exchangeTableRows(table, j, j-1, table.portalKeepFormating);
                }
            } else {
                if(portalCompare(table.rows[j].cells[sortCol].innerHTML, table.rows[j - 1].cells[sortCol].innerHTML, type) > 0 ){
                    exchangeTableRows(table, j, j-1, table.portalKeepFormating);
                }
            }
        }
    }
    
    //Redraw the titles (to set the arrow correctly
    redrawTitles(table);
}

function portalCompare(obj1, obj2, type){
    if(type == "text"){
    	  if(obj1 > obj2){
    	      return 1;
    	  } else if(obj1 == obj2){
    	      return 0;
    	  } else {
    	      return -1;
    	  }
    } else if(type == "double"){
    	  //Invalid data checks
        if(isNaN(obj1) && isNaN(obj2)){
            return 0;
        } else if(!isNaN(obj1) && isNaN(obj2)){
            return 1;
        } else if(isNaN(obj1) && !isNaN(obj2)){
        	   return -1;
        }
        
        n1 = parseFloat(obj1);
        n2 = parseFloat(obj2);
        
        if(n1 > n2){
    	      return 1;
    	  } else if(n1 == n2){
    	      return 0;
    	  } else {
    	      return -1;
    	  }
    } else if(type == "integer"){
        //Invalid data checks
        if(isNaN(obj1) && isNaN(obj2)){
            return 0;
        } else if(!isNaN(obj1) && isNaN(obj2)){
            return 1;
        } else if(isNaN(obj1) && !isNaN(obj2)){
        	   return -1;
        }
        
        n1 = parseInt(obj1);
        n2 = parseInt(obj2);
        
        if(n1 > n2){
    	      return 1;
    	  } else if(n1 == n2){
    	      return 0;
    	  } else {
    	      return -1;
    	  }
    } else if(type == "date"){
    	  cal1 = new CalendarObject();
    	  cal1.parseDate(obj1);
    	  
    	  cal2 = new CalendarObject();
    	  cal2.parseDate(obj2);
    	  
    	  if(cal1.currentDate > cal2.currentDate){
    	      return 1;
    	  } else if(cal1.currentDate == cal2.currentDate){
    	      return 0;
    	  } else {
    	      return -1;
    	  }
    } else if(type == "doubleText"){
    	  //Invalid data checks
	    var phoneNumberDelimiters = "€%()- ";
	    var validWorldPhoneChars = phoneNumberDelimiters + "&nbsp;";
        n1 = stripCharsInBag(obj1,validWorldPhoneChars);
	    n2 = stripCharsInBag(obj2,validWorldPhoneChars);
        n1 = parseFloat(n1);
        n2 = parseFloat(n2);
        if(n1 > n2){
    	      return 1;
    	  } else if(n1 == n2){
    	      return 0;
    	  } else {
    	      return -1;
    	  }
    }
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's <b style="color:black;background-color:#ff9999">characters</b> one by one.
    // If character is <b style="color:black;background-color:#ff66ff">not</b> in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function exchangeTableRows(table, row1, row2, keepFormatting){
    if(keepFormatting){
    	  for(k = 0 ; k < table.rows[0].cells.length; k ++){
    	      temp = table.rows[row1].cells[k].innerHTML;
            table.rows[row1].cells[k].innerHTML = table.rows[row2].cells[k].innerHTML;
            table.rows[row2].cells[k].innerHTML = temp;
            
            temp = table.rows[row1].cells[k].className;
            table.rows[row1].cells[k].className = table.rows[row2].cells[k].className;
            table.rows[row2].cells[k].className = temp;
    	  }
    } else {
        for(k = 0 ; k < table.rows[0].cells.length; k ++){
            temp = table.rows[row1].cells[k].innerHTML;
            table.rows[row1].cells[k].innerHTML = table.rows[row2].cells[k].innerHTML;
            table.rows[row2].cells[k].innerHTML = temp;
        }
    }
}

function redrawTitles(table){
	
    for(i = 0; i < table.rows[0].cells.length; i ++){
    	  if(table.portalAllowedArray != null){
    	      if(!table.portalAllowedArray[i]){
    	          continue;
    	      }
    	  }
        //Add js call
        innerHTML = "<span onClick=\"sortTable('" + table.id + "', " + i + ")\" onMouseOver=\"this.style.cursor = 'pointer'; this.style.cursor = 'hand';\">";
        innerHTML += table.portalOriginalTitleCells[i];
        if(table.portalSorted && table.portalSortedCol != null && table.portalSortedCol == i){
            if(table.portalSortedDir == "up"){
                innerHTML += "&nbsp;&uarr;";
            } else {
                innerHTML += "&nbsp;&darr;";
            }
        }
        innerHTML += "</span>";
        table.rows[0].cells[i].innerHTML = innerHTML;
    }
}