var helpWindow = null;
var letterWindow = null;

function openHelpWindow(URL) {
  helpWindow = window.open(URL,"NCSHelp","resizable=yes,scrollbars=yes,toolbar=yes,height=475,width=466");
  return false;
}

function openLetterWindow(URL) {
  letterWindow = window.open(URL,"NCSSchoolhouseLetter","resizable,scrollbars,height=480,width=640");
  return false;
}

function setFormSubmit(action, cmd) {
  document.controller.action = removeLeadingSlash(action);
  document.controller.cmd.value = cmd;
  if( document.controller.subcmd != null)
    document.controller.subcmd.value = '';
  document.controller.submit();
  return false;
}

function setForm(action, cmd) {
  document.controller.action = removeLeadingSlash(action);
  document.controller.cmd.value = cmd;
}

function findControlByName(form, name){
  var i = 0;
  for( i=0; i<form.elements.length; i++ ) {
    if( form.elements[i].name  == name ) {
      return form.elements[i]
    }
  }
  return null;
}
function removeLeadingSlash(action){
	if (action.charAt(0) == '/')
		return action.substr(1);
	else
  	return action;
}


// Submits a command to the controller servlet and specifies a sub-command that 
// should be processed by the invoked command object.
// NOTE : This function assumes that the "action", "cmd", and "subcmd" parameters 
// are defined as input parameters on the form.  
function submitCommand( action, cmd, subCmd )
{
  document.controller.action = removeLeadingSlash(action);
  document.controller.cmd.value = cmd;
  document.controller.subcmd.value = subCmd;
  document.controller.submit();
  return false;
}

// Submits a sub-command to the default form command.
// NOTE : This function assumes that the "action", "cmd", and "subcmd" parameters 
// are defined as input parameters on the form.  The "action" and "cmd" parameters 
// must be initialized to the appropriate values which specify the default command 
// for the form.
function submitCommandToSelf( subCmd )
{
//  alert('submiting command to self : cmd='+document.controller.cmd.value+' subcmd='+subCmd);
  document.controller.subcmd.value = subCmd;
  document.controller.submit();
  return false;
}

// Submits a command which will select the specified customer ID and then
// display the "home" page to the user.
function selectCustomer(customerId)
{
  document.controller.customer_id.value = customerId;
  submitCommand('/Main', 'customer_selected','');
  return false;
}

/*
*  in IE, forms can be reset by pressing the Esc key twice. We need to catch this and
* throw it out, since we use custom reset commands in many forms.
*
*/
function catchKeyDown(e){
    if(window.event&&window.event.keyCode==27) // esc key in IE only
       return false;
}



//when called by an onkeydown attribute of an element, this
//will prohibit all non-numeric characters.

//USAGE: onKeyDown="return numericOnly(event)"

function numericOnly(e){
    var keycode = getKeyCode(e);
    var metakeys = getMetaKeys(e);
    var keychar = String.fromCharCode(keycode);

                                                //   allow the following:
                                                //------------------------
    return( metakeys.ctrlKey  ||                // ctrl + anything
            metakeys.altKey   ||                // alt + anything
            keycode == 9      ||                // tab
            keycode == 8      ||                // backspace
            keycode == 46     ||                // delete
           (32 < keycode && keycode < 37  ) ||  // home, end, pgup, pgdn
           (36 < keycode && keycode < 41  ) ||  // arrow keys
           (95 < keycode && keycode < 106 ) ||  // keypad numbers
           ( !metakeys.shiftKey &&              // regular numbers without shift
                     ( /\d/.test(keychar)))
    )
}

//get the keycode from a keypress event (keyup, keydown)
function getKeyCode(e){
    if(window.event) //ie
        return window.event.keyCode
    if(e) //DOM
        return e.which;
}

//return an object containing the meta-keys for an event. window.event == ie, e == dom
function getMetaKeys(e){
    return {
        "ctrlKey" : ( window.event && ( window.event.ctrlKey  || window.event.ctrlLeft  ) ) || ( e && e.ctrlKey  ),
        "altKey"  : ( window.event && ( window.event.altKey   || window.event.altLeft   ) ) || ( e && e.altKey   ),
        "shiftKey": ( window.event && ( window.event.shiftKey || window.event.shiftLeft ) ) || ( e && e.shiftKey ),
        "metaKey" : ( window.event && false ) || ( e && e.metaKey )
    };
}

//returns the source of an event
function getEventSrc(e){
    if(window.event) //ie
        return window.event.srcElement;
    if(e){ //DOM
        return e.target;
    }
}

/* add to onKeyUp to restrict the size of a textarea */
function maxTextAreaSize(e,maxSize){

    var src = getEventSrc(e);
    var key = getKeyCode(e);
    /*if(src.value.length > maxSize) {
      //  alert(src.value.length+","+maxSize);

        setTimeout(function(){
            if(change)
                change();   //hack for Record Changes
            src.value = src.value.substring(0, maxSize);
            src.scrollTop = src.scrollHeight;
        },100);

    }
    */
    textLimit(src,maxSize);
}

/*function textLimit(field, maxlen) {
    if (field.value.length > maxlen + 1)
    alert('your input has been truncated!');
    if (field.value.length > maxlen)
    field.value = field.value.substring(0, maxlen);
} */

/*this function does pretty much the same thing as maxTextAreaSize,
 but it displays an alret to let the user know the input has been truncated and for some reason
 maxTextAreaSize does not always count a hard return and textLimit does.*/
function textLimit(field, maxlen)
{
    var extra = 0;

   if(change)
        change();

    if (field.value.length > maxlen)
    {

        if(change)
        change();
        field.value = field.value.substring(0, maxlen);
        field.scrollTop = field.scrollHeight;
        alert('Your input has been truncated, there is a maximum of 250 characters allowed in this field.');
    }

    if (navigator.appName=="Netscape")
    {
       // alert("Firefox");
        var index = field.value.indexOf('\n');

        while(index != -1)
        {
            extra += 1;
            index = field.value.indexOf('\n',index+1);
        }
    }

    if (field.value.length + extra > maxlen)
      field.value = field.value.substring(0, maxlen-extra);
//    else
//      cntfield.value = maxlimit - field.value.length - extra;

}

/*only accepts Numbers keycode 48-57 are numbers 0-9, keycode 8 is backspace and keycode 0 is Delete */
 function intOnly(ctrl,e)
{
        var keycode;
        if (window.event) keycode = window.event.keyCode;
        else if (e) keycode = e.which;
  //      alert(keycode);
        if((keycode>=48&&keycode<=57) || (keycode==8 || keycode==0))
            return true;
        return false;
}
// Michigan Javascript
<!-- customer javascript -->
function LaunchWindow(p_str) 
{
	window.open(p_str,'shderWin','toolbar=0,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=750,height=500');
}
function FooterLaunchWindow(p_str) 
{
	window.open(p_str,'footerWin','toolbar=0,location=1,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=750,height=500');
}
<!-- end customer javascript -->


/**************************************
    Record Changes Save Registry:

    - use RecordChangesSaveRegistry.register(func) to register a function.
    - func will be called when the user saves a student.
    - you may register as many functions as you want.
    - all functions will be called. if any of them return false, the student will not be saved.

    example:
    RecordChangesSaveRegistry.register(function(){
        alert('Saving student now');
    });
****************************************/
var RecordChangesSaveRegistry = (function (){
    //private static
    var registry = [];

    function runAll(){
        var i;
        var success = true;
        for(i=0; i< registry.length; i++){
            if(registry[i]() == false)
                success = false;
        }
        return success;
    }

    var save_func;

    function replaceSaveFunction(){
        if(!save_func){
            save_func = submitCommand;
            submitCommand = function(action, cmd, subCmd){
                if(action=='RecordChanges'&&cmd=='rec_chg_student_update'&&(subCmd=='student_save'||subCmd=='student_history')){
                    if(runAll())
                        save_func(action, cmd, subCmd);
                    else
                        change();
                }
                else{
                    save_func(action, cmd, subCmd);
                }
            }
        }
    }

    return {
        //public static
        register: function(func){
            replaceSaveFunction();
            registry.push(func);
        }
    };
})();

function checkvalidDate(theMonth,theDay,theYear)
{
    var leapYear = false;
    var validMonth = true;
    var validDay = true;
    var validYear = true;

    if (theYear=="" && (theMonth!="" || theDay!=""))
        validYear = false;    

    if ( (theYear%400)==0 || ((theYear%100)!=0 && (theYear%4)==0) )
        leapYear = true;

    if (theMonth>12 || theMonth==0 )
        validMonth = false;

    if (theDay>31 || theDay==0)
        validDay = false;

    if (theDay>30 && (theMonth==4 || theMonth==6 || theMonth==9 || theMonth==11))
        validDay = false;

	if (theMonth==2 && theDay>29)
		validDay = false;
    else if (theMonth==2 && !leapYear && theDay==29)
        validDay = false;

if (!validMonth || !validDay || !validYear)
    return false;
else
    return true;

}

function isValidDate(monthElemId, dayElemId, yearElemId, isBlankValid)
{
	var dobMM = document.getElementById(monthElemId).value+"";
	var dobDD = document.getElementById(dayElemId).value+"";
	var dobYYYY = document.getElementById(yearElemId).value+"";
	var dobValue = dobMM+dobDD+dobYYYY;
	var validDate = checkvalidDate(dobMM,dobDD,dobYYYY);
	
	if (isBlankValid)
		return (validDate || (dobValue==""));
	else
		return validDate;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

