var baseform;
var default_year = '2000';
var default_time = '0000';
var true_char = 'Y';
var false_char = 'N';
var formHasChanged = false;
var ignoreSaveCheck = false;
var minDate = new Date(1970, 1, 1);
var maxDate = new Date(2079, 6, 6);
//--START SORTING STUFF
//Sorting 
var currentCol = 0;
var previousCol = -1;
var direction = 0;
var prevTable = -1;

//comparison functions for determining sort order based on the data type
function CompareAlpha(a, b) {
	if (a[currentCol] < b[currentCol]) { return -1; }
	if (a[currentCol] > b[currentCol]) { return 1; }
	return 0;
}

function CompareAlphaIgnore(a, b) {
	strA = a[currentCol].toLowerCase();
	strB = b[currentCol].toLowerCase();
	if (strA < strB) { return -1; }
	else {
		if (strA > strB) { return 1; }
		else { return 0; }
	}
}

function CompareDate(a, b) {
	// this one works with date formats conforming to Javascript specifications, e.g. m/d/yyyy
	datA = new Date(a[currentCol]);
	datB = new Date(b[currentCol]);
	if (datA < datB) { return -1; }
	else {
		if (datA > datB) { return 1; }
		else { return 0; }
	}
}

function CompareNumeric(a, b) {
	//window.alert ("CompareNumeric");
	numA = a[currentCol]
	numB = b[currentCol]
	if (isNaN(numA)) { return 0;}
	else {
		if (isNaN(numB)) { return 0; }
		else { return numA - numB; }
	}
}
function sort_user_listing(myCol, myType) {
    var avaTable= document.getElementById('tblMain').getElementsByTagName("TBODY")[0];
    sort_table(avaTable,myCol,myType,1);
    return false;
}

//Table sorting function
function sort_table(mySource,myCol,myType,currTable){
    //Reset the "ugh" globals if the tables have changes
    if(currTable != prevTable ){
        currentCol = 0;
        previousCol = -1;
        direction = 0;
        prevTable = currTable
    }
    var rows = mySource.getElementsByTagName("TR");
	var myRows = rows.length
	var myCols = rows[0].cells.length;
	currentCol = myCol
	myArray = new Array(myRows)
	for (i=1; i < myRows; i++) {
		myArray[i-1] = new Array(myCols+2)
		for (j=0; j < myCols; j++) {
			myArray[i-1][j] = rows[i].cells[j].innerHTML;
		}
		myArray[i-1][myCols] = rows[i].onclick
		myArray[i-1][myCols+1] = rows[i].cells[0].style.textDecoration
	}

	if (myCol == previousCol ){
	    // Re-write the table contents in reverse
	    var k = 1;
	    for (i=myRows-2; i >= 0; i--) {
	    	for (j=0; j < myCols; j++) {
	    		mySource.rows[k].cells[j].innerHTML = myArray[i][j]
	    	    mySource.rows[k].cells[j].style.textDecoration = myArray[i][myCols+1]
	    	}
	    	mySource.rows[k].onclick = myArray[i][myCols]
	    	k++
	    }
	        var img = mySource.rows[0].cells[myCol].getElementsByTagName("img")[0];
	        mySource.rows[0].cells[myCol].removeChild(img);
	        img = new Image();
	        if(direction == "asc"){
	            img.src = "images/sort_desc.gif";
	            direction = "desc"
	        }
	        else{
	            img.src = "images/sort_asc.gif";
	            direction = "asc"
	        }
	        mySource.rows[0].cells[myCol].appendChild(img);
	        
	}
	else {
		switch (myType) {
			case "a":
				myArray.sort(CompareAlpha);
				break;
			case "ai":
				myArray.sort(CompareAlphaIgnore);
				break;
			case "d":
				myArray.sort(CompareDate);
				break;
			case "n":
				myArray.sort(CompareNumeric);
				break;
			default:
				myArray.sort()
		}
	    for (i=1; i < myRows; i++) {
	    	for (j=0; j < myCols; j++) {
	    		mySource.rows[i].cells[j].innerHTML = myArray[i-1][j]
	    	    mySource.rows[i].cells[j].style.textDecoration = myArray[i-1][myCols+1]
	    	}
	    	mySource.rows[i].onclick = myArray[i-1][myCols]
	    }
	    img = new Image();
	    img.src = "images/sort_asc.gif";
	    mySource.rows[0].cells[myCol].appendChild(img)
	    direction = "asc";
	    if(previousCol != -1){
	        var img2 = mySource.rows[0].cells[previousCol].getElementsByTagName("img")[0];
	        mySource.rows[0].cells[previousCol].removeChild(img2);
	    }
	}
	previousCol = myCol; // remember the current sort column for the next pass
	//Ajax call to set the sort direction and column 
        if(currTable == 1){
            xmlHttp=GetXmlHttpObject()
	        if (xmlHttp==null){
                alert ("Browser does not support HTTP Request")
                return
            }
	        var url="ajax.aspx"
	        url=url+"?sortColumn="+myCol
	        url=url+"&sortType="+myType
	        url=url+"&sortDirection="+direction
	        url=url+"&action=set_sort"
	        url=url+"&sid="+Math.random()
	        xmlHttp.onreadystatechange=function(){};
	        xmlHttp.open("GET",url,true)
	        xmlHttp.send(null)
        }	
	return false;
}
function GetXmlHttpObject(){
    var xmlHttp=null;
    try {
    // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    } catch (e) {
        //Internet Explorer
        try {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}


//--END SORTING STUFF

function save_check() {


  var curElem;
  
  if(!ignoreSaveCheck)
  {
    if(!formHasChanged)
    {
      for(var i=0; i<baseform.elements.length; i++)
      {
        curElem = baseform.elements[i];
        if(curElem.type!='hidden' &&
           (curElem.value!=null && curElem.defaultValue!=null && curElem.value!=curElem.defaultValue) ||
           (curElem.selectedIndex!=null && has_cbo_changed(curElem)) ||
           (curElem.checked!=null && curElem.defaultChecked!=null && curElem.checked != curElem.defaultChecked))
        {
          formHasChanged = true;
          break;
        }
      }
    }
    if(formHasChanged)
    {
      if(confirm('Do you want to save your changes?'))
      {
        for(var i=0; i<baseform.elements.length; i++)
        {
          curElem = baseform.elements[i];
          if(curElem.type=='submit' && curElem.value=='Save')
          {
            curElem.click();
            break;
          }
        }
      }
    }
  }
}

function has_cbo_changed(cbo)
{
  var retval = !cbo.options[cbo.selectedIndex].defaultSelected;
  var cboHadDefaultSelection = false;
  // Make sure that the default selected value was set to start with
  if(retval)
  {
    for(var i=0; i<cbo.options.length; i++)
    {
      if(cbo.options[i].defaultSelected)
      {
        cboHadDefaultSelection = true;
        break;
      }
    }
    if(!cboHadDefaultSelection && cbo.selectedIndex==0)
      retval = false;
  }
  return retval;
}

function setIgnoreSaveCheck()
{
  ignoreSaveCheck = true;
  return true;
}

function get_boolean(textField)
{
  return (textField!=null && textField.value==true_char);
}

function get_decimal(textField, numDec)
{
  var newVal = 0;
  
  if(textField!=null)
  {
    newVal = get_all(textField, parseFloat(textField.value), false)
    if(newVal!=0)
    {
      var i;
      var decimals = '.';
      var curval = newVal.toString();
      var pos = curval.lastIndexOf('.');
      var maxNumDigitsBeforeDecimal = textField.maxLength - numDec - 1;

      for(i=0; i<numDec; i++)
        decimals += '0';
      if(pos<0)
      {
        if(curval.length > maxNumDigitsBeforeDecimal)   // Remove digits to the left of the decimal point if needed
          curval = curval.substr(curval.length - maxNumDigitsBeforeDecimal);
        textField.value = curval + decimals;
      }
      else
      {
        if(pos > maxNumDigitsBeforeDecimal)   // Remove digits to the left of the decimal point if needed
          curval = curval.substr(pos-maxNumDigitsBeforeDecimal);
        var maxlen = pos+numDec+1;
        if(maxlen<=curval.length)   //  Remove digits to the right of the decimal point if needed
          textField.value = curval.substr(0, maxlen);
        else
          textField.value = curval + decimals.substr(curval.length-pos);
      }
      newVal = parseFloat(textField.value);
    }
    else{
        textField.value = "";
    }
  }
  return newVal;
}

function get_float(textField)
{
  var newVal = 0;
  if(textField!=null)
    newVal = get_number(textField, parseFloat(textField.value));
  return newVal
}


function get_int(textField)
{
  var newVal = 0;
  if(textField!=null)
    newVal = get_number(textField, parseInt(textField.value, 10));
  return newVal;
}

function get_date(textField)
{
  var retval = 0;
  var newDate;
  
  
  if(textField!=null)
  {
    // Fix the year as parse does not do a good job
    var curValue = textField.value;
    var lastSlash = curValue.lastIndexOf('/');
    if(curValue.length>2)
    {
      if(lastSlash<3)
        curValue = curValue + '/' + default_year;
      else
      {
        if(lastSlash == curValue.length-1)
          curValue = curValue + default_year;
        else
        {
          var curYear = curValue.substr(lastSlash+1);
          curValue = curValue.substr(0, lastSlash+1) + 
                     default_year.substr(0, default_year.length - curYear.length) + 
                     curYear;
        }
      }
    }
    newDate = Date.parse(curValue);
    if(newDate < minDate || newDate > maxDate)
      newDate = NaN;
    retval = get_all(textField, newDate, false);
    if(retval!=0)
    {
      var newDate = new Date(retval);
      var fullYear = newDate.getFullYear();
      textField.value = (newDate.getMonth()+1) + '/' + newDate.getDate() + '/' + fullYear;
      textField.defaultValue = textField.value;
    }
  }
  return retval;
}

function get_time(textField)
{
  var retval = 0;
  if(textField!=null)
  {
    var intVal = parseInt(textField.value, 10)
    if(intVal >= 2400)
      intVal = NaN
    var retval = get_all(textField, intVal, false);
    if(retval!=0)
    {
      textField.value = default_time.substr(0, default_time.length - textField.value.length) +
                        textField.value;
      textField.defaultValue = textField.value;
    }
  }
  return retval;
}


function get_number(textField, curValue)
{
  return get_all(textField, curValue, true);
}

function get_all(textField, curValue, overwriteVal)
{
  var retval = 0;
  if(textField!=null && textField.value != '')
  {
    if(isNaN(curValue))
    {
      if(textField.defaultValue=='')
        textField.value = '';
      else
      {
        textField.value = textField.defaultValue;
        retval = textField.defaultValue;
        formHasChanged = true;
      }
    }
    else
    {
      retval = Math.abs(curValue);
      if(overwriteVal)
        textField.value = retval;    
      textField.defaultValue = textField.value;
      formHasChanged = true;
    }
  }
  return retval;
}

function open_help()
{
  inline_help('','F1000');
}

function inline_help(inanchortag, indocfile)
{
  var anchortag = inanchortag;
  var docfile = indocfile;

  if(anchortag.length>0 && anchortag.substr(0,1)!='#')
    anchortag = '#' + anchortag;
  window.open("help/" + docfile + "_Doc.html" + anchortag, "help", "dependant=yes,width=750,height=550,menubar=yes,personalbar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");     
}

function PrintRpt(additionalParams)
{
  window.open(this.document.location.href + additionalParams + "&print=Y", "f1000print",
              "scrollbars=yes,resizable=yes,menubar=no,status=no,toolbar=yes,width=750,height=550");
}

function rtrim(strVal)
{
  var retval = strVal;
  
  while(retval.charAt(strVal.length-1)==' ')
    retval = strVal.substr(0, strVal.length-1);
  
  return retval;
}

function setFnumberArea(){
    var fake = document.getElementsByName('fake_fnumber_office')[0];
    var real = document.getElementsByName('fnumber_office')[0];
    real.value = fake.options[fake.selectedIndex].value;   
}
