/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

var selectedTab = "homeTab";
var selectedVideoDiv = "selectPresentationDiv";

window.onresize = centerDiv;


function centerDiv()
{
    var gDiv = document.getElementById('generalDiv');
    var padding = 0;
    var winW = 630;
    //set winW and winH
    if (document.body && document.body.offsetWidth) {
        winW = document.body.offsetWidth;
    }
    if (document.compatMode=='CSS1Compat' &&
        document.documentElement &&
        document.documentElement.offsetWidth ) {
    winW = document.documentElement.offsetWidth;
    }
    if (window.innerWidth && window.innerHeight) {
    winW = window.innerWidth;
    }
    //alert(xResolution);
    if(winW - 1100 > 0)
    {
        padding = (winW -1100)/2; 
    }
   // alert(padding);
    gDiv.style.marginLeft = padding + 'px';
    
    //load simulator dates
    loadSimulatorDates();
}

function selectTab(tab)
{
    var className;
    var divName = tab + "Div";
    var selectedDiv = selectedTab + "Div";
    switch (tab)
    {
        case "simulatorTab":
            className = "selectedTab15";
            break;
        case "cmcProgramsTab":
            className = "selectedTab15";
            break;
        default:
            className = "selectedTab1";
    }
    if(selectedTab != tab)
    {
        document.getElementById(tab).className = className; //select the tab
        unselectTab(selectedTab);  //unselect the current tab
        document.getElementById(divName).className = "innerFullWidth";  //set the div element to show the selected tab
        document.getElementById(selectedDiv).className = "hide"; //hide the previous div element
        selectedTab = tab;        //reset the selectedTab
    }
}

function unselectTab(tab){
    var className;
    switch (tab)
    {
        case "simulatorTab":
            className = "unselectedTab15";
            break;
        case "cmcProgramsTab":
            className = "unselectedTab15";
            break;
        default:
            className = "unselectedTab1";
    }
    document.getElementById(tab).className = className;
}

function hoverTab(tab){
    if(selectedTab != tab)
    {
        var className;
        switch (tab)
        {
            case "simulatorTab":
                className = "hoveredTab15";
                break;
            case "cmcProgramsTab":
                className = "hoveredTab15";
                break;
            default:
                className = "hoveredTab1";
        }
        document.getElementById(tab).className = className;
    }
}

function unhoverTab(tab){
    if(selectedTab != tab)
    {
        var className;
        switch (tab)
        {
            case "simulatorTab":
                className = "unselectedTab15";
                break;
            case "cmcProgramsTab":
                className = "unselectedTab15";
                break;
            default:
                className = "unselectedTab1";
        }
        document.getElementById(tab).className = className;
    }
}

function changeTextSimplify()
{
    var hdr = document.getElementById('loginHeader');
    var txt = document.getElementById('loginData');
    
    var hdrText = "Simplify";
    var txtText = "Simplify your operations with electronic payment management and reports.";
    
    hdr.innerHTML = hdrText;
    txt.innerHTML = txtText;  
}

function changeTextAutomate()
{
    var hdr = document.getElementById('loginHeader');
    var txt = document.getElementById('loginData');
    
    var hdrText = "Automate";
    var txtText = "Automate your monthly payments through the secure ACH network";
    
    hdr.innerHTML = hdrText;
    txt.innerHTML = txtText;  
}

function changeTextRelax()
{
    var hdr = document.getElementById('loginHeader');
    var txt = document.getElementById('loginData');
    
    var hdrText = "Relax";
    var txtText = "Relaxing is easy when your payments are automated and your operations are simplified with Monthly Collector.";
    
    hdr.innerHTML = hdrText;
    txt.innerHTML = txtText;  
}




/* MC Simulator Functions ---------------------- */
var studentCount =0;  //tracks the num of students
var SelectID;
var StudentID;
var BaseAmountID;
var VariableAmountID;
var TotalAmountID;
var MCFeeID;
var ReducedID;
var NetTotalID;
var CollectDayID;
var DepositDayID;
var keyValue = false;
var StudentArray = new Array(); //holds a multi-dimensional array containing studentCountID[0] and deleted flag[1] and class[2]
var numActiveStudents = 0;  //holds the number of active (non-deleted) students in the studio

var CollectionDayArray = new Array();
//	CollectionDayArray[0] = "6/1/2011";
//	CollectionDayArray[1] = "6/6/2011";
//	CollectionDayArray[2] = "6/10/2011";
//	CollectionDayArray[3] = "6/20/2011";

var DepositDayArray = new Array();
//	DepositDayArray[0] = "6/10/2011";
//	DepositDayArray[1] = "6/15/2011";
//	DepositDayArray[2] = "6/20/2011";
//	DepositDayArray[3] = "6/30/2011";


function setIDS(id) {
    SelectID = "selectID" + id;
    StudentID = "studentID" + id;
    BaseAmountID = "baseAmountID" + id;
    VariableAmountID = "variableAmountID" + id;
    TotalAmountID = "totalAmountID" + id;
    MCFeeID = "mcFeeID" + id;
    ReducedID = "reducedID" + id;
    NetTotalID = "netTotalID" + id;
    CollectDayID = "collectDayID" + id;
    DepositDayID = "depositDayID" + id;
}

function selectRow(id)
{
    var checkBoxID = "selectID" + id;
    var tmpRowID = "rowID" + id;
    if(document.getElementById(checkBoxID).checked == true)
    {
        document.getElementById(tmpRowID).className = "rowSelected";
    }
    else
    {
        document.getElementById(tmpRowID).className = StudentArray[id-1][2]; //set it back to the original className
    }

    toggleRemoveStudent();
}

//adds a student to the studio
function addStudent(userID,env) 
{
    studentCount++; // increment studentCount
    numActiveStudents++;  //increment activeStudents
    setIDS(studentCount); //set ids
    var newStudent = new Array();
    newStudent[0] = studentCount;
    newStudent[1] = false;  //false meaning, not deleted
    if(numActiveStudents % 2 > 0)
   {
       newStudent[2] = "trClass_odd";
   }
   else
   {
        newStudent[2] = "trClass_even";
   }
    StudentArray.push(newStudent); //add the new student to the StudentArray
    createNewStudentHTML(); //add the html to the page

    //update grand total line here
    updateStudentCountTotal();  //student count
    changeGrandTotal('baseAmountID','grandBaseTotal'); //base amount
    updateVariableAmountTotals(); //variable amount
    changeGrandTotal('totalAmountID','grandTotalAmount');  //total Amount
    changeGrandTotal('mcFeeID','grandMCFeeTotal'); //MC Fee
    changeGrandTotal('netTotalID','grandDepositAmount'); //deposit amount
    setFastFeeAmount();  //update the fast pay amount

    //scroll the page
    if(studentCount == 1)
    {window.scrollBy(0,300);}
    if(numActiveStudents <= 18)
    {window.scrollBy(0,40);}

    //simulatorStats(userID,env);
     updateSummaryBox();
     activateFastPay();
}

function removeStudent()
{

    //reset numActiveStudents to 0 for recalculation
    numActiveStudents = 0;
    var tmpRow = "";
    var tmpSelected = "";
    var tmpCheckBox;
    var tmpRowClass;
    //loop thru array and find selected students, change class to reflect new row color or hide
    
    for(var i = 1; i <= studentCount; i++)
    {
        if((numActiveStudents + 1) % 2 > 0)
        {
            tmpRowClass = "trClass_odd";
        }
        else
        {
           tmpRowClass = "trClass_even";
        }
        tmpSelected = "selectID" + i;
        tmpRow = "rowID" + i;
        tmpCheckBox = document.getElementById(tmpSelected)
        if(StudentArray[i-1][1] == false) //if student is not deleted
        {
             if(tmpCheckBox.checked == true)  //if the row is selected to be deleted
             {
                    StudentArray[i-1][1] = true; //set it to deleted
                    tmpRowClass = "hide";
             }
             else
             {
                  numActiveStudents++;
             }

             document.getElementById(tmpRow).className = tmpRowClass;
        }
    }

    if(numActiveStudents == 0)
    {
         document.getElementById("rowID0").className = "trClass_even";  //reshow the start screen
    }

    //update grand total line here
    updateStudentCountTotal();  //student count
    changeGrandTotal('baseAmountID','grandBaseTotal'); //base amount
    updateVariableAmountTotals(); //variable amount
    changeGrandTotal('totalAmountID','grandTotalAmount');  //total Amount
    changeGrandTotal('mcFeeID','grandMCFeeTotal'); //MC Fee
    changeGrandTotal('netTotalID','grandDepositAmount'); //deposit amount
    document.getElementById('removeButton').disabled = true;
    updateSummaryBox();
    setFastFeeAmount();
    activateFastPay();
    
}

//build Element Functinos

function createNewStudentHTML() {
    var lastRowId = studentCount - 1;
    var lastMCRowID = "rowID" + lastRowId;
    var lastMCRow = document.getElementById(lastMCRowID);//gets last row inserted in the table
    var newMCRow = document.createElement("tr");
    var tr_id = "rowID" + studentCount;  //sets the id of the row
    var tr_class = "trClass_even";
    

   if(numActiveStudents % 2 > 0)
   {
       tr_class = "trClass_odd";
   }
    newMCRow.id = tr_id; //set id
    newMCRow.className = tr_class; //set class

    //newMCRow.innerHTML = newHTML;
    newMCRow.appendChild(buildSelectElement());
    newMCRow.appendChild(buildStudentElement());
    newMCRow.appendChild(buildBaseAmountElement());
    newMCRow.appendChild(buildVariableAmountElement());
    newMCRow.appendChild(buildTotalAmountElement());
    newMCRow.appendChild(buildMCFeeElement());
    newMCRow.appendChild(buildReducedElement());
    newMCRow.appendChild(buildNetTotalElement());
    newMCRow.appendChild(buildCollectionDayElement());
    newMCRow.appendChild(buildDepositDayElement());
    if (numActiveStudents == 1) {
       document.getElementById('rowID0').className="hide"; //hide rowID0
    }
    lastMCRow.parentNode.insertBefore(newMCRow,lastMCRow.nextSibling); //inserts after the last node in the table
}

function buildSelectElement()
{
    var selectElement = document.createElement("td"); //create new column element
    
    selectElement.setAttribute("class","selectColumn");

    //create input type checkbox as an element
    var inputElement = document.createElement("input");
    inputElement.setAttribute("type","checkbox");
    inputElement.setAttribute("id",SelectID);
    var currStudentCount = studentCount;
    //inputElement.onclick = function(){selectRow(currStudentCount)};
    if(inputElement.addEventListener)//for firefox and chrome and ie 9
    {
       inputElement.addEventListener('click', function(){selectRow(currStudentCount)}, false);
    }
    else if(inputElement.attachEvent) //for ie 8 and less
    {
        inputElement.attachEvent('onclick',function(){selectRow(currStudentCount)});
    }

    selectElement.appendChild(inputElement);

    return selectElement;
}

function buildStudentElement() {

    var studentElement = document.createElement("td");
    studentElement.setAttribute("class", "simulatorElement");

    var inputStudent = document.createElement("input");
	inputStudent.setAttribute("class","MCAppTextBox");
        inputStudent.setAttribute("type", "text");
        inputStudent.setAttribute("size", "15");
        inputStudent.setAttribute("value", "new student " + studentCount);
	inputStudent.setAttribute("id",StudentID);

    studentElement.appendChild(inputStudent);

    return studentElement;
}

function buildBaseAmountElement(){
    var txtBaseAmount = new Number(document.getElementById("txtBaseAmount").value);
        txtBaseAmount = rounded(txtBaseAmount);
        
	var baseAmountElement = document.createElement("td");
		baseAmountElement.setAttribute("class","simulatorElement");
		baseAmountElement.setAttribute("id",BaseAmountID);

	var textBaseElement = document.createTextNode(txtBaseAmount.toFixed(2));

	baseAmountElement.appendChild(textBaseElement);

	//alert(baseAmountElement.childNodes[0].nodeValue);
	return baseAmountElement;
}

function buildVariableAmountElement(){
    var currStudentCount = studentCount;
    var variableElement = document.createElement("td");
        variableElement.setAttribute("class", "variableAmountColumn");

    var inputElement = document.createElement("input");
        inputElement.setAttribute("type", "text");
        inputElement.setAttribute("id", VariableAmountID);
        inputElement.setAttribute("class","MCAppTextBox");
        inputElement.setAttribute("size","8");
        inputElement.setAttribute("value","0.00");

    //keypress
    if(inputElement.addEventListener)//for firefox and chrome and ie 9
    {
       inputElement.addEventListener('keypress', function(e){e = window.event || e;var valid = variableKeyPress(e,currStudentCount);
                                                               if(!valid){
                                                                   if(e.preventDefault){e.preventDefault();}
                                                                   else{e.returnValue = false;}
                                                               }}, false);
    }
    else if(inputElement.attachEvent) //for ie 8 and less
    {
        inputElement.attachEvent('onkeypress', function(e){e = window.event || e;var valid = variableKeyPress(e,currStudentCount);
                                                               if(!valid){
                                                                   if(e.preventDefault){e.preventDefault();}
                                                                   else{e.returnValue = false;}
                                                               }}, false);
    }

    //keyup
    if(inputElement.addEventListener)//for firefox and chrome and ie 9
    {
       inputElement.addEventListener('keyup', function(e){e = window.event || e;variableKeyup(e,currStudentCount);}, false);
    }
    else if(inputElement.attachEvent) //for ie 8 and less
    {
        inputElement.attachEvent('onkeyup', function(e){e = window.event || e;variableKeyup(e,currStudentCount);}, false);
    }

    //change
    //keyup
    if(inputElement.addEventListener)//for firefox and chrome and ie 9
    {
       inputElement.addEventListener('blur', function(){variableOnChange(currStudentCount);}, false);
    }
    else if(inputElement.attachEvent) //for ie 8 and less
    {
        inputElement.attachEvent('onblur', function(){variableOnChange(currStudentCount);}, false);
    }

     variableElement.appendChild(inputElement);

     return variableElement;

}

function buildTotalAmountElement(){

	var txtBaseAmount = new Number(document.getElementById("txtBaseAmount").value);
        txtBaseAmount = rounded(txtBaseAmount);

	var totalAmountElement = document.createElement("td");
		totalAmountElement.setAttribute("class","simulatorElement");
		totalAmountElement.setAttribute("id",TotalAmountID);

	var textTotalElement = document.createTextNode(txtBaseAmount.toFixed(2));

	totalAmountElement.appendChild(textTotalElement);

	return totalAmountElement;
}

function buildMCFeeElement(){

	var txtBaseAmount = document.getElementById("txtBaseAmount").value;
	var mcFeeAmount = new Number(calcMCFee(txtBaseAmount,false));
            mcFeeAmount = rounded(mcFeeAmount);

	var MCFeeAmountElement = document.createElement("td");
		MCFeeAmountElement.setAttribute("class","simulatorElement");
		MCFeeAmountElement.setAttribute("id",MCFeeID);

	var textMCFeeElement = document.createTextNode(mcFeeAmount.toFixed(2));

	MCFeeAmountElement.appendChild(textMCFeeElement);

	return MCFeeAmountElement;
}

function buildReducedElement(){
    var currStudentCount = studentCount;
    var reducedElement = document.createElement("td");
        reducedElement.setAttribute("class", "reducedColumn");

    var inputElement = document.createElement("input");
        inputElement.setAttribute("type", "checkbox");
        inputElement.setAttribute("id", ReducedID);

     if(inputElement.addEventListener)//for firefox and chrome and ie 9
    {
       inputElement.addEventListener('click', function(){onReducedClick(currStudentCount)}, false);
    }
    else if(inputElement.attachEvent) //for ie 8 and less
    {
        inputElement.attachEvent('onclick',function(){onReducedClick(currStudentCount)});
    }

     reducedElement.appendChild(inputElement);

     return reducedElement;
}

function buildNetTotalElement(){

	var txtBaseAmount = new Number(document.getElementById("txtBaseAmount").value);
	var mcFeeAmount = new Number(calcMCFee(txtBaseAmount,false));
            mcFeeAmount = rounded(mcFeeAmount);
	var netTotalAmount = txtBaseAmount - mcFeeAmount;
	netTotalAmount = rounded(netTotalAmount);

	var netTotalAmountElement = document.createElement("td");
		netTotalAmountElement.setAttribute("class","simulatorElement");
		netTotalAmountElement.setAttribute("id",NetTotalID);

	var textnetTotalElement = document.createTextNode(netTotalAmount.toFixed(2));

	netTotalAmountElement.appendChild(textnetTotalElement);

	return netTotalAmountElement;
}

function buildCollectionDayElement(){
	var collectionDay = CollectionDayArray[document.getElementById("ddlCollectionDay").value];

        var collectionDayElement = document.createElement("td");
            collectionDayElement.setAttribute("id", CollectDayID);
            collectionDayElement.setAttribute("class","simulatorElement");

        var textCollectDayElement = document.createTextNode(collectionDay);

            collectionDayElement.appendChild(textCollectDayElement);

            return collectionDayElement;
}

function buildDepositDayElement(){
	var depositDay = DepositDayArray[document.getElementById("ddlCollectionDay").value];
        
        //fast pay
        if(document.getElementById('chkbxFastPay').checked)
        {
            depositDay = CollectionDayArray[document.getElementById("ddlCollectionDay").value];   
        }

        var depositDayElement = document.createElement("td");
            depositDayElement.setAttribute("id", DepositDayID);
            depositDayElement.setAttribute("class","simulatorElement");

        var textDepositDayElement = document.createTextNode(depositDay);

            depositDayElement.appendChild(textDepositDayElement);

            return depositDayElement;
}

//change events/calculations
function changeMCFee()
{
    //this function assumes that the IDs have been set
    var reduced = document.getElementById(ReducedID).checked;
    var totalAmount = (document.getElementById(TotalAmountID).childNodes[0].nodeValue) * 1.00;
    var fee = new Number(calcMCFee(totalAmount,reduced));
        fee = rounded(fee);
    document.getElementById(MCFeeID).childNodes[0].nodeValue = fee.toFixed(2);

    //update grand totals line
    changeGrandTotal('mcFeeID','grandMCFeeTotal'); //MC Fee
}

function updateStudentCountTotal()
{
    var grandTotal = document.getElementById('grandStudentCount');
    if(grandTotal.childNodes.length == 0)
    {
       var newTextNode = document.createTextNode(numActiveStudents);
       grandTotal.appendChild(newTextNode);
    }
    else
    {
        var textNode = grandTotal.childNodes[0];
        textNode.nodeValue= numActiveStudents;
    }
}

function changeTotalAmount()
{
    //this function assumes that the IDs have been set
    var baseAmount = new Number(document.getElementById(BaseAmountID).childNodes[0].nodeValue);
    var variableAmount = new Number(document.getElementById(VariableAmountID).value);
    var totalAmount = baseAmount + variableAmount;
    if(!isNaN(totalAmount))
    {
         totalAmount = rounded(totalAmount);
    }
    else
    {
        totalAmount = "0.00";
    }
    document.getElementById(TotalAmountID).childNodes[0].nodeValue = totalAmount.toFixed(2);

    //change grand total amounts

    changeGrandTotal('totalAmountID','grandTotalAmount'); //total amount
}

function changeGrandTotal(type,grandTotalID)
{
    var grandTotal = document.getElementById(grandTotalID);
    var vTotal = new Number(0.00);

    for(var i = 0; i < studentCount; i++ )
    {
        if(StudentArray[i][1] == false) //check to make sure the student isn't deleted
        {
            var tmpID = type + StudentArray[i][0];
            var tmpTotal = new Number(document.getElementById(tmpID).childNodes[0].nodeValue);
            if(!isNaN(tmpTotal))
            {
               vTotal += rounded(tmpTotal);
            }
        }
    }
    
    //check for fastPay
    if(document.getElementById('chkbxFastPay').checked)
    {
        var fpFee = calculateFastPayFee();
        
        //if this is the MC Fee, add the fpFee to the total amount
        if(type == 'mcFeeID')
        {
           vTotal += fpFee;     
        }
        
        //if this is the Net Deposit, subtract the fpFee from the total amount
        if(type == 'netTotalID')
        {
            vTotal -= fpFee;    
        }
    }

    if(grandTotal.childNodes.length == 0)
    {
       var newTextNode = document.createTextNode("$" + vTotal.toFixed(2));
       grandTotal.appendChild(newTextNode);
    }
    else
    {
        var textNode = grandTotal.childNodes[0];
        textNode.nodeValue= "$" + vTotal.toFixed(2);
    }
}

function changeVariableAmount(amount)
{
    amount = amount * 1.00; //cast it to a number
    var maxAmount = 50.00;
    var minAmount = (document.getElementById(BaseAmountID).childNodes[0].nodeValue) * -1.00;

    if(amount < minAmount)
    {
       alert("The minimum value that this Variable Amount can be is: " + minAmount + ", thus putting the total amount at 0.00.  Total collection amounts may not be less than 0.00.");
       amount = minAmount.toFixed(0);
       document.getElementById(VariableAmountID).value = amount;
    }
    else if( amount > maxAmount)
    {
       alert("The maximum value that the Variable Amount can be is: " + maxAmount + ".  The Max Variable Amount is set in the student's contract.  For this simulator, the Max Variable amount is set at 50.  50 is a typical amount for the max variable amount.");
       amount = maxAmount.toFixed(0);
       document.getElementById(VariableAmountID).value = amount;
    }
    else
    {
        amount = amount;
    }

    changeTotalAmount();  //update totalAmount for the line and the grand totals
    changeMCFee(); //update MC fees
    changeDepositAmount();
    updateVariableAmountTotals();
    updateSummaryBox();
}

function changeDepositAmount()
{
    //this function assumes the IDs have been set
    var totalAmount = new Number(document.getElementById(TotalAmountID).childNodes[0].nodeValue);
    var mcFee = new Number(document.getElementById(MCFeeID).childNodes[0].nodeValue);
    var netDeposit = new Number(totalAmount - mcFee);
    netDeposit = rounded(netDeposit);
    document.getElementById(NetTotalID).childNodes[0].nodeValue = netDeposit.toFixed(2);

    //update totals
    changeGrandTotal('netTotalID','grandDepositAmount'); //deposit amount
}

function updateVariableAmountTotals()
{
    var variableTotal = document.getElementById('grandVariableTotal');
    var vTotal = new Number(0.00);

    for(var i in StudentArray )
    {
        if(StudentArray[i][1] == false) //check to make sure the student isn't deleted
        {
            var tmpID = "variableAmountID" + StudentArray[i][0];
            var tmpTotal = new Number(document.getElementById(tmpID).value);
            if(!isNaN(tmpTotal))
            {
               vTotal += rounded(tmpTotal);
            }
        }
    }

    if(variableTotal.childNodes.length == 0)
    {
       var newTextNode = document.createTextNode("$" + vTotal.toFixed(2));
       variableTotal.appendChild(newTextNode);
    }
    else
    {
        var textNode = variableTotal.childNodes[0];
        textNode.nodeValue= "$" + vTotal.toFixed(2);
    }
}

function variableKeyup(e,id)
{
    setIDS(id);
    var inputBox = document.getElementById(VariableAmountID);
    var keynum;
    if(window.event)
    {
        keynum = e.keyCode; //for ie
    }
    else
    {
        keynum = e.which;
    }
    if(keynum == 8 || keynum == 46 || keyValue == true)//backspace or delete
    {
        if(!isNaN(inputBox.value))
        {
            changeVariableAmount(inputBox.value);
        }
        else
        {
           changeVariableAmount(0);
        }
    }
    keyValue = false;
}

function variableOnChange(id)
{
    setIDS(id)
    var boxValue = new Number(document.getElementById(VariableAmountID).value);
    if(!isNaN(boxValue))
    {
        boxValue = rounded(boxValue);
    }
    else
    {
        boxValue = new Number(0.00);
    }
    
    document.getElementById(VariableAmountID).value = boxValue.toFixed(2);
}

function baseOnChange()
{

    var boxValue = new Number(document.getElementById('txtBaseAmount').value);
    if(!isNaN(boxValue))
    {
        boxValue = rounded(boxValue);
    }
    else
    {
        boxValue = new Number(0.00);
    }

    document.getElementById('txtBaseAmount').value = boxValue.toFixed(2);
}

function variableKeyPress(e,id)
{
    setIDS(id);
    var keynum;
    var keychar;
    var boxValue = document.getElementById(VariableAmountID).value;
    var newBoxValue;
    if(window.event)
    {
        keynum = e.keyCode;    //for ie
    }
    else
    {
        keynum = e.which;     //for others
    }
    var cursorPosition = doGetCaretPosition(document.getElementById(VariableAmountID));
    keychar=String.fromCharCode(keynum);
    newBoxValue = insertChar(boxValue,keychar,cursorPosition);
    if(newBoxValue == "-" || keynum == 8 || keynum == 46) //allows for negatives.  Firefox triggers this event when backspace or delete buttons are used, ie and chrome do not
    {
        keyValue = true;
       return true;
    }
    else
    {
       if(isNaN(newBoxValue) || keychar == " ")
       {
          return false;
       }
       else
       {
           keyValue = true;
           return true;
       }
    }

}

function baseKeyPress(e)
{
    e = window.event || e;
    var keynum;
    var keychar;
    var boxValue = document.getElementById('txtBaseAmount').value;
    var newBoxValue;
    if(window.event)
    {
        keynum = e.keyCode;    //for ie
    }
    else
    {
        keynum = e.which;     //for others
    }
    var cursorPosition = doGetCaretPosition(document.getElementById('txtBaseAmount'));
    keychar=String.fromCharCode(keynum);
    newBoxValue = insertChar(boxValue,keychar,cursorPosition);
    if(keynum == 8 || keynum == 46) // do not allow for negatives.  Firefox triggers this event when backspace or delete buttons are used, ie and chrome do not
    {
        keyValue = true;
        return true;
    }
    else
    {
       if(isNaN(newBoxValue) || keychar == " ")
       {
          return false;
       }
       else
       {
           keyValue = true;
           return true;
       }
    }
}

function onReducedClick(id)
{
    setIDS(id);
    changeMCFee();
    changeDepositAmount();
    updateSummaryBox();
}

function toggleRemoveStudent()
{
    var disabled2 = true;
    if(studentCount > 0)
    {
        var tmpSelected;
        for(var i = 1; i <= studentCount; i++)
        {
           tmpSelected =  "selectID" + i;
           tmpCheckBox = document.getElementById(tmpSelected)
            if(StudentArray[i-1][1] == false) //if student is not deleted
            {
                if(tmpCheckBox.checked == true)  //if the row is selected to be deleted
                {
                   disabled2 = false;
                   break;
                }
            }
        }
        document.getElementById('removeButton').disabled = disabled2;

    }
    else
    {
        document.getElementById('removeButton').disabled = true;
    }
}

function onCollectionChange()
{
    var collectionDayIndex = document.getElementById('ddlCollectionDay').value;
    var tmpCollectID
    var tmpDepositID
    var tmpCollectionNode;
    var tmpDepositNode;
    for(var i = 0; i < studentCount; i++)
    {
        tmpCollectID = "collectDayID" + StudentArray[i][0];
        tmpDepositID = "depositDayID" + StudentArray[i][0];
        tmpCollectionNode = document.getElementById(tmpCollectID);
        tmpDepositNode = document.getElementById(tmpDepositID);

        
        tmpCollectionNode.childNodes[0].nodeValue = CollectionDayArray[collectionDayIndex];
        if(document.getElementById('chkbxFastPay').checked)
        {
           tmpDepositNode.childNodes[0].nodeValue = CollectionDayArray[collectionDayIndex];
        }
        else
        {
           tmpDepositNode.childNodes[0].nodeValue = DepositDayArray[collectionDayIndex]; 
        }
    }

    updateSummaryBox();
}

function updateSummaryBox()
{
   var summaryBox = document.getElementById('summaryBox');
   var collectionDayIndex = document.getElementById('ddlCollectionDay').value;
   var collectionDay;
   if(document.getElementById('chkbxFastPay').checked)
   {
      collectionDay = CollectionDayArray[collectionDayIndex];
   }
   else
   {
       collectionDay = DepositDayArray[collectionDayIndex];
   }
   
   var depositAmount = document.getElementById('grandDepositAmount').childNodes[0].nodeValue;
   var summaryBoxInput = "A single deposit in the amount of " + depositAmount + " would post to your account on " + collectionDay;
       summaryBoxInput += ".  A detailed report very similar to what you see above would be emailed to you.  The reports also track your year-to-date totals";
   var trClass = "summaryBox";

   if(summaryBox.childNodes.length == 0)
   {
       if(numActiveStudents  == 0)
           {
               summaryBoxInput = "";
               trClass = "hide";
           }
       var newNode = document.createTextNode(summaryBoxInput);
       summaryBox.className = trClass;
        summaryBox.appendChild(newNode);
   }
   else
   {
       if(numActiveStudents  == 0)
           {
               summaryBoxInput = "";
               trClass = "hide";
           }
      summaryBox.childNodes[0].nodeValue = summaryBoxInput;
      summaryBox.className = trClass;
   }
}

function setFastFeeAmount()
{
    var fpElement = document.getElementById('fastPayFee');
    vTotal = calculateFastPayFee();
    
    if(fpElement.childNodes.length == 0)
    {
       var newTextNode = document.createTextNode(vTotal.toFixed(2));
       fpElement.appendChild(newTextNode);
    }
    else
    {
        var textNode = fpElement.childNodes[0];
        textNode.nodeValue= vTotal.toFixed(2);
    }
    
}

function activateFastPay()
{
    
    if(numActiveStudents > 0)
    {
       // alert("numActiveStudents is > 0");
       document.getElementById('chkbxFastPay').disabled = false;     
    }
    else
    {
       // alert("numActiveStudents is 0");
       document.getElementById('chkbxFastPay').disabled = true; 
       document.getElementById('chkbxFastPay').checked = false;
       fastPay_check();  
       setFastFeeAmount();
    }
}

function fastPay_check(){
    var chkFastPay = document.getElementById('chkbxFastPay');
    var rwFastPay = document.getElementById('rowFastPay');
    setFastFeeAmount(); //set the fast pay fee amount
    onCollectionChange();  //change the collection days
    changeDepositAmount(); //update deposit amount
    changeMCFee();
    updateSummaryBox();
     
    if(chkFastPay.checked)
    {
        rwFastPay.className = "fastPay";     
    }
    else
    {
        rwFastPay.className = "hide"; 
    } 
}


//Utility Functions
function rounded(num)
{
    var result = new Number(Math.round(num * 100)/100);
    return parseFloat(result);
}

function calcMCFee(totalAmount,reduced)
{
	var fee;
	var max = 5.50;

	if(totalAmount > 0)
	{
		var baseAmount;
		if(totalAmount >= 50 && reduced == false)
		{
			baseAmount = 2.25;
		}
		else if(totalAmount >= 50 && reduced == true)
		{
			baseAmount = 1.00;
		}
		else if(totalAmount >= 20 && reduced == false)
		{
			baseAmount = 1.25;
		}
		else if(totalAmount >= 20 && reduced == true)
		{
			baseAmount = 0.75;
		}
		else
		{
			baseAmount = 0.75;
		}

		fee = baseAmount + (totalAmount * 0.01);
	}
	else{
		fee = 0;
	}

	if(fee <= max)
	{
		return fee;
	}
	else
	{
		return max;
	}
}

function doGetCaretPosition (ctrl) {
	var CaretPos = 0;
	// IE Support
	if (document.selection) {

		ctrl.focus ();
		var Sel = document.selection.createRange();
		var SelLength = document.selection.createRange().text.length;
		Sel.moveStart ('character', -ctrl.value.length);
		CaretPos = Sel.text.length - SelLength;
	}
	// Firefox support
	else if (ctrl.selectionStart || ctrl.selectionStart == '0')
		CaretPos = ctrl.selectionStart;
	return (CaretPos);
}

function insertChar(value,ch,index)
{
    value = value + ""; //conver to string
    var stringArray = value.split('');
    stringArray.splice(index,0,ch);
    var stringValue = "";
    for(i = 0; i < stringArray.length; i++)
    {
        stringValue += (stringArray[i] + "");
    }
    return stringValue;
}

function getUserPosition()
{
    var yPos = window.pageYOffset;
}

	
function calculateFastPayFee()
{
    var totalCollection1 = document.getElementById('grandTotalAmount');
    var totalAmt = totalCollection1.childNodes[0].nodeValue;
    totalAmt = totalAmt.substring(1); //remove the $ sign
    var totalCollection = rounded(totalAmt); //convert it to a number
    
    var fastPayFee;

    if(totalCollection > 0)
    {
            var tier = Math.ceil(totalCollection/1000);
            fastPayFee = 7.00 * tier;

    }
    else
    {
      fastPayFee = 0;
    }

    return rounded(fastPayFee);
}




/* End MC Simulator Functions  -------------------- */


//------------------------AJAX---------------------------------------------------
function createXmlHttpObject()
{
    var xmlHttp;
    try
    {
            //IE7 and newer or other browsers
            xmlHttp = new XMLHttpRequest();
    }
    catch(e)
    {
            try
            {
                    //IE 6 and older
                    xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
            }
            catch(e)
            {

            }
    }
    if(!xmlHttp)
    {
            alert("Error creating the XMLHttpRequest object.");
            return null;
    }
    else
    {
            return xmlHttp;
    }
}

function simulatorStats(userID,env)
{
    // create a new xmlHttp object
    var xmlHttp = createXmlHttpObject();

    if(xmlHttp)
    {
        try
        {
            var page = "simulatorStats.php";
            var parameters = "?userID=" + userID + "&environment=" + env;
            var url = page + parameters;
            xmlHttp.open("GET",url,true);
//            xmlHttp.onreadystatechange = function(){
//              if(xmlHttp.readyState == 4)
//              {
//                    if(xmlHttp.status == 200)
//                    {
//                        try
//                        {
//                            alert("insert occured");
//                        }
//                        catch(e)
//                        {
//
//                        }
//                    }
//              }
//
//            }//end function
            xmlHttp.send(null);
        }
        catch (e)
        {

        }
    }
}

function loadSimulatorDates()
{
    // create a new xmlHttp object
    var xmlHttp = createXmlHttpObject();

    if(xmlHttp)
    {
        try
        {
            var page = "forms/loadDates.php";
            xmlHttp.open("GET",page,true);
            xmlHttp.onreadystatechange = function(){
              if(xmlHttp.readyState == 4)
              {
                    if(xmlHttp.status == 200)
                    {
                        try
                        {
                            //get the string from the php file
                            var dates = xmlHttp.responseText.toString();
                            var sCollectDates = dates.substring(0,dates.indexOf('#')); //get only collectionDates by selecting until the # mark
                            var sDepositDates = dates.substring(dates.indexOf('#') + 1);  //get only deposit dates by selecting from # to the end
                            
                            //load collectionDates
                            var index = sCollectDates.indexOf(':');
                            while(index > -1)
                            {
                                var sub1 = sCollectDates.substring(0, index);  //get first date of the string
                                CollectionDayArray.push(sub1);  //add the date to the array
                                sCollectDates = sCollectDates.substring(index + 1);  //reset the string to omit the first date
                                index = sCollectDates.indexOf(':');
                            }
                            
                            //load depositDates
                             index = sDepositDates.indexOf(':');
                            while(index > -1)
                            {
                                sub1 = sDepositDates.substring(0, index);  //get first date of the string
                                DepositDayArray.push(sub1);  //add the date to the array
                                sDepositDates = sDepositDates.substring(index + 1);  //reset the string to omit the first date
                                index = sDepositDates.indexOf(':');
                            }
                        }
                        catch(e)
                        {
                            alert("error with processing data: \n" + e.toString());
                        }
                    }
              }

            }//end function
            xmlHttp.send(null);
        }
        catch (e)
        {

        }
    }
}


//------------------------VIDEO PRESENTATIONS------------------------------------
function playVideo(elName)
{
    var divName = elName + "Div";
    document.getElementById(divName).className = "presentationDiv";
    document.getElementById(selectedVideoDiv).className = "hide";
    selectedVideoDiv = divName;   
}



