define([
	"dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
	"dojo/parser", 
	"dojo/ready", 
    "dojo/dom",
	"dojo/_base/xhr",
	"dojo/dom-construct",
	"dojo/_base/array",
	"dojo/on",
	"chy/widget/LayouteditorCell",
	"dojo/text!./templates/LayouteditorRow.html"	
], function(declare, _WidgetBase, _TemplatedMixin, parser, ready, dom, xhr, domConstruct, array, on, LayouteditorCell, template) {
	return declare("widget.LayouteditorRow",[_WidgetBase, _TemplatedMixin], {
		//properties
		templateString: template,
		layoutConfigNode: null,
		cells: new Array(),
		contextInfo: null,
		
		//constructor
		constructor: function(args){
	        declare.safeMixin(this,args);			
		},
		
		postCreate:function(){
			this.inherited(arguments);
			array.forEach(this.layoutConfigNode.childNodes,function(layoutConfigNode){
				if(layoutConfigNode.localName == 'field'){
					var cellIndex = this.cells.length;
					this.cells[cellIndex] = new LayouteditorCell({layoutConfigNode: layoutConfigNode, contextInfo: this.contextInfo});
					domConstruct.place(this.cells[cellIndex].domNode,this.domNode,"last");
					parser.parse();
				}
			},this);
			
			this.addCellButton.thisRow = this;
			on(this.addCellButton, "click", function(e){
				var cellLayoutConfigNode = this.thisRow.layoutConfigNode.ownerDocument.createElementNS("http://www.innovationinvestments.nl/layout","xl:field");
				cellLayoutConfigNode.setAttribute('id','-1');
				cellLayoutConfigNode.setAttribute('rowspan','1');
				cellLayoutConfigNode.setAttribute('colspan','1');
				cellLayoutConfigNode.setAttribute('styleCSS','');
				this.thisRow.layoutConfigNode.appendChild(cellLayoutConfigNode);
				var cellIndex = this.thisRow.cells.length;
				this.thisRow.cells[cellIndex] = new LayouteditorCell({layoutConfigNode: cellLayoutConfigNode, contextInfo: this.thisRow.contextInfo});
				domConstruct.place(this.thisRow.cells[cellIndex].domNode,this.thisRow.domNode,"last");
				parser.parse();
			});
			
			this.removeRowButton.thisRow = this;
			on(this.removeRowButton, "click", function(e){
				var isEmpty = true;
				array.forEach(this.thisRow.layoutConfigNode.childNodes,function(layoutConfigNode){
					if(layoutConfigNode.localName == 'field'){
						isEmpty = false;
					}
				},this);				
				if(!isEmpty){
					alert("Row is not emptey.");
					return;
				}
				this.thisRow.destroy();
			});
			
			parser.parse();
		},
		
		onStart: function(){
			this.inherited(arguments);
			
			parser.parse();
		},
		
		destroy:function(){
			this.inherited(arguments);
			this.layoutConfigNode.parentNode.removeChild(this.layoutConfigNode);
		}
	});
});	
