	/************************************************************************************************************
	(C) www.dhtmlgoodies.com, November 2005
	
	This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	
	
	Terms of use:
	You are free to use this script as long as the copyright message is kept intact. However, you may not
	redistribute, sell or repost it without our permission.
	
	Thank you!
	
	www.dhtmlgoodies.com
	Alf Magne Kalleland

	April 2008 (JZK) - Very useful script, unfortunately though designed to be effective with simple conventional tables
                         Script adapted to take into account where table header(s) begin, row highlighting, exception handling, etc
                         Depending on the volumne of data, IE browsers process script very slowly, short coming of IE unfortunately.
	
	************************************************************************************************************/
		




	function sortNumeric(a,b){
		

    
      
  		a = a.replace(/,/,'.');
	  	b = b.replace(/,/,'.');

      a = a.replace('/','');
      b = b.replace('/','');

  		if(a.indexOf('/')>=0)a = eval(a);
	  	if(b.indexOf('/')>=0)b = eval(b);


      r = a/1 - b/1;

  		return a/1 - b/1;


	}
	

	function sortString(a, b) {

    //alert('string : '+a+' : '+b);
	  if ( a.toUpperCase() < b.toUpperCase() ) return -1;
	  if ( a.toUpperCase() > b.toUpperCase() ) return 1;
	  return 0;
	}
		
	function sortTable()
	{
		if(!tableWidget_okToSort)return;
		tableWidget_okToSort = false;
		/* Getting index of current column */
		var obj = this;
		var indexThis = 0; //0
	      var content ='';
		//alert('tag name '+obj.tagName);
		while(obj.previousSibling){
			obj = obj.previousSibling;
			if(obj.tagName=='TH')indexThis++;		
		}
		//alert('indexThis '+indexThis);
		if(this.getAttribute('direction') || this.direction){
			direction = this.getAttribute('direction');
			if(navigator.userAgent.indexOf('Opera')>=0)direction = this.direction;
			if(direction=='ascending'){
				direction = 'descending';
				this.setAttribute('direction','descending');
				this.direction = 'descending';	
			}else{
				direction = 'ascending';
				this.setAttribute('direction','ascending');		
				this.direction = 'ascending';		
			}
		}else{
			direction = 'ascending';
			this.setAttribute('direction','ascending');
			this.direction = 'ascending';
		}
		
		var tableObj = this.parentNode.parentNode.parentNode;
		var tBody = tableObj.getElementsByTagName('TBODY')[0];


		
		var widgetIndex = tableObj.getAttribute('tableIndex');
		if(!widgetIndex)widgetIndex = tableObj.tableIndex;
		
		if(currentColumn)currentColumn.className='';
		//alert('col index? '+indexThis);
		//document.getElementById('col' + widgetIndex + '_' + (indexThis+1)).className='highlightedColumn'; //1
		currentColumn = document.getElementById('col' + widgetIndex + '_' + (indexThis+1)); //1

			
		var sortMethod = tableWidget_arraySort[widgetIndex][indexThis]; // N = numeric, S = String
		if(activeColumn[widgetIndex] && activeColumn[widgetIndex]!=this){
			if(activeColumn[widgetIndex])activeColumn[widgetIndex].removeAttribute('direction');			
		}

		activeColumn[widgetIndex] = this;
		
		var cellArray = new Array();
		var cellObjArray = new Array();
            var index = 0;
		//alert('rows '+tableObj.rows.length);
            var totalColumns = tableObj.rows[tableHeaderOffSet].cells.length;
		//alert('cols '+ totalColumns);

            for(var cellNo=0;cellNo<totalColumns;cellNo++)
            {
              //if (tableObj.rows[tableHeaderOffSet -2].cells[cellNo].className=='highlightedColumn') // -1
		  if (tableObj.rows[tableHeaderOffSet -2].cells[cellNo].className=='highlightedColumnAsc' || tableObj.rows[tableHeaderOffSet -2].cells[cellNo].className=='highlightedColumnDsc') // -1
              {
 		    index = cellNo;
                //alert('highlighted column '+index);
                break;
              }
            }
            //alert('before loop start');
            
            var totalRows = tableObj.rows.length;
		for(var no=tableHeaderOffSet - 1;no<totalRows;no++) // -0
            {
             try 
              { 
		  if ((tableObj.rows[no].cells[indexThis].tagName != 'TH')  &&  (tableObj.rows[no].cells[indexThis].id != 'ignore') && (tableObj.rows[no].cells[indexThis].innerHTML != '')) //this ignores any additional table headers midway through table - however, dumps them at the bottom of page, will revisit
              {  
			content = tableObj.rows[no].cells[indexThis].innerHTML+'';
			cellArray.push(content);
                  //alert('alert 1');
			cellObjArray.push(tableObj.rows[no].cells[indexThis]);
                  //alert('alert 2');





                  /*if (tableObj.rows[no].cells[indexThis] != null)
                  { 
                    tableObj.rows[no].cells[indexThis].className='highlightedColumn';
                  }
                  if (indexThis != index)
                  {
			  tableObj.rows[no].cells[index].className='';
                  } */


		  }
             }
             catch (e)
             {
             /* if (tableObj.rows[no].cells[indexThis] != null)
              {
                tableObj.rows[no].cells[indexThis].className='highlightedColumn';
              } */


             }
		}
            //alert('after loop end : '+cellArray);


    
		if(sortMethod=='N'){
                  try
                  { 
                    
			              cellArray = cellArray.sort(sortNumeric);
                  }
                  catch (e)
                  {
                     cellArray = cellArray.sort(sortString);
                  } 
		}
    else
    {
      
			cellArray = cellArray.sort(sortString);
		}
		
		if(direction=='descending'){
			for(var no=cellArray.length;no>=0;no--){
				for(var no2=0;no2<cellObjArray.length;no2++){
					if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
						cellObjArray[no2].setAttribute('allreadySorted','1');	
						tBody.appendChild(cellObjArray[no2].parentNode);				
					}				
				}			
			}
		}else{
			for(var no=0;no<cellArray.length;no++){
				for(var no2=0;no2<cellObjArray.length;no2++){
					if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
						cellObjArray[no2].setAttribute('allreadySorted','1');	
						tBody.appendChild(cellObjArray[no2].parentNode);				
					}				
				}			
			}				
		}
		
		for(var no2=0;no2<cellObjArray.length;no2++){
			cellObjArray[no2].removeAttribute('allreadySorted');	
		}


	      for(var no3=tableHeaderOffSet -1;no3<totalRows;no3++) // 0
            {
		  tableObj.rows[no3].className='r'+eval(no3 % 2);	
            } 

           /* for(var cellNo=0;cellNo<totalColumns;cellNo++)
            {
              if (tableObj.rows[tableHeaderOffSet -1].cells[cellNo].className=='highlightedColumn')
              {
 		    index = cellNo;
                alert('highlighted column '+index);
                break;
              }
            } */


            if (indexThis != index)
            {
		  tableObj.rows[tableHeaderOffSet - 2].cells[index].className=''; // -1
            } 


            if (direction=='descending')
            {
	        tableObj.rows[tableHeaderOffSet - 2].cells[indexThis].className='highlightedColumnDsc'; // -1
              //alert(tableObj.rows[tableHeaderOffSet - 2].cells[indexThis].innerHTML); // = tableObj.rows[tableHeaderOffSet - 2].cells[indexThis].innerHTML + 'xx';
            }
		else
            {
		  tableObj.rows[tableHeaderOffSet - 2].cells[indexThis].className='highlightedColumnAsc';
            }
            //alert('index '+index);


		tableWidget_okToSort = true;
		
		
	}
	function initSortTable(objId,sortArray)
	{
		var obj = document.getElementById(objId);
		obj.setAttribute('tableIndex',tableWidget_tableCounter);
		obj.tableIndex = tableWidget_tableCounter;
		tableWidget_arraySort[tableWidget_tableCounter] = sortArray;
		var tHead = obj.getElementsByTagName('TR')[tableHeaderOffSet-1];
		var cells = tHead.getElementsByTagName('TH');
                //alert('cells '+cells.length);   
		for(var no=0;no<cells.length;no++){
			if(sortArray[no]){
                                //alert('col? '+no); 
				cells[no].onclick = sortTable;	
			}else{
				cells[no].style.cursor = 'default';	
			}
		}	
	
		//for(var no2=0;no2<sortArray.length;no2++){	/* Right align numeric cells */
			//if(sortArray[no2] && sortArray[no2]=='N')obj.rows[0].cells[no2].style.textAlign='right'; 
                        //  if(sortArray[no2] && sortArray[no2]=='N')obj.rows[tableHeaderOffSet].cells[no2].style.textAlign='right'; 
		//}		
		
		tableWidget_tableCounter++;
	}
