Ext.namespace('Ext.ux.form');

Ext.ux.form.FormPanel = Ext.extend(Ext.form.FormPanel, {
	
	initComponent  : function(){
        Ext.ux.form.FormPanel.superclass.initComponent.call(this);
    },
    
    onRender : function(ct, position) {
        Ext.ux.form.FormPanel.superclass.onRender.call(this, ct, position);
        
        this.form.reader = new Ext.data.JsonReader({
			root: 'results',
			id: 'id'
		},this.dataArray);
		
		this.handleRedirect = function(data) {
			if (this.redirectURL) {
				if (this.send_data_upon_redirect && data) {
					
					var decodedData = Ext.decode(data);
					
					var hidden = [];
					for (var i in decodedData.data) {
						var v = decodedData.data[i];
						if (Ext.isObject(v)) v = Ext.encode(v);
						
						hidden.push(new Ext.form.Hidden({name: i, value: v}));
					}
					
					var sendDataUponRedirect = new Ext.form.FormPanel({
						url: this.redirectURL,
						renderTo: Ext.getBody(),
						hidden: true,
						standardSubmit:true,
						items: hidden
					});
					sendDataUponRedirect.form.submit();
					
				} else {
					window.location = this.redirectURL;
				}
			}
		};
		
        this.submit = function() {
        	
        	if (this.form.isValid()) {
                
        		var _this = this;
        		var p = {'data[id]': this.data_id,'data[webform_id]': this._nodeId,'data[custom_id]': this.custom_id,'data[multipage_id]': this.multipage_id || '0','data[custom_data]': Ext.encode(this.custom_data)};
        		
        		this.form.submit({
        			waitMsg:'Processing',
        			params: p,
        			failure: function(form, action) {
        				var r = Ext.decode(action.response.responseText);
        				Ext.Msg.alert('Error',r.errorInfo);
        			},
        			success: function(form, action) {
        				var r = Ext.decode(action.response.responseText);
        				
						_this.data_id = r.id;
						
						_this.handleRedirect(r.submittedData);
						
        			}
        		});
        	}
        };
        if (this.el.hasClass('webform_viewResults')) {
	        this.on('afterrender', function() {
	        	this.cascade(function(c) {
	        		if ((c instanceof Ext.form.Radio) || (c instanceof Ext.form.Checkbox)) {
	        			c.setDisabled(true);
	        		} else if (c.setReadOnly) {
	        			c.setReadOnly(true);
	        		}
	        	});
	        });
        }
    },
    afterRender : function() {
    	Ext.ux.form.FormPanel.superclass.afterRender.call(this);
    	
    	if (this.data_id) {
			this.on('actioncomplete', function(form, action) {
				if (action.type=='load') {
					if (this.el.hasClass('webform_viewResults')) {
						var r = Ext.decode(action.response.responseText).results[0];
						this.cascade(function(c) {
							// upload fields
			        		if ((c instanceof Ext.form.TextField) && c.inputType=='file') {
			        			if (r[c.initialName]) {
			        				var div = document.createElement('div');
			        				div.style.padding = '3px 0 0 4px';
			        				var link = document.createElement('a');
			        				link.href = r[c.initialName];
			        				link['className'] = 'link';
			        				var text = r[c.initialName].split('/');
			        				link.innerHTML = text[text.length-1];
			        				div.appendChild(link);
			        				c.el.parent().appendChild(div);
			        			}
			        		}
			        		// textarea
			        		if ((c instanceof Ext.form.TextArea)) {
		        				var div = document.createElement('div');
		        				div.style.padding = '3px 0 0 4px';
		        				div.style.color = '#444';
		        				div.innerHTML = c.getValue();
		        				var p = c.el.parent();
		        				c.el.remove();
		        				p.appendChild(div);
			        		}
			        		// html editor
			        		if ((c instanceof Ext.form.HtmlEditor)) {
			        			var p = c.el.parent();
			        			var v = c.getValue();
			        			while (p.first()) p.first().remove();
			        			
		        				var div = document.createElement('div');
		        				div.style.padding = '3px 0 0 4px';
		        				div.style.display = 'block';
		        				div.style.color = '#444';
		        				div.innerHTML = v;
		        				p.appendChild(div);
			        		}
			        		// captcha
			        		if ((c instanceof Ext.ux.form.Captcha)) {
//								c.destroy();
								c.el.parent().parent().setStyle('display','none');
			        		}
			        	});
					}
				}
			},this);
			this.form.load({url: '/webforms/getFormResults/'+this.data_id,waitMsg: 'Loading...'});
		}
		if (!this.el.hasClass('webform_viewResults')) {
			this.cascade(function(c) {
        		// dual-fields
        		if (c.dualField) {
        			c.validator = function(v) {
        				var dual = this.find('initialName',c.dualField)[0];
        				if (dual && dual.getValue()==c.getValue()) {
        					return true;
        				}
        				return 'This value should be the same as the "'+c.dualField+'" field.';
        			}.createDelegate(this);
        		}
        	},this);
		}
    }
});
Ext.reg('webform', Ext.ux.form.FormPanel);

Ext.ux.form.SubmitButton = Ext.extend(Ext.Button, {
	
	initComponent  : function(){
        Ext.ux.form.SubmitButton.superclass.initComponent.call(this);
    },
    
    onRender : function(ct, position){
        Ext.ux.form.SubmitButton.superclass.onRender.call(this, ct, position);
        this.initSubmitButton();
    },
    
    initSubmitButton : function() {
    	this.handler = function() {
        	var f = this.findParentByType('webform');
        	if (f) {
        		f.submit();
        	}
        }
    }

});
Ext.reg('submitbutton', Ext.ux.form.SubmitButton);

Ext.ux.form.Captcha = Ext.extend(Ext.form.TextField, {
	
    onRender : function(ct, position){
        Ext.ux.form.Captcha.superclass.onRender.call(this, ct, position);
        var el = this.el.parent();
        
        var label = el.prev();
        var div = document.createElement('div');
		div.style.paddingBottom = '3px';
		div.innerHTML = label.dom.innerHTML;
		el.parent().insertFirst(div);
		label.remove();
		
		// get form
		var form = this.findParentByType('webform');
		
		var img = document.createElement('img');
		img.src = '/users/captcha/'+form._nodeId+'?_dc='+Math.random();
		img.border='0';
		img.style.verticalAlign = 'middle';
		img.style.marginRight = '5px';
		el.insertFirst(img);
		
		form.form.on('actionfailed', function(f, action) {
			if (action.type=='submit') {
				img.src = '/users/captcha/'+form._nodeId+'?_dc='+Math.random();
				this.setValue('');
			}
		},this);
    }
});
Ext.reg('captcha', Ext.ux.form.Captcha);


Ext.namespace("Ext.ux.layout");

Ext.ux.layout.TableFormLayout = Ext.extend(Ext.layout.TableLayout, {
    monitorResize: true,
    setContainer: function() {
        Ext.layout.FormLayout.prototype.setContainer.apply(this, arguments);
        this.currentRow = 0;
        this.currentColumn = 0;
        this.cells = [];
    },
    renderItem : function(c, position, target) {
        if (c && !c.rendered) {
            var cell = Ext.get(this.getNextCell(c));
            cell.addClass("x-table-layout-column-" + this.currentColumn);
            Ext.layout.FormLayout.prototype.renderItem.call(this, c, 0, cell);
        }
    },
    getAnchorViewSize : Ext.layout.AnchorLayout.prototype.getAnchorViewSize,
    getTemplateArgs : Ext.layout.FormLayout.prototype.getTemplateArgs,
    onLayout : function(ct, target) {
        Ext.ux.layout.TableFormLayout.superclass.onLayout.call(this, ct, target);
        if (!target.hasClass("x-table-form-layout-ct")) {
            target.addClass("x-table-form-layout-ct");
        }
        var viewSize = this.getAnchorViewSize(ct, target);
        var aw, ah;
        if (ct.anchorSize) {
            if (typeof ct.anchorSize == "number") {
                aw = ct.anchorSize;
            } else {
                aw = ct.anchorSize.width;
                ah = ct.anchorSize.height;
            }
        } else {
            aw = ct.initialConfig.width;
            ah = ct.initialConfig.height;
        }
        var cs = ct.items.items, len = cs.length, i, j, c, a, cw, ch;
        var x, w, h, col, colWidth, offset;
        for (i = 0; i < len; i++) {
            c = cs[i];
            // get table cell
            x = c.getEl().parent(".x-table-layout-cell");
            if (this.columnWidths) {
                // get column
                col = parseInt(x.dom.className.replace(/.*x\-table\-layout\-column\-([\d]+).*/, "$1"));
                // get cell width (based on column widths)
                colWidth = 0, offset = 0;
                for (j = col; j < (col + (c.colspan || 1)); j++) {
                    colWidth += this.columnWidths[j];
                    offset += 10;
                }
                w = (viewSize.width * colWidth) - offset;
            } else {
                // get cell width
                w = (viewSize.width / this.columns) * (c.colspan || 1);
            }
            // set table cell width
            x.setWidth(w);
            // get cell width (-10 for spacing between cells) & height to be base width of anchored component
            w = w - 10;
            h = x.getHeight();
            // perform anchoring
            if (c.anchor) {
                a = c.anchorSpec;
                if (!a) {
                    var vs = c.anchor.split(" ");
                    c.anchorSpec = a = {
                        right: this.parseAnchor(vs[0], c.initialConfig.width, aw),
                        bottom: this.parseAnchor(vs[1], c.initialConfig.height, ah)
                    };
                }
                cw = a.right ? this.adjustWidthAnchor(a.right(w), c) : undefined;
                ch = a.bottom ? this.adjustHeightAnchor(a.bottom(h), c) : undefined;
                if (cw || ch) {
                    c.setSize(cw || undefined, ch || undefined);
                }
            }
        }
    },
    parseAnchor : function(a, start, cstart) {
        if (a && a != "none") {
            var last;
            if (/^(r|right|b|bottom)$/i.test(a)) {
                var diff = cstart - start;
                return function(v) {
                    if (v !== last) {
                        last = v;
                        return v - diff;
                    }
                };
            } else if (a.indexOf("%") != -1) {
                var ratio = parseFloat(a.replace("%", "")) * .01;
                return function(v) {
                    if (v !== last) {
                        last = v;
                        return Math.floor(v * ratio);
                    }
                };
            } else {
                a = parseInt(a, 10);
                if (!isNaN(a)) {
                    return function(v) {
                        if (v !== last) {
                            last = v;
                            return v + a;
                        }
                    };
                }
            }
        }
        return false;
    },
    adjustWidthAnchor : function(value, comp) {
        return value - (comp.isFormField ? (comp.hideLabel ? 0 : this.labelAdjust) : 0);
    },
    adjustHeightAnchor : function(value, comp) {
        return value;
    },
    getLabelStyle : Ext.layout.FormLayout.prototype.getLabelStyle
});

Ext.Container.LAYOUTS["tableform"] = Ext.ux.layout.TableFormLayout;