/** Page: javascript validation library
 *
 * Contains the functions to perform validation on input forms.
 * Checks that all required fields contain a value.
 * 
 * Note:  The inclusion of this file sets the onLoad event handler
 * for a page, it will also set an onsubmit event handler
 * for all forms within the page.  This may conflict with other
 * functionality needed.
 * 
 * Requires that string.js has been loaded.
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @copyright   Copyright (c) 2003 by International Studies Abroad Inc.
 * @version     $Id: validation.js,v 1.2 2009/09/15 13:48:22 fcheung Exp $
 * @package     Main
 * @subpackage  Javascript
 */
// capture existing onload events.
var prevOnload = window.onload;

// required to add the validate function to the forms
window.onload = updateForms;

formOnSubmitFuncs = new Array();

// Method: updateForms() {{{
/** Method: updateForms()
 *
 * Overwrites the onsubmit event handler with the validate required
 * variables function.
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @access      public
 * @return      boolean         true
 */
function updateForms() {
    // trigger existing onload events.
    if (prevOnload != null) {
        prevOnload();
    }
    len = document.forms.length;

    for (i = 0; i < len; i++) {
        formOnSubmitFuncs[document.forms[i].name] = document.forms[i].onsubmit;
        document.forms[i].onsubmit = valReq;
    }

    return true;
}
// }}}

// Method: sortInputIntoGroups() {{{
/** Method: sortInputIntoGroups()
 *
 * Given a form object, it's elements are sorted into
 * groups based on their names.
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @access      public
 * @param       object  form    html form object
 * @return      array           input elements array
 */
function sortInputIntoGroups(form) {
    groups = new Array();

    cnt = form.elements.length;

    for (i = 0; i < cnt; i++) {
        if (groups[form.elements[i].name] == undefined) {
            groups[form.elements[i].name] = new Array();
            groups[form.elements[i].name][0] = form.elements[i];
            groups[form.elements[i].name][0]['required'] = form.elements[i].getAttribute('required');
        } else {
            len = groups[form.elements[i].name].length;
            groups[form.elements[i].name][len] = form.elements[i];
            groups[form.elements[i].name][len]['required'] = form.elements[i].getAttribute('required');
        }
    }

    return groups;
}
// }}}

// Method: validateSingleInputElement() {{{
/** Method: validateSingleInputElement()
 *
 * Determines if a value has been set for a single element.
 * Only considers the following input types:
 *  input type=file
 *  input type=text
 *  textarea
 *  select box
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @access      public
 * @param       object  elem    html input element object
 * @return      boolean         true if set
 */
function validateSingleInputElement(elem) {
    set = false;

    switch (elem.tagName) {
        case 'INPUT':
            if (elem.type == 'text' || elem.type == 'file') {
            	//var sval = elem.value;
                if (elem.value != null && elem.value.replace(/\s+/gi, '') != "") {
                    set = true;
                }
            }
            break;
        case 'SELECT':
            if (-1 != elem.selectedIndex && 0 != elem.options[elem.selectedIndex].value)
            {
                set = true;
            }
            break;
        case 'TEXTAREA':
            if (elem.value != null && elem.value.trim() != "") {
                set = true;
            }
            break;
        // no default
    }

    return set;
}
// }}}

// Method: validateInputGroup() {{{
/** Method: validateInputGroup()
 *
 * Determines if a value has been set within a group of elements.
 * Only considers the following input types for a group:
 *  input type=file
 *  input type=text
 *  input type=radio
 *  input type=checkbox
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @access      public
 * @param       object  group   array of html input element objects
 * @return      boolean         true if set
 */
function validateInputGroup(group) {
    set = false;
    len = group.length;

    for (i = 0; i < len; i++) {
        if (group[i].tagName == 'INPUT') {
            switch (group[i].type) {
                case 'radio':
                    // fall through
                case 'checkbox':
                    if (group[i].checked) {
                        set = true;
                    }
                    break;
                case 'file':
                    // fall through
                case 'text':
                    if (group[i].value != null && group[i].value.replace(/\s+/gi, '') != "") {
                        set = true;
                    }
                    break;
                // no default
            }
        }
    }

    return set;
}
// }}}

// Method: valReq() {{{
/** Method: valReq()
 *
 * Validates that all required input elements of the form
 * have been given a value.  If this is not true, then
 * the form is not submitted and an error message is 
 * delivered to the user via an alert box.
 *
 * @author      Katherine Carr <kcarr@studiesabroad.com>
 * @access      public
 * @return      boolean     true on success
 */
function valReq() {
    form = this;
    rc = false;
	serviceCheckPass = true;
	otherCapacityCheckPass = true;
	disciplineCheckPass = true;

    groups = sortInputIntoGroups(form);

    missingReq  = false;
    reqMsg      = '';
    for (name in groups) {
        if (groups[name][0]['required'] != undefined 
            || (groups[name][0]['hasAttribute'] != undefined && groups[name][0].hasAttribute('required'))) 
        {
            set = false;
            if (groups[name].length == 1) {
               set = validateSingleInputElement(groups[name][0]);
            } else {
               set = validateInputGroup(groups[name]);
            }

            if (false == set) {
                missingReq  = true;
                if (groups[name][0]['hasAttribute'] != undefined && groups[name][0].hasAttribute('required')) {
                    reqMsg += "\t" + groups[name][0].getAttribute('required') + "\n";
                } else {
                    reqMsg += "\t" + groups[name][0]['required'] + "\n";
                }
            }
        }
    }
	/** Form specific check - LPI Global Impact Skills Accessement Form checking less than 3 skills entered	{{{
	*/
	if (form.name == 'skillsForm') {
		serviceCheckPass = valServiceArea(form);
		if (!serviceCheckPass) {
			missingReq = true;
			reqMsg += "\tPlease indicate THREE service areas!\n";
		}
	}
	// }}}

	/** Form specific check - LPI Teacher Recommendation Form checking capacity == other and discipline == yes if so make text-area: otherCapacity and discipline-comments manatory	{{{
	*/
	if (form.name == 'teacherrecForm') {
		otherCapacityCheckPass = valOtherCapacity(form);
		// = val
		if (!otherCapacityCheckPass) {
			if (form.otherCapacity.value == null || form.otherCapacity.value.trim() == "") {
				missingReq = true;
				reqMsg += "\tPlease describe how you know the student\n";
			}
		}

		disciplineCheckPass = valDiscipline(form);
		if (!disciplineCheckPass) {
			if (form.disciplineComments.value == null || form.disciplineComments.value.trim() == "") {
				missingReq = true;
				reqMsg += "\tPlease elaborate disciplinary problems of the student\n";
			}
		}

	}
	// }}}


    if (true == missingReq) {
        msg = "Some of the required fields in this form are not filled in.\n"
            + reqMsg;
        alert(msg);

        rc = false;
    } else {
        rc = true;
    }

    if (formOnSubmitFuncs[form.name]) {
        func = formOnSubmitFuncs[form.name];
        rc2 = func.call();

        if (rc == true && rc2 == true) {
            rc = true;
        }
    }

    return rc;
}
// }}}

// Method : valServiceArea(form) {{{
/** Method : valServiceArea(form)
 *  Form sepcific checking 3 checkboxes are checked
 */
function valServiceArea(form) {
     form = document.forms['skillsForm'];
	 var total = 0;
	 var max = form.service.length;
	 var result = false;
	 for (var idx = 0; idx < max; idx++) {
		 if (eval("document.forms['skillsForm'].service[" + idx + "].checked") == true) {
			 total += 1;
		 }
	 }
	 if (total == 3)    {
		 result  = true;
	 }
	return result;
}
// }}}

function valOtherCapacity(form) {
     form = document.forms['teacherrecForm'];
	 var result = true;
	 if (form.capacity[4].checked == true) {
			 result = false;
	 }
	return result;
}
function valDiscipline(form) {
     form = document.forms['teacherrecForm'];
	 var result = true;
	 if (form.discipline[0].checked == true) {
			 result = false;
	 }
	return result;
}
