


// Rounded corner init...
window.onload = function( ) {
	settings = {
		tl: { radius: 7 },
		tr: { radius: 7 },
		bl: { radius: 7 },
		br: { radius: 7 },
		antiAlias: true,
		autoPad: false,
		validTags: ["div"]
	}

	settings.autoPad = true;
	var roundedDivs = new curvyCorners( settings, "rounded");
	roundedDivs.applyCornersToAll();

	settings.autoPad = false;
	var roundedPadless = new curvyCorners( settings, "roundedPadless" );
	roundedPadless.applyCornersToAll();
}

/*
 * Get schema & host. 
 *
 */
function getSchemaHost(){
   return location.protocol + '//' + location.host;
}


var enableCofrsSubmissionControls = function( ) {
	/* to enable */
	var submitToCofrsButton = jQuery('.submitToCofrsButton');
	var resubmitToCofrsButton = jQuery('.resubmitToCofrsButton');
	var cancelCofrsButton = jQuery('.cancelCofrsButton');

	submitToCofrsButton.css('display', 'inline');
	resubmitToCofrsButton.css('display', 'none');
	cancelCofrsButton.css('display', 'inline');

	return;
}

/**
* Functions below were introduced to address the Application ice:commandLink onclick/onmousedown form
* submission issues when Submit for Approval confirmation dialog is Cancelled
*
*/
function confirmSubmitForApproval(link) {
	if (confirmSubmit()) {
		link.fireEvent('onclick');
		return true;
	}
	return false;
}

function confirmSubmit() {
	var ans = confirm('Are you sure you wish to submit this Application? \n (No further edits will be allowed)');
	if (ans == true) {
		return true;
	} 
	else {
		return false;
	}
}
/*
 * Used on application switching.  Resets user editable fiels (expended & encumbered)
 */
function resetReimbursementAmounts() {
   var val = 0.0;
   
   //
   //Set all extended parts (but not the error message) to 0 and clear
   //error highlighting.
   jQuery.each(jQuery(".expendedPart").not('.errorMessage'), function() {
      jQuery(this).val(val).format("#,##0.00");
      jQuery(this).removeClass("validationErrorMessage");
   });   
   
   jQuery(".expendedTotal").text(val).format("#,##0.00");   
  
   //
   //Set all encumbered parts (but not the error message) to 0 and clear
   //error highlighting.   
   jQuery.each(jQuery(".encumberedPart").not('.errorMessage'), function() {
      jQuery(this).val(val).format("#,##0.00");
      jQuery(this).removeClass("validationErrorMessage");
   });    
   
   jQuery(".encumberedTotal").text(val).format("#,##0.00");      
   
   //
   //And hide all the error messages
   jQuery.each(jQuery(".errorMessage"), function() {
      var val = jQuery(this).hide();
   });   
   
}


function computeReimbursementAmounts(rowClass) {

   var validationFailed = false;
   //
   //Note row for customized error messages
   var row = "";
   
   if (rowClass == ".personnelRow")
      row = "Personnel";
   else if (rowClass == ".equipmentRow")
      row = "Equipment";
   else if (rowClass == ".trainingRow") 
      row = "Training";
   

   // Inputs for the calculations
   var allocated = jQuery(rowClass + " .allocationPart").parse("#,##0.00")[0];
   var expendedPrior = jQuery(rowClass + " .expendedPriorPart").parse("#,##0.00")[0];
   var expended = jQuery(rowClass + " .expendedPart").parse("#,##0.00")[0];
   var encumbered = jQuery(rowClass + " .encumberedPart").parse("#,##0.00")[0];

   // Do all row calculations up front 
   var expendedYtd = expendedPrior + expended;
   var obligated = expendedYtd + encumbered;
   var unobligated = allocated - obligated;
   jQuery(rowClass + " .unobligatedPart").text(unobligated).format("#,##0.00");   
   jQuery(rowClass + " .obligatedPart").text(obligated).format("#,##0.00");   
   jQuery(rowClass + " .expendedYtdPart").text(expendedYtd).format("#,##0.00");   
   
   //
   //Do validation.
   if (obligated > allocated) {
      validationFailed = true;
      
      //
      //Highlight expended, obligated if they have values:
      if (expended > 0)
         jQuery(rowClass + " .expendedPart").addClass("validationErrorMessage");
      else 
         jQuery(rowClass + " .expendedPart").removeClass("validationErrorMessage");
      
      if (encumbered > 0)
         jQuery(rowClass + " .encumberedPart").addClass("validationErrorMessage");
      else 
         jQuery(rowClass + " .encumberedPart").removeClass("validationErrorMessage");      
      
      jQuery(rowClass + ".errorMessage.encumberedPartError").html("Total " + row + " Obligated ($" + obligated + 
            ") exceeds " + row + " Allocation ($" + allocated + ")<br/>");
      jQuery(rowClass + ".errorMessage.encumberedPartError").css("display", "block");        
      jQuery(rowClass + ".errorMessage.encumberedPartError").show();
   }
   else {
      validationFailed = false;
      jQuery(rowClass + " .encumberedPart").removeClass("validationErrorMessage");
      jQuery(rowClass + ".errorMessage").hide();
      jQuery(rowClass + " .expendedPart").removeClass("validationErrorMessage");  
      jQuery(rowClass + ".errorMessage").hide();          
   }      
   
   //
   //Calculate totals
   var arr = [ ".expended", ".expendedYtd", ".encumbered", ".obligated", ".unobligated" ];        
   jQuery.each(arr, function() { computeReimbursementTotal(this); });     
   
   if (validationFailed) {
      jQuery(".saveSubmitLink").hide();
      jQuery(".fakeSubmitButton").show();
   }
   else {
     
      jQuery(".saveSubmitLink").show();
      jQuery(".fakeSubmitButton").hide();
   }
}

var autoFinalized;
function computeReimbursementTotal(columnClass) {

   var sum = 0;

   jQuery.each(jQuery("input" + columnClass + "Part, span" + columnClass + "Part"), function() {
      var val = jQuery(this).parse("#,###.00")[0];
      if (! isNaN(val))
         sum += val;
   });

	if(columnClass == '.unobligated' && sum <= 0 ) {
		jQuery("input.cbxFinalReimbursement:checkbox").each(function() {
			var input = jQuery(this);
			if( ! input.attr('checked') ) {
				autoFinalized = true;
				input.attr('checked', true);
			}
		});

	} else {     //alert(autoFinalized);
		jQuery("input.cbxFinalReimbursement:checkbox").each(function() {
			var input = jQuery(this);
			if( input.attr('checked') && typeof(autoFinalized) !== 'undefined' && autoFinalized) {
				autoFinalized = false;
				jQuery( '.cbxFinalReimbursement' ).attr('checked', false);
			}
		});

	}

   jQuery(columnClass + "Total").text(sum).format("#,###.00");
}

function supressEnterKey(event) {
   return event.keyCode != 13;
}

var finalReportStatusIsChecked = function( ) {
	var retVal = false;
	jQuery("fieldset.typeFilter :checkbox").each(function() {
		var checkbox = jQuery(this);
		if(checkbox.val() == "Final Report" && checkbox.attr("checked")) {
			retVal = true;
		}
	});
	return retVal;
}

var progressReportStatusIsChecked = function( ) {
	var retVal = false;
	jQuery("fieldset.typeFilter :checkbox").each(function() {
		var checkbox = jQuery(this);
		if(checkbox.val() == "Progress Report" && checkbox.attr("checked")) {
			retVal = true;
		}
	});
	return retVal;
}

var reimbursementStatusIsChecked = function( ) {
	var retVal = false;
	jQuery("fieldset.typeFilter :checkbox").each(function() {
		var checkbox = jQuery(this);
		if(checkbox.val() == "Reimbursement" && checkbox.attr("checked")) {
			retVal = true;
		}
	});
	return retVal;
}

var toggleStatus = function( type ) {    
	if( type.val() == 'Progress Report') {
		jQuery("fieldset.statusFilter :checkbox").each(function() {
			var status = jQuery(this);
			if( status.val() == "Submitted" || status.val() == "Reviewed" ) {
				if( type.attr('checked') ) {
					status.show( );
					status.attr('checked', true);
					jQuery('label[for="'+status.attr("id")+'"]').show();
				} else {
					status.hide( );
					status.attr('checked', false);
					jQuery('label[for="'+status.attr("id")+'"]').hide();
				}
			} 
			if( ! reimbursementStatusIsChecked() && ( status.val() == "Pending" || status.val() == "Approved" || status.val() == "Rejected" || status.val() == "Controller Rejected" )) {
				status.hide( );
				status.attr('checked', false);
				jQuery('label[for="'+status.attr("id")+'"]').hide();
			}
		});
	}

	if( type.val() == 'Reimbursement' ) {    
		jQuery("fieldset.statusFilter :checkbox").each(function() {
			var status = jQuery(this);
			if( (! progressReportStatusIsChecked() ) && ( status.val() == "Submitted" || status.val() == "Reviewed" )) {
				status.hide( );
				status.attr('checked', false);
				jQuery('label[for="'+status.attr("id")+'"]').hide();
			}
			if( type.val() == 'Reimbursement' &&
					( status.val() == "Pending" || status.val() == "Approved" || status.val() == "Rejected" || status.val() == "Controller Rejected" ) ) {
				if( ! type.attr('checked') ) {
					status.hide( );
					status.attr('checked', false);
					jQuery('label[for="'+status.attr("id")+'"]').hide();
				} else {
					status.show( );
					status.attr('checked', true);
					jQuery('label[for="'+status.attr("id")+'"]').show();
				}
			}
		});
	}
}
/**
 * The selected value in the application status dropdown at the time of page load.
 */
var statusValue;

/**
 * This value will be set to true if the current selection in the status dropdown does not match the selected value at
 * the time of page load.
 */
var statusChanged = false;
function inlineTotalValues(partSelector, totalSelector) {
    var sum = 0;
      jQuery.each(jQuery(partSelector), function() {
         var value = jQuery(this).parse("#,##0.00");
         if (isNaN(value))
            value = 0;
         else
            value = value[0];
         jQuery(this).val(value).format("#,##0.00");
         sum = sum + value;
      });
      try {
         jQuery(totalSelector).text(sum).format("#,###.00");
         } catch (err) {}
      try {
         jQuery(totalSelector).val(sum).format("#,###.00");
      } catch (err) {}
}

function totalValues(partSelector, totalSelector) {
   jQuery(partSelector).change(function() {
      var sum = 0;
      jQuery.each(jQuery(partSelector), function() {
         var value = jQuery(this).parse("#,##0.00");
         if (isNaN(value))
            value = 0;
         else
            value = value[0];
         jQuery(this).val(value).format("#,##0.00");
         sum = sum + value;
      });
      try {
         jQuery(totalSelector).text(sum).format("#,###.00");
         } catch (err) {}
      try {
         jQuery(totalSelector).val(sum).format("#,###.00");
         } catch (err) {}
   });
}

if (typeof(jQuery) !== 'undefined') {

jQuery(document).ready(
	function() {

      jQuery(".login-username").focus();
      
      jQuery(".fakeSubmitButton").hide();

      //this call to load the handlers is now embedded in the page
      //this allows for the logic to be there after the controls have been collapsed and then reexpanded  
      /*jQuery("fieldset.typeFilter :checkbox").each(function() {
	        var input = jQuery(this); */
          /* this hides the final report option because it wants to be included in the search
            but since it is a pseudo option you don't want it checked all of the time just when the
            Reimbursement request since a reimbursement request can be a final report type
           */

            /*if( input.val() == "Final Report" ) {
                input.hide();
                jQuery('label[for="'+input.attr("id")+'"]').hide();
            } else {
	            input.change(function() { toggleStatus( input ) });
            }
	  });*/
      /**
       * If we're on the reimbursement request page, this javascript will be activated.
       */
      if (jQuery(".reimbursementRequest, .reimbursementApproval").length > 0) {

         /**
          * Whenever a user clicks on an extended amount textbox, select all contents.
          */
         jQuery(".expendedPart").focus(function() {
            jQuery(this).select();
         });
         
         /**
          * Whenever a user clicks on an encumbered amount textbox, select all contents.
          */
         jQuery(".encumberedPart").focus(function() {
            jQuery(this).select();
         });

         /**
          * Force these textboxes to the desired number format, ignoring non-numerics
          */
         jQuery(".encumberedPart, .expendedPart").change(function() {
            var value = jQuery(this).parse("#,##0.00");
            if (isNaN(value))
               value = 0;
            else
               value = value[0];
            jQuery(this).val(value).format("#,##0.00");
         });

         /**
          * When any of the textbox values is changed, recalculate the fields for that row.
          */
         jQuery(".personnelRow .allocationPart, .personnelRow .expendedPart, .personnelRow .encumberedPart").change(function() {
            computeReimbursementAmounts(".personnelRow");
         });
         jQuery(".equipmentRow .allocationPart, .equipmentRow .expendedPart, .equipmentRow .encumberedPart").change(function() {
            computeReimbursementAmounts(".equipmentRow");
         });
         jQuery(".trainingRow .allocationPart, .trainingRow .expendedPart, .trainingRow .encumberedPart").change(function() {
            computeReimbursementAmounts(".trainingRow");
         });
      }


      if (jQuery(".applicationForm")) {

/*
         jQuery("form").keypress(function(e) {
            window.alert("keypress");
           if (e.which == 13 && !jQuery(e.target).is("textarea")) {
              window.alert("enter");
             return false;
           }
         });
*/

         /**
			 * Retain the original selected value in the status dropdown at the time of page load.
			 */
			if (jQuery(".applicationStatus")) {
				statusValue = jQuery(".applicationStatus").val();
			}

			/**
			 * Add an event handler to the status dropdown to update the statusChanged global variable when the newly
			 * selected value does not match the value at page load.
			 */
			jQuery(".applicationStatus").change(function() {
				statusChanged = (jQuery(this).val() != statusValue);
			});

			/**
			 * When these textboxes receive mouse focus, automatically select all of the text in them.
			 */
			jQuery(".contingencyPart").focus(function() {
            jQuery(this).select();
			});
			jQuery(".mgmtPart").focus(function() {
				jQuery(this).select();
			});
			jQuery(".commishPart").focus(function() {
				jQuery(this).select();
			});
			jQuery(".scaoPart").focus(function() {
				jQuery(this).select();
			});
         jQuery(".applicantAmount").focus(function() {
            jQuery(this).select();
         });			

         /**
			 * When any of these text boxes change value, recalculate the number in the total field.
			 */
         totalValues(".contingencyPart, .contingencyPart-dis", ".contingencyTotal");
         totalValues(".mgmtPart, .mgmtPart-dis", ".mgmtTotal");
         totalValues(".commishPart, .commishPart-dis", ".commishTotal");
         totalValues(".scaoPart, .scaoPart-dis", ".scaoTotal");
         /*totalValues(".applicantAmount, .applicantAmount-dis", ".totalAmount"); */
			
			/**
			 * Trigger total calculations for each approval section.
			 */
			jQuery(".contingencyPart:first, .contingencyPart-dis:first").change();
			jQuery(".mgmtPart:first, .mgmtPart-dis:first").change();
			jQuery(".commishPart:first, .commishPart-dis:first").change();
			jQuery(".scaoPart:first, .scaoPart-dis:first").change();
         jQuery(".applicantAmount:first, .applicantAmount-dis:first").change();			
		}
	}
);

}


