﻿// JScript File for registration pages
//set focus to first field when page load
function focus_first_field()
{
    // loop through all forms on the page
    for(var f=0; f < document.forms.length; f++)
    {
        // set frm variable so we don't have to call 'document.forms[f]' everywhere
        var frm = document.forms[f];

        // loop through all fields in the form
        for(var x=0; x < frm.length; x++)
        {
            // set fld variable so we don't have to call 'document.forms[f][x]' everywhere
            var fld = frm[x];

            // use a try/catch block so that if anything fails we just go to the next field
            try
            {
                if(!fld.isDisabled && !fld.readOnly)
                {
                    //alert(canFocus(fld));
                    if( !canFocus(fld))
                    {
                        return;
                    }
                    // I want to handle different field types differently, so switch on the type
                    switch(fld.type)
                    {
                        // for text boxes, set the focus AND select the text, just like a Windows app
                        case 'text':
                        case 'password':
                            fld.select();
                            fld.focus();
                            return;
                        // for check boxes and radio buttons, set the focus to the one that is already
                        // checked in the group.
                        case 'checkbox':
                        case 'radio':
                            //alert("c");
                            // if it's not an array, there's only one, so focus on it
                            if(frm[fld.name].length == undefined)
                            {
                                //document.getElementByName(fld.name).focus();
                                fld.focus();
                            }
                            else
                            {
                                //alert(fld.name);
                               
                                // find which one is checked and focus on it
                                for(var y=0; y < frm[fld.name].length; y++)
                                {
                                    var fldtemp = frm[fld.name][y];
                                    
                                    //alert(fld.id);
                                    if(fldtemp.checked)
                                    {
                                        //var els = document.getElementsByName(fld.name);els[0].focus(); 
                                        //document.getElementById(fld.id).focus();
                                        fldtemp.focus();
                                        break;
                                    }
                                }
                                // if we didn't find the checked one, just focus on the first one
                                if(y == frm[fld.name].length)
                                    //document.getElementByName(fld.name)[0].focus;
                                    fld = frm[fld.name][0].focus();
                            }
                            return
                        // select boxes and buttons can just have a simple focus() call
                        case 'select-one':
                        case 'select-multiple':
                        case 'button':
                            fld.focus();
                            return;
                    }
                }
            }
            // if anything fails for any reason (hidden div, etc.), execution jumps to catch
            // then goes through the loop again
            catch(e)
            {
                //alert(e);
            }
        }
    }
}

//set focus to first field when page load
function focus_first_textbox()
{
    // loop through all forms on the page
    for(var f=0; f < document.forms.length; f++)
    {
        // set frm variable so we don't have to call 'document.forms[f]' everywhere
        var frm = document.forms[f]

        // loop through all fields in the form
        for(var x=0; x < frm.length; x++)
        {
            // set fld variable so we don't have to call 'document.forms[f][x]' everywhere
            var fld = frm[x]

            // use a try/catch block so that if anything fails we just go to the next field
            try
            {
                if(!fld.isDisabled && !fld.readOnly)
                {
                    // check if it is textbox, if it is focus
                    if(fld.type == 'text')
                    {
                        // for text boxes, set the focus AND select the text, just like a Windows app
                        fld.select();
                        fld.focus();
                        return true;
                    }
                }
            }
            // if anything fails for any reason (hidden div, etc.), execution jumps to catch
            // then goes through the loop again
            catch(e)
            {}
        }
    }
    return false;
}

//set focus to textbox when page load, 
//if there is not textbox, set to first field
function FocusPageFirstField()
{
    //if(!focus_first_textbox())
    {
        focus_first_field();
    }
}

function canFocus(el)
{
    if( window.document.body.clientHeight)/*window.document.body.offsetHeight*/
    {//check the el if is in the page not need to scroll
        elPosition = getElementPosition(el);
        if(elPosition < window.document.body.clientHeight)
        {
            return true;
        }
        else
        {
            return false;
        }
        
    }
    else
    {
        return true;
    }

}
function getElementPosition(el)
{
    var c = el, l = 0, t = 0;
    if( c.offsetParent )
    {
        for (; c.offsetParent; c = c.offsetParent)
        {
            //l += c.offsetLeft;
            t += c.offsetTop;
        }
    }
    else if( c.x && c.y)
    {
        //l += c.x;
        t += c.y;
    }
    else if(c.offsetTop && c.offsetLeft)
    {
        //l += c.offsetLeft;
        t += c.offsetTop;
    }
    if(el.offsetHeight)
    {
        t += el.offsetHeight;
    }
    return t;
}

//this function will only allow positive numbers, for now - DZ
function IsNumeric(strString, isDecimal)
{
    //DZ - 11/09/2007 - the negative is also allowed now.
   var strValidChars = "-0123456789";
   var strChar;
   var blnResult = true;
   
   if(isDecimal) strValidChars += ".";
   if (strString.length == 0) return false;

   //  test strString consists of valid characters listed above
    for (i = 0; i < strString.length && blnResult == true; i++)
    {
        strChar = strString.charAt(i);
        if (strValidChars.indexOf(strChar) == -1)
        {
            blnResult = false;
        }
    }
    return blnResult;
}

//set the object's error color if validation fails.
//currently used as the user is typing in a text box and also is implemented for just numeric validation
//the switch statement can be used to expand on the type of validation.
function SetErrorColor(obj, validationType, keyCode)
{
    if(keyCode != 0 && keyCode != 8) //we need to take into account tab and backspace key press
    {
        var stringToValidate = String.fromCharCode(keyCode);
        var isValid = false;
        if( obj != null )
        {
            //DZ - 11/09/07 - the negative symbol can only be at the very beginning of the string
            //alert(obj.value.indexOf("-"));
            if(stringToValidate=="-" && getSelectionStart(obj) > 0)
            {
                isValid = false;
            }
            else
            {
                switch(validationType.toLowerCase())
                {
                    case "decimal":
                        isValid = IsNumeric(stringToValidate, true);
                        var p = obj.value.indexOf(".", 0);
                        var dec = ".";
                        if(p > -1 && stringToValidate == dec)
                        {
                            obj.value = obj.value.replace(dec, "");
                        }
                        break;
                    case "integer":
                        isValid = IsNumeric(stringToValidate, false);
                        break;
                }
            }
            
            if(!isValid)
            {
                obj.style.color = "red";
                RevertColorToDefaultAfterTimeout(obj, 150);
            }
        }
    
        return isValid;
    }
    return true;
}

function RevertColorToDefaultAfterTimeout(obj, timeout)
{
    setTimeout("document.getElementById('" + obj.id + "').style.color='black'", timeout);
}

function GetEventObject(e)
{
    return (e.srcElement == null ? e.target : e.srcElement);
}

function GetKeyCode(e)
{
    return (window.event == null ? e.which : window.event.keyCode);
}

function ProcessEventResult(e, res)
{
    if(!res)
    {
        if(e.preventDefault)
        {
            e.preventDefault();
        }
    }
    return res;
}

//decimal validation
function DecimalValidate(e)
{
    var obj = GetEventObject(e);
    var keyCode = GetKeyCode(e);
    return ProcessEventResult(e, SetErrorColor(obj, "decimal", keyCode));
}

//validate integer fields or whole numbers
function IntegerValidate(e)
{
    var obj = GetEventObject(e);
    var keyCode = GetKeyCode(e);
    return ProcessEventResult(e, SetErrorColor(obj, "integer", keyCode));
}

//currently used for onblur events for decimal fields
function InjectCommas(e)
{
    var obj = GetEventObject(e);
    if(obj.value.length > 0)
    {
        var containsNegSymbol = obj.value.indexOf("-") > -1;
        //dz - 11/09/07 strip out the negative symbol as this does not affect comma injection algorithm
        var fieldValueToTest = obj.value.replace("-", "");
        //get the value
        var floatValue = parseFloat(fieldValueToTest).toString();
        var value = (floatValue.indexOf(".", 0) >=0 ? floatValue.split(".")[0] : floatValue);
        //keep everything after the decimal point
        var prec = (floatValue.indexOf(".", 0) >=0 ? "." + floatValue.split(".")[1] : "");
        var newValue = "";
        var counter = 1;
        for(x=value.length-1; x>=0; x--)
        {
            //need to re-build the string so we can inject commas where necessary.
            newValue = value.charAt(x) + newValue;
            //inject the commas at certain intervals
            if(counter % 3==0 && x > 0)
            {
                //alert(newValue);
                newValue = "," + newValue;
            }
            
            counter++;
        }
        
        //we need to preserve the original max length
        if(obj.originalMaxLength == null)
        {
            obj.originalMaxLength = obj.maxLength;
        }
        
        //DZ - 11/09/07 - need to support the potential for negative symbol
        var valueToDisplay = newValue + prec;
        if(containsNegSymbol) valueToDisplay = "-" + valueToDisplay;
        obj.maxLength = valueToDisplay.length;
        obj.value = valueToDisplay;
    }
}

//function used for onfocus to remove commas
function RemoveCommas(e)
{
    var obj = GetEventObject(e);
    obj.value = obj.value.replace(/,/g, "");
    
    //set the max length back to the original
    if(obj.originalMaxLength != null)
    {
        obj.maxLength = obj.originalMaxLength;
    }
}

//currently used for onblur events
function RemoveTrailingNonNumeric(e)
{
    var obj = GetEventObject(e);
    if(obj.value.lastIndexOf(".", obj.value.length - 1) == obj.value.length - 1)
    {
        obj.value = obj.value.replace(".", "");
    }
}

//wrapper around a couple of formatting functions
function FormatNumericField(e)
{
    RemoveTrailingNonNumeric(e);
    InjectCommas(e);
}

//DZ 12/04/07 - adding another wrapper for CFs so commas are not injected.  6191
//wrapper around a couple of formatting functions for custom fields
function FormatNumericFieldForCustomField(e)
{
    RemoveTrailingNonNumeric(e);
}

/*
    DZ - 11/09/07
    Extracted this from http://javascript.nwbox.com/cursor_position/cursor.js

*/

function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

function getSelectionEnd(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveStart('character', -o.value.length)
		return r.text.length
	} else return o.selectionEnd
}
