/*
    Class with methods for formatting strings.

    Requires trim()-method defined in service_common.js
*/
function Formatter() {

   /*
        Trims whitespaces from all text-, textarea- and file-fileds

        Parameter:  theForm - Form-object
    */
    Formatter.prototype.trimAllFields = function(theForm) {

        elements = theForm.elements;

        for (i = 0; i < elements.length; i++) {
            element = elements[i];

            if (element.type == 'text' || element.type == 'textarea') {
                element.value = element.value.trim();
            }
        }
    }

    /*  Format zipcode. First use Validator.checkZipcode(zipcode) to validate

        Parameter:   zipcode - Zipcode to format
        Return:      zipcode - Formatted zipcode (if length equals 5) */
    Formatter.prototype.formatZipCode = function (zipcode) {

        // Remove whitespaces
        zipcode = zipcode.replace(/\s/g,"");

        // check if length == 5
        if (zipcode.length != 5) {
            return zipcode;
        }

        return (zipcode.substring(0,3) + " " + zipcode.substring(3,5));
    }

/*  Format phonenumber. First use Validator.checkPhone(phone) to validate

    Parameter:   phone - Phone number to format
    Return:      phone - Formatted phone */
    Formatter.prototype.formatPhoneNumber = function (phone) {

        tmpPhone = phone.replace(/\s/g,"");

        if (tmpPhone == '' || tmpPhone.indexOf("-") == -1) {
            return phone;
        }
        var areacode = "";
        var phonenumber    = "";

        areacode = tmpPhone.substring(0,tmpPhone.indexOf("-"));
        phonenumber = tmpPhone.substring(tmpPhone.indexOf("-") + 1);

        var phoneregexp = /^\d+$/;

        if (!phoneregexp.test(phonenumber)) {
            return phone
        }

        if (phonenumber.length == 5) {
            phonenumber = phonenumber.substring(0,3) + " " +
            phonenumber.substring(3);
        } else if (phonenumber.length == 6) {
            phonenumber = phonenumber.substring(0,2) + " " +
            phonenumber.substring(2,4) + " " + phonenumber.substring(4);
        } else if (phonenumber.length == 7) {
            phonenumber = phonenumber.substring(0,3) + " " +
            phonenumber.substring(3,5) + " " + phonenumber.substring(5);
        }

        return (areacode + "-" + phonenumber);
    }
}
