/*
Copyright (c) 2008 oathouse.com ltd
@author 	Nick Maunder
@version 	1.00 2008/9/16
Description: provides a single generic process for basic in-page validation
of form data.

Requires validations array to have been built in the page:
this holds DOM location of field, test to be carried out,
message to be displayed if test fails.

example:
validations.push(["document.auction.contactName", "notBlank", " - please enter a contact name for the pickup"]); 
Requires error div element to be in page: <div id="errors">

 */
var messages;
var errors;

function validateAndSubmit(form, errorHeader) {

    if(!validate(errorHeader)) {
        window.scrollTo(0,0);
        return(false);
    }
    form.submit();
    return true;
}

function validate(errorHeader) {

    //alert("number of validations: " + validations.length);

    messages = new Array();

    var checkToMake;
    var field;
    var message;

    var goodToSubmit = true;
    errors = document.getElementById("errors");
    errors.innerHTML = "";

    for(var i = 0; i<validations.length; i++) {

        field = eval(validations[i][0]);
        checkToMake = validations[i][1];
        message = validations[i][2];

        switch(checkToMake) {
            case("notBlank"):
                if(isEmpty(field.value)) {
                    messages.push(message);
                    highlight(field);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("appearsEmail"):
                if(!looksLikeEmail(field)) {
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("matchEmail"):
                if(!matchEmails()) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else if(!looksLikeEmail(field)) {
                    highlight(field);
                }
                else {
                    dimlight(field);
                }
                break;

            case("isInteger"):
                if(!isInteger(field)) {
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("isIntegerOrBlank"):
                if(!isIntegerOrBlank(field)) {
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("isFloat"):
                if(!isFloat(field)) {
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("isGreaterThanZero"):
                if(!isGreaterThanZero(field)) {
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("validPassword"):
                if(!isValidPassword(field)) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("blankOrValidPassword"):
                if(isEmpty(field.value)) {
                    dimlight(field);
                }
                else if(!isValidPassword(field)) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(field);
                }
                break;

            case("matchPassword"):
                if(!matchPasswords()) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else if(!isValidPassword(field)) {
                    highlight(field);
                }
                else {
                    dimlight(field);
                }
                break;

            case("blanksMatchPassword"):
                if(!matchPasswords()) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else if(isEmpty(field.value)) {
                    dimlight(field);
                }
                else if(!isValidPassword(field)) {
                    highlight(field);
                }
                else {
                    dimlight(field);
                }
                break;

            case("blanksMatchAdminPassword"):
                if(!matchAdminPasswords()) {
                    highlight(field);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else if(isEmpty(field.value)) {
                    dimlight(field);
                }
                else if(!isValidPassword(field)) {
                    highlight(field);
                }
                else {
                    dimlight(field);
                }
                break;

            case("checked"):
                var wrap = field.parentNode;
                if(!field.checked) {
                    highlightCheckbox(wrap);
                    messages.push(message);
                    goodToSubmit = false;
                }
                else {
                    dimlight(wrap);
                }
                break;

            default:
                // do nothing
            // end cases
        }
    }

    if(!goodToSubmit) {
        createErrorMessage(errorHeader);
    }
    return(goodToSubmit);
}

// validation methods     
function isEmpty(str) {
	
    if(str == null || str.length == 0) {
        return(true);
    }

    // test returns false if there is at least one non-whitespace
    // this means that the string is not empty
    // if the test returns true, the string is empty
    return(!/\S/.test(str));
}

function looksLikeEmail(field) {
    var s = field.value;

    if(isEmpty(s)) {
        highlight(field);
        return(false);
    }

    // check format: OK
    if(/[\w-]+@([\w-]+\.)+[\w-]+/.test(s)) {
        dimlight(field);
        return(true);
    }
    // not OK
    highlight(field);
    return(false);	
}

function matchEmails() {
	
    var email = document.getElementById(emails[0]).value;
    var emailConfirmation = document.getElementById(emails[1]).value;

    return(email == emailConfirmation);
}

function isInteger(field) {
    var s = field.value;

    if(isEmpty(s) || s.length>10) {
        highlight(field);
        return(false);
    }
    // check for numbers: OK
    if(/^-?\d+$/.test(s)) {
        dimlight(field);
        return(true);
    }
    // Not OK
    highlight(field);
    return(false);	
}

function isIntegerOrBlank(field) {
    var s = field.value;

    if(isEmpty(s)) {
        dimlight(field);
        return(true);
    }
    if(s.length>10) {
        highlight(field);
        return(false);
    }
    // check for numbers: OK
    if(/^-?\d+$/.test(s)) {
        dimlight(field);
        return(true);
    }
    // Not OK
    highlight(field);
    return(false);
}

function isFloat(field) {
    var s = field.value;

    if(isEmpty(s) || s.length>11) {
        highlight(field);
        return(false);
    }
    // may be negative
    if(s.substr(0, 1)=="-") {
        s = s.substr(1, s.length);
    }

    // check for float: OK
    // either an integer or a floating dec point
    if((/^\d+\.\d+$/.test(s)) || (/^\d+$/.test(s))) {
        dimlight(field);
        return(true);
    }
    // Not OK
    highlight(field);
    return(false);	
}

function isGreaterThanZero(field) {

    if(!isFloat(field)) {
        return(false);
    }
    var s = field.value;
    if(s>0) {
        return(true)
    }
    highlight(field);
    return(false);
}

function isValidPassword(field) {
    var s = field.value;

    // check for correct characters: needs to be word characters only and 
    //  more than 8 characters: 
    // if OK return true
    if(/[a-zA-Z0-9]{8,}/.test(s)) {
        dimlight(field);
        return(true);
    }
    // Not OK
    highlight(field);
    return(false);	
}

function bothDates() {

    //alert("elements: " + searchDates[0] + ", " + searchDates[1]);

    var date0 = document.getElementById(searchDates[0]).value;
    var date1 = document.getElementById(searchDates[1]).value;

    //alert("dates: " + date0 + ", " + date1);

    return((date0 == "dd/mm/yyyy" && date1 == "dd/mm/yyyy") ||
        (date0 != "dd/mm/yyyy" && date1 != "dd/mm/yyyy"));
}

function matchPasswords() {
	
    var password = document.getElementById(passwords[0]).value;
    var passwordConfirmation = document.getElementById(passwords[1]).value;
    return(password == passwordConfirmation);
}

function matchAdminPasswords() {

    var password = document.getElementById(passwords[2]).value;
    var passwordConfirmation = document.getElementById(passwords[3]).value;
    return(password == passwordConfirmation);
}

// colours for fields
function highlight(field) {
    field.style.backgroundColor = "#ccf";
    field.style.borderColor = "#c00";
}

function highlightCheckbox(field) {
    field.style.backgroundColor = "#c00";
    //field.style.borderColor = "#c00";
}

function dimlight(field) {
    field.style.backgroundColor = "#fff";
    field.style.borderColor = "#777";
}

// build and display error message
function createErrorMessage(errorHeader) { 

    if(errors==undefined) {
        errors = document.getElementById("errors");
    }
    var message = "<p>" + errorHeader + "<br />";    
    for(var i = 0; i<messages.length; i++) {
        message += (messages[i] + "<br />");
    }
    message += "</p>";
    errors.innerHTML = message;
}
