﻿Ext.override(Ext.form.Label, {
    getText: function () {
        return this.text || Ext.util.Format.htmlDecode(this.html);
    },
	getValue: function() {
		return this.text || Ext.util.Format.htmlDecode(this.html);
	},
	setValue: function(text) {
		this.setText(text);
	}
});

var JsonTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
    requestData: function (node, callback) {
        if (this.fireEvent("beforeload", this, node, callback) !== false) {
            this.transId = Ext.Ajax.request({
                method: this.requestMethod,
                url: this.dataUrl || this.url,
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: { callback: callback, node: node },
                //params      : this.getParams(node)
                jsonData: this.jsonData || { "node": node.id }, //not used
                headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' }
            });
        } else {
            // if the load is cancelled, make sure we notify
            // the node that we are done
            if (typeof callback == "function") {
                callback();
            }
        }
    },
    processResponse: function (response, node, callback) {
        var json = response.responseText;
        try {
            var o = Ext.decode(json);
            o = o.d ? o.d : o;
            node.beginUpdate();
            for (var i = 0, len = o.length; i < len; i++) {
                //remove the __type attribute from the json object o
                delete o[i].__type; // dont need this as treeNode just ignores this attribute
                var n = this.createNode(o[i]);
                n.allowDrop = true;
                if (n) {
                    node.appendChild(n);
                }
            }
            node.endUpdate();
            if (typeof callback == "function") {
                callback(this, node);
            }
        } catch (e) {
            this.handleFailure(response);
        }
    }

});

var JsonTreeLoader2 = Ext.extend(Ext.tree.TreeLoader, {
    requestData: function (node, callback) {
        if (this.fireEvent("beforeload", this, node, callback) !== false) {
            this.transId = Ext.Ajax.request({
                method: this.requestMethod,
                url: this.dataUrl || this.url,
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
                argument: { callback: callback, node: node },
                //params      : this.getParams(node)
                jsonData: this.jsonData || { "node": node.id }, //not used
                headers: this.header || { 'Content-Type': 'application/json;charset=utf-8' }
            });
        } else {
            // if the load is cancelled, make sure we notify
            // the node that we are done
            if (typeof callback == "function") {
                callback();
            }
        }
    },
    processResponse: function (response, node, callback) {
        var json = response.responseText;
        try {
            var o = Ext.decode(json);
            o = o.d ? o.d : o;
            node.beginUpdate();
            for (var i = 0, len = o.length; i < len; i++) {
                //remove the __type attribute from the json object o
                delete o[i].__type; // dont need this as treeNode just ignores this attribute
                var n = this.createNode(o[i]);
                n.allowDrop = true;
                if (n) {
                    node.appendChild(n);
                }
            }
            node.endUpdate();
            if (typeof callback == "function") {
                callback(this, node);
            }
        } catch (e) {
            this.handleFailure(response);
        }
    }

});

/*
Ext.override(Ext.tree.TreeNode, {
    appendChild: function (n) {
        var node, exists;
        if (!n.render && !Ext.isArray(n)) {
            n = this.getLoader().createNode(n);
        } else {
            exists = !n.parentNode;
        }
        node = Ext.tree.TreeNode.superclass.appendChild.call(this, n);
        if (node) {
            this.afterAdd(node, exists);
        }
        this.ui.updateExpandIcon();
        return node;
    },
    insertBefore: function (node, refNode) {
        var newNode, exists;
        if (!node.render) {
            node = this.getLoader().createNode(node);
        } else {
            exists = !node.parentNode;
        }
        newNode = Ext.tree.TreeNode.superclass.insertBefore.call(this, node, refNode);
        if (newNode && refNode) {
            this.afterAdd(newNode, exists);
        }
        this.ui.updateExpandIcon();
        return newNode;
    },
    afterAdd: function (node, exists) {
        if (this.childrenRendered) {
            node.render(exists);
        } else if (exists) {
            node.renderIndent(true, true);
        }
    }
});
*/
Ext.apply(Ext.form.VTypes, {
   password: function(value, field)
   {
      if (field.initialPasswordField)
      {
         var pwd = Ext.getCmp(field.initialPasswordField);
         this.passwordText = 'De to indtastede adgangskoder er ikke ens.';
         return (value == pwd.getValue());
      }
 
      this.passwordText = 'Adgangskoden skal være på mindst 8 tegn og skal indeholde mindst ét tal.';
       
      var hasLength = (value.length >= 8);

      var hasNumeric = (value.replace(/[^\d]/g, '')).length > 0;
 
      return (hasNumeric && hasLength);
   },
 
   passwordText: 'Adgangskoden skal være på mindst 8 tegn og skal indeholde mindst ét tal.'

});


/**
* @class Ext.LinkButton
* @extends Ext.Button
* A Button which encapsulates an &lt;a> element to enable navigation, or downloading of files.
* @constructor
* Creates a new LinkButton
*/

Ext.LinkButton = Ext.extend(Ext.Button, {
    template: new Ext.Template(
        '<table id="{4}" cellspacing="0" class="x-btn {3}"><tbody class="{1}">',
            '<tr><td class="x-btn-tl"><i> </i></td><td class="x-btn-tc"></td><td class="x-btn-tr"><i> </i></td></tr>',
            '<tr>',
                '<td class="x-btn-ml"><i> </i></td>',
                '<td class="x-btn-mc">',
                    '<em class="{2}" unselectable="on">',
                        '<a href="{5}" style="display:block" target="{6}" class="x-btn-text">{0}</a>',
                    '</em>',
                '</td>',
                '<td class="x-btn-mr"><i> </i></td>',
            '</tr>',
            '<tr><td class="x-btn-bl"><i> </i></td><td class="x-btn-bc"></td><td class="x-btn-br"><i> </i></td></tr>',
        '</tbody></table>'
    ).compile(),

    buttonSelector: 'a:first',

    /** 
    * @cfg String href
    * The URL to create a link for.
    */
    /** 
    * @cfg String target
    * The target for the &lt;a> element.
    */
    /** 
    * @cfg Object
    * A set of parameters which are always passed to the URL specified in the href
    */
    baseParams: {},

    //  private
    params: {},

    getTemplateArgs: function () {
        return Ext.Button.prototype.getTemplateArgs.apply(this).concat([this.getHref(), this.target]);
    },

    onClick: function (e) {
        if (e.button != 0) {
            return;
        }
        if (this.disabled) {
            e.stopEvent();
        } else {
            if (this.fireEvent("click", this, e) !== false) {
                if (this.handler) {
                    this.handler.call(this.scope || this, this, e);
                }
            }
        }
    },

    // private
    getHref: function () {
        var result = this.href;
        var p = Ext.urlEncode(Ext.apply(Ext.apply({}, this.baseParams), this.params));
        if (p.length) {
            result += ((this.href.indexOf('?') == -1) ? '?' : '&') + p;
        }
        return result;
    },

    /**
    * Sets the href of the link dynamically according to the params passed, and any {@link #baseParams} configured.
    * @param {Object} Parameters to use in the href URL.
    */
    setParams: function (p) {
        this.params = p;
        this.el.child(this.buttonSelector, true).href = this.getHref();
    }
});

Ext.reg('linkbutton', Ext.LinkButton);

/// Patch der retter et problem med at radiobuttons ikke bliver skiftet hvis man kalder setValue på dem.
Ext.override(Ext.form.Radio, {
    setValue: function (v) {
        if (typeof v == 'boolean') {
            Ext.form.Radio.superclass.setValue.call(this, v);
        } else if (this.rendered) {
            var els = this.getCheckEl().select('input[name=' + this.el.dom.name + ']');
            els.each(function (el) {
                if (el.dom.value == v) {
                    Ext.getCmp(el.dom.id).setValue(true);
                } else {
                    Ext.getCmp(el.dom.id).setValue(false);
                }
            }, this);
        }
        return this;
    }
});

// Plugin is configured with a listeners config object.
// The Component is appended to the argument list of all handler functions.
Ext.DomObserver = Ext.extend(Object, {
    constructor: function(config) {
        this.listeners = config.listeners ? config.listeners : config;
    },

    init: function(c) {
        var p, l = this.listeners;
        for (p in l) {
            if (Ext.isFunction(l[p])) {
                l[p] = this.createHandler(l[p], c);
            } else {
                l[p].fn = this.createHandler(l[p].fn, c);
            }
        }
        c.render = c.render.createSequence(function() {
            c.el.on(l);
        });
    },

    createHandler: function(fn, c) {
        return function(e) {
            fn.call(this, e, c);
        };
    }
});
