$.widget("ui.dsForm", {
    options: {
        title: 'test',
        path: 'ejs/common/dsForm',
        autolabelwidth: true,
        form: {
            id: "id",
            action: "",
            name: "name"
                
        },
        data: [{
            type: 'textbox',
            name: 'test',
            label: 'label',
            value: 'x',
            required: false
        }],
        beforeFormBuild: undefined ,
        afterFormBuild: undefined,
        beforeValidate: undefined,
        extendValidate: function() {return true;},
        afterValidate: undefined,
        errorValidate: function(msg) {alert(msg);},
        beforeSubmit: undefined,
        afterSubmit: function(data, status) {alert(status);}
        
        
    }, 
    
    _init : function()
    {
        var object = this;
        var formdiv = object.element;
        
        // Initialize default functions
        if (typeof(this.options.beforeFormBuild) == "undefined") this.options.beforeFormBuild = this.beforeFormBuild; 
        if (typeof(this.options.afterFormBuild) == "undefined") this.options.afterFormBuild = this.afterFormBuild; 
        if (typeof(this.options.beforeValidate) == "undefined") this.options.beforeValidate = this.beforeValidate; 
        if (typeof(this.options.afterValidate) == "undefined") this.options.afterValidate = this.afterValidate; 
        
        // Handle form
        this.options.beforeFormBuild.call(object, formdiv);
        object.doFormBuild(object, formdiv);
        var form = $('form', formdiv); // we now have an form
        this.options.afterFormBuild.call(object, formdiv, form);
        
        // Attach ajaxSubmit to form
        var data = { beforeValidate: this.options.beforeValidate,
                     doValidate: object.doValidate,
                     extendValidate: this.options.extendValidate,
                     afterValidate: this.options.afterValidate,
                     errorValidate: this.options.errorValidate,
                     beforeSubmit: this.options.beforeSubmit,
                     afterSubmit: this.options.afterSubmit
                   };
        $('#' + this.options.form.id).bind("submit", data, function(event) { 
            var options = event.data;
            // Do the validation stuff before the submit
            try {
                var isValid = options.beforeValidate.call(this) && options.doValidate.call(this,this, options.errorValidate) && options.extendValidate.call(this,this);
                // if (typeof(this.options.extendValidate) == "undefined"){
                options.afterValidate.call(this, isValid);
                if (isValid) {
                    var opt = {
                            beforeSubmit: options.beforeSubmit,
                            success: options.afterSubmit,
                            type: 'post',
                            dataType:  'json',
                            timeout:   3000 
                    };
                    $(this).ajaxSubmit(opt); 
                }             
            } catch (e) {
                // TODO: handle exception
                alert(e.message);
                return false;
            }
            // return false to prevent normal browser submit and page navigation 
            return false; 
        });
        
    },
    textelements : function(element)
    {

        $(element).bind({

            focusin : function()
            {
                $(this).toggleClass('ui-state-focus');
            },
            focusout : function()
            {
                $(this).toggleClass('ui-state-focus');
            }
        });

    },
    buttons : function(element)
    {
        if ($(element).is(":submit")) {
            $(element).addClass("ui-priority-primary ui-corner-all hover");
            $(element).bind("click", function(event)
            {
                //event.preventDefault();
            });
        } else if ($(element).is(":reset")) $(element).addClass("ui-priority-secondary ui-corner-all hover");
        $(element).bind('mousedown mouseup', function()
        {
            $(this).toggleClass('ui-state-active');
        }

        );
    },
    checkboxes : function(element)
    {
        $(element).parent("label").after("<span />");
        var parent = $(element).parent("label").next();
        $(element).addClass("ui-helper-hidden");
        parent.css({
            width : 16,
            height : 16,
            display : "block"
        });
        parent.wrap("<span class='ui-state-default ui-corner-all' style='display:inline-block;width:16px;height:16px;margin-right:5px;'/>");
        parent.parent().addClass('hover');
        parent.parent("span").click(function(event)
        {
            $(this).toggleClass("ui-state-active");
            parent.toggleClass("ui-icon ui-icon-check");
            $(element).click();

        });

    },
    radio : function(element)
    {
        $(element).parent("label").after("<span />");
        var parent = $(element).parent("label").next();
        $(element).addClass("ui-helper-hidden");
        parent.addClass("ui-icon ui-icon-radio-off");
        parent.wrap("<span class='ui-state-default ui-corner-all' style='display:inline-block;width:16px;height:16px;margin-right:5px;'/>");
        parent.parent().addClass('hover');
        parent.parent("span").click(function(event)
        {
            $(this).toggleClass("ui-state-active");
            parent.toggleClass("ui-icon-radio-off ui-icon-bullet");
            $(element).click();
        });
    },
    selector : function(element)
    {
        var parent = $(element).parent();
        parent.css({
            "display" : "block",
            width : 140,
            height : 21
        }).addClass("ui-state-default ui-corner-all");
        $(element).addClass("ui-helper-hidden");
        parent.append("<span id='labeltext' style='float:left;'></span><span style='float:right;display:inline-block' class='ui-icon ui-icon-triangle-1-s' ></span>");
        parent.after("<ul class=' ui-helper-reset ui-widget-content ui-helper-hidden' style='position:absolute;z-index:50;width:140px;' ></ul>");
        $.each($(element).find("option"), function()
        {
            $(parent).next("ul").append("<li class='hover'>" + $(this).html() + "</li>");
        });
        $(parent).next("ul").find("li").click(function()
        {
            $("#labeltext").html($(this).html());
            $(element).val($(this).html());
        });
        $(parent).click(function(event)
        {
            $(this).next().slideToggle('fast');
            event.preventDefault();
        });

    },
    beforeFormBuild : function(formdiv) {
        var object = this;
    },
    doFormBuild : function (object, formdiv) {
        var object = this;
        var content = $.View(this.options.path + '/form.ejs', this.options);
        formdiv.append(content);
        
        var form = $('form', formdiv);
        var inputs = form.find("input , select ,textarea");
        
        $.each(inputs, function()
        {
            $(this).addClass('ui-state-default ui-corner-all');

            if ($(this).is(":reset ,:submit")) object.buttons(this);
            else if ($(this).is(":checkbox")) object.checkboxes(this);
            else if ($(this).is("input[type='text']") || $(this).is("textarea") || $(this).is("input[type='password']")) object.textelements(this);
            else if ($(this).is(":radio")) object.radio(this);
            else if ($(this).is("select")) object.selector(this);

            if ($(this).hasClass("date")) $(this).datepicker();
        });
        $(".hover").hover(function()
        {
            $(this).addClass("ui-state-hover");
        }, function()
        {
            $(this).removeClass("ui-state-hover");
        });
        
        if (this.options.autolabelwidth) {
            var labelwidth = 0;
            $('label', form).each(function(){
                var currentwidth = $(this).outerWidth();
                if (labelwidth < currentwidth) labelwidth = currentwidth;
            });
            $('label', form).css('display', 'block').css('float', 'left').css('width', (labelwidth + 15) + 'px');
        }
    },
    afterFormBuild : function(formdiv, form){
        var object = this;
    },
    beforeValidate : function(){
        var form = this;
        return true;
    },
    doValidate : function (object, errorValidate) {
        var errors = 0;
        var form = $(object);

        // remove all old validation errors
        $(".validateerror", form).each(function()
        {
            $(this).removeClass('validateerror');
            $(this).css("border", "");
        });

        // Check for the validation errors
        $(".required", form).each(function()
        {
            var obj = $('input', $(this));
            if (obj.val() == '') {
                obj.addClass('validateerror');
                obj.css("border", "1px solid red");
                errors++;
            }
        });

        if (errors) {
            // call validateError
            errorValidate.call(this, 'Niet alle verplichte velden zijn ingevuld!');
            return false;
        }

        // if no errors, it submits successfully
        return true;
    },
    afterValidate : function(isValid){
        var form = this;
    },
    beforeSubmit : function(element){}
});

