/*
 * Steve's Simple PHP Forms
 * Javascript Form Validator
 *
 * This script is open source, free for use and modification.
 * Please leave this notice in tact to credit me for creating it.
 *
 * Author: Steven Moseley
 * Homepage: http://www.stevenmoseley.com
 * Business: http://www.transio.com
 *
 * Fixed by T. Silverstein (did not work in IE).
 *
 */

// Validates all fields in the specified form
function validate(form) {
    var inputs = form.getElementsByTagName('*');
    var valid = true;
    var message = '';

    var radioNames = new Array();
    var checkboxNames = new Array();
    
    // Search for invalid inputs
    var i;
    for (i = 0; i < inputs.length; i++) {
        var ok = true;
        var input = inputs[i];
        // var inputClass = input.getAttribute('class') ? input.getAttribute('class') : '';
        var inputClass = input.className;
        
        var tagName = input.tagName ? input.tagName : '';
        var name = input.getAttribute('name') ? input.getAttribute('name') : '';
        var title = input.getAttribute('title') ? input.getAttribute('title') : '';
        var required = inputClass.indexOf('required') >= 0;
        var minlength = !isNaN(input.getAttribute('minlength')) && input.getAttribute('minlength') > 0 ? input.getAttribute('minlength') : 0;
        var maxlength = !isNaN(input.getAttribute('maxlength')) && input.getAttribute('maxlength') > 0 ? input.getAttribute('maxlength') : 0;
        var format = input.getAttribute('format') ? input.getAttribute('format') : '';
        var confirmName = name.indexOf('confirm_') == 0 ? name.substr(8) : '';
    
        // Required radio list
        if (required && input.getAttribute('type') == 'radio') {
            checked = checkMulti(name);
            if (!checked) {
                alreadyAccountedFor = false;
                for(var j=0;j<radioNames.length;j++){
                    if(radioNames[j]==name) alreadyAccountedFor = true;
                }
                if(!alreadyAccountedFor){
                    radioNames.push(name);
                    message += '"' + name + '" is required.  Please select one.\n';
                    ok = false;
                }
            }
        }

        // Required checkbox list
        if (required && input.getAttribute('type') == 'checkbox') {
            checked = checkMulti(name);
            if (!checked) {
                alreadyAccountedFor = false;
                for(var j=0;j<checkboxNames.length;j++){
                    if(checkboxNames[j]==name) alreadyAccountedFor = true;
                }
                if(!alreadyAccountedFor){
                    checkboxNames.push(name);
                    message += '"' + name + '" is required.\n';
                    ok = false;
                }
            }
        }
        
        // Required Input test
        if (required && minlength <= 0 && format.length == 0) {
            if (tagName == 'select') {
                if (!input.options || input.options.length == 0 || !input[input.selectedIndex].value || input[input.selectedIndex].value == '') {
                    message += '"' + title + '" is required.  Please make a selection.\n';
                    ok = false;
                }
            } else {
                if (input.value.length == 0) {
                    message += '"' + title + '" is a required field.\n';
                    ok = false;
                }
            }
        }

        // Minlength test
        if (minlength > 0) {
            if (input.value.length < minlength) {
                message += '"' + title + '" has a minimum required length of ' + minlength + ' characters.\n';
                ok = false;
            }
        }

        // Maxlength test
        if (maxlength > 0) {
            if (input.value.length > maxlength) {
                message += '"' + title + '" has a maximum length of ' + maxlength + ' characters.\n';
                ok = false;
            }
        }

        // Format test
        if (format.length > 0) {
            if (format.toLowerCase() == 'email') {
                if (input.value.indexOf('@') <= 0 || input.value.indexOf('.') <= 0  || input.value.length < 6) {
                    message += '"' + title + '" is not a valid email address.\n';
                    ok = false;
                }
            } else if (format.toLowerCase() == 'mmdd') {
                //var mm = input.value.substring(0, 2);
                //var dd = input.value.substring(2);
                if (input.value.length < 4 || Math.isNaN(input.value)) {
                    message += '"' + title + '" is not a proper MMDD date format.\n';
                    ok = false;
                }
            } else if (format.toLowerCase() == 'numeric') {
                if (!isFloatingPointNumber(input.value)) {
                    message += '"' + title + '" must be a number.\n';
                    ok = false;
                }
            } else if (format.toLowerCase() == 'int') {
                if (!isInt(input.value)) {
                    message += '"' + title + '" must be a whole number.\n';
                    ok = false;
                }
            }

            // Regular Expressions
            //regex = input.format;
            //ok = ok && regex.exec(input.value);

        }

        // Confirm input test
        if (confirmName.length > 0) {
            confirmInput = document.getElementById(confirmName);
            if (confirmInput && input.value != confirmInput.value) {
                confirmTitle = confirmInput.getAttribute('title') ? confirmInput.getAttribute('title') : 'Input';
                message += '"' + confirmTitle + '" and "' + title + '" do not match.\n';
                ok = false;
            }
        }

        // Focus on first bad input
        if (required) {
            if (!ok) {
                if (input.getAttribute('errorElement') != null) {
                    redLabel = document.getElementById(input.getAttribute('errorElement'));
                    redLabel.style.backgroundColor = '#F55';
                }
                else {
                    input.style.backgroundColor = '#F55';
                    input.style.color = '#FFF';
                }
                if (valid) {
                    try {
                        input.focus();
                    } catch (e) {}
                }
                valid = false;
            } else {
                if (input.getAttribute('errorElement') != null) {
                    redLabel = document.getElementById(input.getAttribute('errorElement'));
                    redLabel.style.backgroundColor = '#FFF';
                }
                else {
                    input.style.backgroundColor = '';
                    input.style.color = '';
                }
            }
        }
    }
    if (message.length > 0) {
        window.alert(message);
    }
    return valid;
}

function checkMulti(name) {
    var inputs = document.getElementsByName(name);
    var checked = false;
    var i;
    for (i = 0; i < inputs.length; i++) {
        var input = inputs[i];
        checked = checked || input.checked;
    }
    return checked;
}

function allowOnlyFloatingPointNumbers(textbox, val){

    val = val.replace(/[^0-9.-]/g, ''); // strip non-digit chars
    val = stripDuplicateChars(val, '.', 1, 0); // strip excess decimals
    val = stripDuplicateChars(val, '-', 0, 1); // strip excess minus signs
    textbox.value = val; // replace textbox value
    if (!isFloatingPointNumber(val)){ alert('This is not a valid number, please correct it...');}
}

function isFloatingPointNumber(val) {
    return isNumeric(val, false);
}

function isInt(val) {
    return isNumeric(val, true);
}

function isNumeric(val, isInt) {
    var validChars = "0123456789" + (isInt ? "" : ".");
    var isNumber = true;
    for (var i = 0; i < val.length && isNumber == true; i++) {
        var char = val.charAt(i);
        isNumber = isNumber && validChars.indexOf(char) > -1;
    }
    return isNumber;
}

function stripDuplicateChars(str, strip, n, s){
    var count=0; var stripped=str.substring(0, s); var chr;
    for (var i=s; i<str.length; i++){ chr = str.substring(i, i+1);
        if (chr == strip) {
            count++;
            if (count<n+1) {
                stripped = stripped + chr;
            }
        } else {
            stripped = stripped + chr;
        }
    }
    return stripped;
}

// Focuses on the first <input> or <select> field in the specified form
function focusForm(formId) {
    var elements = (formId)
            ? document.getElementById(formId).getElementsByTagName('*')
            : document.getElementsByTagName('*');
    for (var i = 0; i < elements.length; i++) {
        input = elements[i];
        if (input.tagName.toLowerCase() == 'input' ||
                input.tagName.toLowerCase() == 'select') {
            input.focus();
            break;
        }
    }
    return true;
}

function toggleCheckbox(id) {
    var checkbox = document.getElementById(id);
    checkbox.checked = !checkbox.checked;
}

// Shows or hides the specified form
function showForm(formId) {
    document.getElementById(formId).style.display = '';
    document.getElementById('hide_' + formId).style.display = '';
}

function hideForm(formId) {
    document.getElementById(formId).style.display = 'none';
    document.getElementById('hide_' + formId).style.display = 'none';
}

function confirmDelete(itemName, deleteUrl) {
    if (window.confirm('Are you sure you want to delete:\n' + itemName + '?')) {
        window.location = deleteUrl;
    }
}

function loadSelected(pageUrl, selectField, persistedParameters) {
    var idName = selectField.name;
    var id = selectField[selectField.selectedIndex].value;
    if (id > 0) {
        var location = pageUrl + '?' + idName + '=' + id;
        for (var i = 0; i < persistedParameters.length; i++) {
            location += '&' + persistedParameters[i][0] + '=' + persistedParameters[i][1];
        }
        window.location.href = location;
    }
}

function loadType(typeField) {
    var typeId = typeField[typeField.selectedIndex].value;
    var subtypeField = document.getElementById("listing_subtype_id");
    for (var i = 0; i < subtypeField.length; i++) {
        var option = subtypeField[i].id;
        var optionTypeId = option.substring(option.indexOf("_") + 1, option.indexOf("."));
        if (optionTypeId == typeId || optionTypeId == '') {
            subtypeField[i].style.display = '';
        } else {
            subtypeField[i].style.display = 'none';
        }
    }
}



function getParameter(key) {
    var querystring = window.location.search.substring(1);
    var parameters = querystring.split('&');
    for (var i = 0; i < parameters.length; i++) {
        var pos = parameters[i].indexOf('=');
        if (pos > 0) {
            if (key == parameters[i].substring(0, pos)) {
                return '&' + parameters[i];
            }
        }
    }
    return '';
}

function popWindow(url, width, height) {
    var popup = window.open(url, 'popup', 'width=' + width + ', height=' + height + ', toolbars=no,  status=no, menu=no, scrollbars=yes');
}
