function primeForm() {

    // Handle copy of form submit to form objective
    $('.form_field[type=submit]').click( function() {
        $(this).closest('form').children('input[name=objective]').val($(this).attr('name'));
    });

    // Multitext in form
    $('.form_expander input').keyup(function() {
        if ($(this).val() != '' && $(this).closest('.form_expander').is(':last-child')) {
            var org = $(this).closest('.form_validate_elementcontainer');
            // Destroy providers if present
            if (org.hasClass('form_customerprovider') ||
                org.hasClass('form_todoprovider') ||
                org.hasClass('form_projectprovider') ||
                org.hasClass('form_caseprovider') ||
                org.hasClass('form_buyerprovider')) org.find('input').autocomplete('destroy');

            $(this).closest('.form_expander').clone(true).insertAfter($(this).closest('.form_expander')).find('input').val('');
            
            // Reapply providers
            if (org.hasClass('form_customerprovider')) form_customer_provider(org);
            if (org.hasClass('form_todoprovider')) form_todo_provider(org);
            if (org.hasClass('form_projectprovider')) form_project_provider(org);
            if (org.hasClass('form_caseprovider')) form_case_provider(org);
            if (org.hasClass('form_buyerprovider')) form_buyer_provider(org);
        }
    })

    // Field that replicates
    $('.form_expander input').change(function() {
        if ($(this).val() == '' && ! $(this).closest('.form_expander').is(':only-child')) {
            $(this).closest('.form_expander').remove();
        }
    })

    // Repeat interface
    $('.form_handle_repeater').change(form_repeat_change);
    $('.form_handle_repeater').each(form_repeat_change);


    // Error trigger
    $.fn.triggerError = function (txt) {
        this.each(function() {
            if ($(this).hasClass('form_error')) return true;
            $(this).addClass('form_error');
            $(this).closest('.mbformcontainer').find('.form_errortxt').html(txt);
            return true;
        })
        return this;
    }

    // Error remover
    $.fn.removeError = function () {
        this.find('.form_error').each(function() {
            $(this).removeClass('form_error');
            $(this).closest('.mbformcontainer').find('.form_errortxt').html('');
        })
        return this;
    }

    // Form clear
    $.fn.clearForm = function() {
        this.each(function() {
            $(this).removeError();
            $(this).find('input[type="text"]').val('');
            $(this).find('textarea').val('');
            $(this).find('select option:first-child').attr('selected', true);
        })
    }

    // Validation
    $('form.mbform').submit(function(e) {
        // Discard validation from all hidden fields
        var str = new String();
        $(this).find('.form_field:hidden').not('input[type=hidden]').each(function() {
            if (str != '') str = str + ' ';
            str = str + $(this).attr('id');
        })
        $(this).find('INPUT[name=form_field_discard]').val(str);

        // Trim all textual fields
        $(this).find('INPUT[type=text],TEXTAREA').each(function() {
            $(this).val($(this).val().replace(/^\s*/, '').replace(/\s*$/, ''));
        })

        $(this).removeError();
        var result = true;
        // Check for empty required fields
        $(this).find('INPUT.form_validate_required:visible,TEXTAREA.form_validate_required:visible').each(function() {
            if ($(this).attr('type') == 'checkbox') {
                if (! $(this).attr('checked')) {
                    $(this).triggerError('Feltet skal markeres');
                }
            } else if ($(this).val() == '') {
                if ($(this).attr('type') == 'file') $(this).triggerError('Du skal vælge en fil');
                else $(this).triggerError('Dette felt skal udfyldes');
                result = false;
            }
        })
        $(this).find('SELECT.form_validate_required:visible').each(function() {
            if ($(this).children('option:selected').val() == '') {
                $(this).triggerError('Du skal vælge en mulighed');
                result = false;
            }
        })
        $(this).find('.form_validate_elementcontainer.form_validate_required:visible').each(function() {
            if ($(this).find('input[type=checkbox]:checked').size() == 0 && $(this).find('input[type=checkbox]').size() > 0) {
                $(this).triggerError('Du skal markere mindst en');
                result = false;
            }
            if ($(this).find('input[type="text"]').filter('[value=""]').size() == $(this).find('input[type="text"]').size() && $(this).find('input[type="text"]').size() > 0) {
                $(this).triggerError('Dette felt skal udfyldes');
                result = false;
            }
        })

        // Check for minimum lengths (string)
        $(this).find('INPUT.form_validate_min:visible,TEXTAREA.form_validate_min:visible').not('.form_validate_number').each(function() {
            var str = $(this).val();
            var minput = $(this).getcv('form_validate_mininput');
            if (str != '' && str.length < parseInt(minput)) {
                $(this).triggerError('Mindst '+minput+' tegn');
                result = false;
            }
        })
        // Check for maximum lengths (string)
        $(this).find('INPUT.form_validate_max:visible,TEXTAREA.form_validate_max:visible').not('.form_validate_number').each(function() {
            var str = $(this).val();
            var minput = $(this).getcv('form_validate_maxinput');
            if (str != '' && str.length > parseInt(minput)) {
                $(this).triggerError('Højst '+minput+' tegn');
                result = false;
            }
        })

        // Check for minimum lengths (numbers)
        $(this).find('INPUT.form_validate_min:visible').filter('.form_validate_number').each(function() {
            var str = $(this).val();
            var minput = $(this).getcv('form_validate_mininput');
            if (str != '' && parseInt(str) < parseInt(minput)) {
                $(this).triggerError('Skal mindst være '+minput);
                result = false;
            }
        })
        // Check for maximum lengths (numbers)
        $(this).find('INPUT.form_validate_max:visible').filter('.form_validate_number').each(function() {
            var str = $(this).val();
            var minput = $(this).getcv('form_validate_maxinput');
            if (str != '' && parseInt(str) > parseInt(minput)) {
                $(this).triggerError('Må højst være '+minput);
                result = false;
            }
        })

        // Check for valid emails
        $(this).find('INPUT.form_validate_email:visible').each(function() {
            var str = $(this).val();
            if (str != '' && ! str.match(/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i)) {
                $(this).triggerError('Ugyldig email');
                result = false;
            }
            return true;
        })
        // Check for valid times
        $(this).find('INPUT.form_validate_time:visible').each(function() {
            var str = $(this).val();
            // Try to match different short timeforms
            if (str == '' ||
                str.match(/^\d{2}[:.]\d{2}([:.]\d{2})?$/i) ||
                str.match(/^((2[0-3])|([0-1]?[0-9]))[0-5][0-9]$/i) ||
                str.match(/^[0-9][:.][0-5][0-9]$/i) ||
                str.match(/^((2[0-3])|([0-1]?[0-9]))$/i) ||
                str.match(/^[0-9]$/i)) return true;
            $(this).triggerError('Ugyldig tidspunkt');
            result = false;
            return true;
        })
        // Check for valid duration
        $(this).find('INPUT.form_validate_duration:visible').each(function() {
            var str = $(this).val();
            // Try to match different short timeforms
            if (str == '' ||
                str.match(/^\d*[:.][0-5][0-9]$/i) ||
                str.match(/^\d+$/i)) return true;
            $(this).triggerError('Ugyldig varighed');
            result = false;
            return true;
        })
        // Check for valid numbers
        $(this).find('INPUT.form_validate_number:visible').each(function() {
            var str = $(this).val();
            if (str == '' ||
                str.match(/^[0-9.]+$/)) return true;
            $(this).triggerError('Ugyldigt tal');
            result = false;
            return true;
        })
        // Check for valid ranges
        $(this).find('SPAN.rangecontainer').each(function() {
            if ($(this).find('INPUT').filter('[value=""]').size() > 0) return true;
            var val1 = parseInt($(this).find('INPUT:eq(0)').val());
            var val2 = parseInt($(this).find('INPUT:eq(1)').val());
            if (val1 <= val2) return true;
            $(this).find('INPUT:eq(0)').triggerError('Ugyldig rækkefølge');
            result = false;
            return true;
        })
        // Check for valid amount
        $(this).find('INPUT.form_validate_amount:visible').each(function() {
            var str = $(this).val();
            if (str == '' ||
                str.match(/^([0-9.]+?)([.,](\d{1,2}))?$/)) return true;
            $(this).triggerError('Ugyldigt beløb');
            result = false;
            return true;
        })
        // Check for valid dates
        $(this).find('INPUT.form_validate_date:visible').each(function() {
            var str = $(this).val();
            // Try to match different short dateforms
            if (str == '' ||
                str.match(/^(\d{1,2})[-.:\/](\d{1,2})/i) ||
                str.match(/^(\d{1,2})[-.:\/](\d{1,2})[-.:\/](\d{2,4})/i)) return true;
            $(this).triggerError('Ugyldig dato');
            result = false;
            return true;
        })

        // Check if we need to save on submit
        if (result && $(this).hasClass('saveonsubmit')) {
           // Save form in cookie, for later use
            $.cookie('savedform_'+$(this).attr('id'),$(this).serialize());
        }
        if (! result) e.stopImmediatePropagation();
        return result;
    })

    var sourcefield = null;
    // Buyer adder
    $('#ebuyeradddialog').stddialog({
        "Opret" : function() {
            $('#ebuyeraddform').submit();
        }
    })
    $('#ebuyeraddform').submit(function() {
        // Additional verify
        if ($(this).find('#mobile').val() == '' && $(this).find('#phone').val() == '') {
            $(this).find('#mobile').triggerError('Udfyld mindst et telefonnummer');
            return false;
        }
        $.post('/obj/Ebuyer/php/quicksave.php', {buyername: $(this).find('#buyername').val(), phone: $(this).find('#phone').val(), mobile: $(this).find('#mobile').val(), email: $(this).find('#email').val()}, function (data) {
            sourcefield.val(data);
            $('#ebuyeradddialog').dialog('close');
        })
        return false;
    })
    $('.addbuyer').click(function() {
        sourcefield = $(this).closest('.mbformcontainer').find('input').last();
        $('#ebuyeraddform #buyername').val(sourcefield.val());
        $('#ebuyeradddialog').dialog('open');
    }).css('cursor', 'pointer');

}

function form_repeat_change() {
    var basename = $(this).attr('name');
    $('#'+basename+'_week_container').hide();
    $('#'+basename+'_month_container').hide();
    $('#'+basename+'_months_container').hide();
    $('#'+basename+'_yearly_container').hide();
    switch ($(this).children('option:selected').val()) {
        case '2':
        case '3':
        case '4':
            $('#'+basename+'_week_container').show();
        break;
        case '5':
        case '6':
        case '7':
            $('#'+basename+'_month_container').show();
        break;
        case '8':
            $('#'+basename+'_yearly_container').show();
        break;
        case '9':
            $('#'+basename+'_month_container').show();
            $('#'+basename+'_months_container').show();
        break;
    }
}

function form_add_option(str, opt) {
    if (str.indexOf('?') == -1) return str+'?'+opt;
    else return str+'&'+opt;
}
