/*
 * Author: Mirko Witzmann
 * Date: 2010-02-02
 * Dependencies: jquery-1.4.1.min.js, lib.js (jamp class)
 * Package: form class
 */

/*
 * form Object
 * 
 *  name: name of form
 *  file: Object
 *      ajax: ajax file
 *      mode: mode parameter [use seperator "," for more modes]
 *  func: function which will be executed after firing the ajax request
 *
 *      method require: Object
 *          name: name of element
 *          type: type of element
 *          text: error message
 *
 *          if type == int
 *          charprecision: [lower|equal|greater]
 *          charlength: number of chars to check
 *
 */
function form(name,file,func) {

    var t = this;

    this.form = 'form[name='+name+']';
    this.require = new Object();
    this.compare = new Object();
    this.calculate = new Object();
    this.buttonName = '';
    this.error = 0;
    this.errorArray = new Array();

    this.chars = [{
        1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E', 6: 'F', 7: 'G', 8: 'H', 9: 'I'
    }];

    /*
     * settings for the overlay layer and error message box
     */
    this.errorSettings = {
        containerId: 'popupformcontainer',
        opacity: 0.8,
        background: '#191919',
        zIndex: 1200
    };

    /*
     * checks if object is a filled object
     */
    this.isObject = function(o) {
        for(i in o) {
            return true;
        }
        return false;
    };

    /*
     * includes an object with methods for the required fields,
     * with an error message and the field type
     */
    this.require = function(require) {
        this.require = require;
    }

    /*
     * includes the response code after settling out an ajax request
     */
    this.response = function(response) {
        if(response!='') {
            this.response = response;
        }
    }

    /*
     * includes an object with method which compares two or more fields with
     * eachother
     */
    this.compare = function(compare) {
        if(compare!='') {
            this.compare = compare;
        }
    };

    /*
     * calculates
     */
    this.calculate = function(calculate) {
        if(calculate!='') {
            this.calculate = calculate;
        }
    };

    /*
     * sets an onclick-event on a specific button
     */
    this.button = function(name) {
        if($(this.form+' input[name='+name+']').length>0) {
            this.buttonName = name;

            $(this.form+' input[name='+name+']').click(function(e) {
                t.send(e);
            });
        } else {
            alert('Button doesn\'t exists. Form won\'t work');
        }
    };

    /*
     * checks if the typed string already exists (usefull to check existing emails in database)
     * if false (return string contains the error message), the send button will be disabled to avoid duplicated entries and an error
     * message will appear on the right of the element
     * if true (return string is 'done'), the form will be fired
     */
    this.exists = function(data) {

        /*
         * data object
         *  mode: mode parameters
         *  checkFile: ajax file
         *  element: name of element
         */

        var field = this.form+' input[name='+data.element+']';
        var buttonfield = this.form+' input[name='+this.buttonName+']';

        this.errorArray.length = 0;

        if($(field).length>0) {
            $(field).keyup(function() {
                if(jamp.isValidEmail(field)) {
                    $.ajax({
                        url: jamp.settings.ajaxPath+data.checkFile,
                        data: data.mode+'&'+data.element+'='+$(field).val(),
                        type: 'post',
                        success: function(html) {
                            if(html!='done') {
                                $(buttonfield).attr('disabled','disabled');
                                $(field).css({ 'border': '1px '+jamp.settings.errorColor+' solid' });

                                // Fehlermeldung(en) ausgeben
                                var outputhtml = '';
                                var box = '';
                                
                                if($('#'+name+data.element+t.errorSettings.containerId).length<=0) {
                                    outputhtml = '<ul>'
                                        outputhtml += '<li>'+html+'</li>';
                                    outputhtml += '</ul>';

                                    box = '<div id="'+name+data.element+t.errorSettings.containerId+'" class="'+t.errorSettings.containerId+'">';
                                        box += '<div class="popupform">';
                                            box += '<div class="list2"></div>';
                                        box += '</div>';
                                    box += '</div>';

                                    $(field).after(box);
                                    $('#'+name+data.element+t.errorSettings.containerId+' .popupform .list2').append(outputhtml);

                                    $('#'+name+data.element+t.errorSettings.containerId).css({
                                        top: $(field).position().top,
                                        left: $(field).position().left+$(field).width()+20
                                    }).fadeIn('slow');
                                }

                            } else {
                                $(buttonfield).removeAttr('disabled');
                                $(field).css({ 'border': '1px '+jamp.settings.successColor+' solid' });
                                $('#'+name+data.element+t.errorSettings.containerId).fadeOut('slow',function() { $(this).remove(); });
                            }
                        }
                    });
                }
            });
        }
    };

    /*
     * empties form element/selects the first item after sending the form
     */
    this.emptyForm = function() {
        $(this.form+' input,'+this.form+' textarea').each(function() {
            if($(this).attr('type')!='checkbox' && $(this).attr('type')!='radio' && $(this).attr('type')!='button') {
                $(this).val('');
            } else {
                if($(this).attr('type')=='checkbox') {
                    $(this).removeAttr('checked')
                } else if($(this).attr('type')=='radio') {
                    $(this).removeAttr('selected');
                }
            }
            if($(this).attr('type')!='button') {
                $(this).css({ border: '1px '+jamp.settings.defaultColor+' solid' });
            }
        });
        
        $(this.form+' select option:first').attr('selected','selected');
        $(this.form+' select').css({ border: '1px '+jamp.settings.defaultColor+' solid' });
    };

    /*
     * creates a box with the error messages
     */
    this.errorMessage = function() {
        var html = '';
        var box = '';

        if($('#'+name+t.errorSettings.containerId).length<=0) {

            html = '<ul>'
            if(t.errorArray.length>0) {
                for(i in t.errorArray) {
                    html += '<li>'+t.errorArray[i]+'</li>';
                }
            }
            html += '</ul>';

            box = '<div id="pageOverlay"></div>';
            box += '<div id="'+name+t.errorSettings.containerId+'" class="'+t.errorSettings.containerId+'">';
                box += '<div class="popupform">';
                    box += '<div class="list2"></div>';
                    box += '<div align="right"><a onfocus="this.blur();" href="javascript: void(0);" onclick="$(\'#'+name+t.errorSettings.containerId+'\').fadeOut(\'slow\',function() { $(this).remove(); $(\'#pageOverlay\').remove(); });" title="ok"><img src="img/buttonok.gif" alt="ok" title="ok"></a></div>';
                box += '</div>';
            box += '</div>';

            $('body').append(box);
            $('#pageOverlay').css({
                position: 'absolute',
                top: 0,
                left: 0,
                width: $(document).width()-24+'px',
                height: $(document).height()+'px',
                opacity: t.errorSettings.opacity,
                background: t.errorSettings.background,
                zIndex: t.errorSettings.zIndex
            });

            $('#'+name+t.errorSettings.containerId+' .popupform .list2').append(html);

            $('#'+name+t.errorSettings.containerId).css({
                position: 'absolute',
                top: (($(window).height()/2)+($(window).scrollTop())-($('#'+name+t.errorSettings.containerId).height()/2)),
                left: ($(document).width()/2)-($('#'+name+t.errorSettings.containerId).width()/2),
                zIndex: t.errorSettings.zIndex+100
            }).fadeIn('slow');

            $(window).scroll(function() {
                $('#'+name+t.errorSettings.containerId).css({ top : (($(window).height()/2)+($(window).scrollTop())-($('#'+name+t.errorSettings.containerId).height()/2)) });
            });

        }
    };

    /*
     * sets checking method for each form element
     */
    this.formHandle = function(element) {
        if(element.length>0) {
            for(i in element) {
                var el = element[i];
                var tagName = $(this.form+' *[name='+el.name+']')[0].tagName;

                if($(this.form+' *[name='+el.name+']').attr('type')=='text') {
                    this.input(el);
                } else if($(this.form+' *[name='+el.name+']').attr('type')=='password') {
                    this.password(el);
                } else if($(this.form+' *[name='+el.name+']').attr('type')=='radio') {
                    this.radio(el);
                } else if($(this.form+' *[name='+el.name+']').attr('type')=='checkbox') {
                    this.checkbox(el);
                } else if($(this.form+' *[name='+el.name+']').attr('type')=='hidden') {
                    this.hidden(el);
                } else if($(this.form+' *[name='+el.name+']').attr('type')=='file') {
                    this.file(el);
                } else {
                    if(tagName=='TEXTAREA') {
                        this.textarea(el);
                    } else if(tagName=='SELECT') {
                        this.select(el);
                    }
                }
            }
        }
    };

    /*
     * checks if an error occurs. If not, an ajax request is gonna triggered,
     * otherwise error messages will appear
     */
    this.send = function() {
        t.error = 0;
        t.errorArray.length = 0;

        if(this.require.length>0) {
            var element = this.require;
            if($.isArray(element)) {
                this.formHandle(element);
            }
        }

        if(this.compare.length>0) {
            var compare = this.compare;
            if($.isArray(compare)) {
                this.compareField(compare[0],compare[1]);
            }
        }

        if(this.isObject(this.calculate)) {
            var calculate = this.calculate;
            this.calculateField(calculate);
        }

        if(t.error==0) {
            var data = this.data();
            var properties = '';


            if(file.mode!=undefined) {
                var tmpMode = file.mode.split(',');
                for(i in tmpMode) {
                    properties += tmpMode[i]+'&';
                }
            }

            if(this.isObject(file)) { // per Ajax absenden
                $.ajax({
                    url: jamp.settings.ajaxPath+file.ajax,
                    data: properties+data,
                    type: 'post',
                    success: function(html) {
                        t.emptyForm();
                        if(func!='') {
                            func(html);
                        }
                    }
                });
            } else {
                // Normal per Post absenden
                $(this.form).submit();
            }
        } else {
            // Fehlermeldung(en) ausgeben
            t.errorMessage();
        }

    };

    /*
     * builds the data string for the ajax request
     */
    this.data = function() {
        var data = '';

        if($(this.form).length>0) {
            $(this.form+' input, '+this.form+' select, '+this.form+' textarea').each(function() {
                if($(this).attr('name')!=t.buttonName) {
                    data += $(this).attr('name')+'='+$(this).val()+'&';
                }
            });

            return data;
        }

        return false;
    };

    /*
     * methods to handle errors/successes for each form element
     */
    this.input = function(element) {
        if($(this.form+' input[name='+element.name+']').val()!=undefined) {
            if(element.type=='text') {
                if($(this.form+' input[name='+element.name+']').val()=='') {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    t.error++;
                } else {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });
                }
            } else if(element.type=='int') {
                if($(this.form+' input[name='+element.name+']').val()=='' || isNaN($(this.form+' input[name='+element.name+']').val())) {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    t.error++;
                } else {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });
                }
            } else if(element.type=='email') {
                if($(this.form+' input[name='+element.name+']').val()=='' || !jamp.isValidEmail(this.form+' input[name='+element.name+']')) {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    t.error++;
                } else {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });
                }
            }

            var input = $(this.form+' input[name='+element.name+']').val();
            if( ( element.charprecision=='equal' && input.length!=element.charlength ) |
                ( element.charprecision=='lower' && input.length<element.charlength ) |
                ( element.charprecision=='greater' && input.length>element.charlength ) ) {

                $(this.form+' input[name='+element.name+']').css({
                    'border': '1px '+jamp.settings.errorColor+' solid'
                });

                if(jQuery.inArray(element.text,t.errorArray)==-1) {
                    t.errorArray.push(element.text);
                }

                t.error++;
            }
        }
    };

    this.password = function(element) {
        if($(this.form+' input[name='+element.name+']').val()!=undefined) {
            if(element.type=='text') {
                if($(this.form+' input[name='+element.name+']').val()=='') {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    t.error++;
                } else {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });
                }
            }
        }
    };

    this.textarea = function(element) {
        if($(this.form+' textarea[name='+element.name+']').val()!='undefined') {
            if($(this.form+' textarea[name='+element.name+']').val()=='') {
                $(this.form+' textarea[name='+element.name+']').css({
                    'border': '1px '+jamp.settings.errorColor+' solid'
                });

                if(jQuery.inArray(element.text,t.errorArray)==-1) {
                    t.errorArray.push(element.text);
                }

                t.error++;
            } else {
                $(this.form+' textarea[name='+element.name+']').css({
                    'border': '1px '+jamp.settings.successColor+' solid'
                });
            }
        }
    };

    this.select = function(element) {
        if($(this.form+' select[name='+element.name+']').val()==null || $(this.form+' select[name='+element.name+']').val()=='') {
            $(this.form+' select[name='+element.name+']').css({
                'border': '1px '+jamp.settings.errorColor+' solid'
            });

            if(jQuery.inArray(element.text,t.errorArray)==-1) {
                t.errorArray.push(element.text);
            }

            t.error++;
        } else {
            $(this.form+' select[name='+element.name+']').css({
                'border': '1px '+jamp.settings.successColor+' solid'
            });
        }
    };

    this.file = function(element) {
        if($(this.form+' input[name='+element.name+']').val()=='') {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.errorColor+' solid'
            });

            if(jQuery.inArray(element.text,t.errorArray)==-1) {
                t.errorArray.push(element.text);
            }

            t.error++;
        } else {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.successColor+' solid'
            });
        }
    };

    this.radio = function(element) {
        if($(this.form+' input[name='+element.name+']:checked').val()==undefined) {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.errorColor+' solid'
            });

            if(jQuery.inArray(element.text,t.errorArray)==-1) {
                t.errorArray.push(element.text);
            }

            t.error++;
        } else {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.successColor+' solid'
            });
        }
    };

    this.checkbox = function(element) {
        if($(this.form+' input[name='+element.name+']:checked').val()==null) {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.errorColor+' solid'
            });

            if(jQuery.inArray(element.text,t.errorArray)==-1) {
                t.errorArray.push(element.text);
            }

            t.error++;
        } else {
            $(this.form+' input[name='+element.name+']').css({
                'border': '1px '+jamp.settings.successColor+' solid'
            });
        }
    };

    this.compareField = function(element,element2) {
        if($(this.form+' *[name='+element.name+']').length>0 && $(this.form+' *[name='+element2.name+']').length>0) {
            if($(this.form+' *[name='+element.name+']').val()!='' && $(this.form+' *[name='+element2.name+']').val()!='') {
                if($(this.form+' *[name='+element.name+']').val()!=$(this.form+' *[name='+element2.name+']').val()) {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    $(this.form+' input[name='+element2.name+']').css({
                        'border': '1px '+jamp.settings.errorColor+' solid'
                    });

                    if(jQuery.inArray(element.text,t.errorArray)==-1) {
                        t.errorArray.push(element.text);
                    }

                    t.error++;
                } else {
                    $(this.form+' input[name='+element.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });

                    $(this.form+' input[name='+element2.name+']').css({
                        'border': '1px '+jamp.settings.successColor+' solid'
                    });
                }
            }
        }
    };

    this.char2num = function(item) {
        if(item!=undefined) {
            for(i in t.chars) {
                for(y in t.chars[i]) {
                    if(t.chars[i][y]==item) {
                        return y;
                    }
                }
            }

            return '';
        } else {
            return '';
        }
    };

    this.num2char = function(item) {
        if(item!=undefined) {
            for(i in t.chars) {
                for(y in t.chars[i]) {
                    if(y==item) {
                        return t.chars[i][y];
                    }
                }
            }

            return '';
        } else {
            return '';
        }
    };

    this.calculateField = function(calculate) {
        if(calculate.length>0) {
            for(i in calculate) {
                var calc = calculate[i];

                if($(this.form+' input[name='+calc.name+']').length>0) {
                    // $_SESSION Zeichen
                    
                    var ergebnis_calc = this.char2num(calc.calc1)+this.char2num(calc.calc2);
                    ergebnis_calc = ergebnis_calc.split('');

                    var ergebnis_calc_zahlen = String(parseInt(ergebnis_calc[0])+parseInt(ergebnis_calc[1]));
                    ergebnis_calc_zahlen = ergebnis_calc_zahlen.split('');

                    var ergebnis_calc_zeichen = this.num2char(ergebnis_calc_zahlen[0])+''+this.num2char(ergebnis_calc_zahlen[1]);

                    // Ergebnis aus Feld Zahlen
                    var ergebnis = $(this.form+' input[name='+calc.name+']').val().split('');
                    // Ergebnis Zeichen
                    var ergebnis_zeichen = this.num2char(ergebnis[0])+''+this.num2char(ergebnis[1]);


                    if(ergebnis_calc_zeichen==ergebnis_zeichen) {
                        $(this.form+' input[name='+calc.name+']').css({
                            'border': '1px '+jamp.settings.successColor+' solid'
                        });
                    } else {
                        $(this.form+' input[name='+calc.name+']').css({
                            'border': '1px '+jamp.settings.errorColor+' solid'
                        });

                        if(jQuery.inArray(calc.text,t.errorArray)==-1) {
                            t.errorArray.push(calc.text);
                        }

                        t.error++;
                    }
                }
            }
        }
    };

    this.hidden = function(element) {

    };

}