define([
	"dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
	"dojo/parser", 
	"dojo/ready", 
    "dojo/dom",
	"dojo/_base/xhr",
	"dojo/dom-construct",
	"dojo/_base/array",
	"dojo/dnd/Source",
	"dojo/on",
	"dojo/dom-style",
	"dijit/form/DropDownButton", 
	"dijit/TooltipDialog",
	"chy/widget/LayouteditorMovable",
	"dojo/text!./templates/LayouteditorCell.html"	
], function(declare, _WidgetBase, _TemplatedMixin, parser, ready, dom, xhr, domConstruct, array, Source, on, domStyle, DropDownButton, TooltipDialog, LayouteditorMovable, template) {
	return declare("widget.LayouteditorCell",[_WidgetBase, _TemplatedMixin], {
		//properties
		templateString: template,
		layoutConfigNode: null,
		rowspan: "1",
		colspan: "1",
		styleCSS: "",
		movable: null,
		contextInfo: null,
		htmlContent: "",
		nolabel: 'false',
		
		//constructor
		constructor: function(args){
	        declare.safeMixin(this,args);
			if(this.layoutConfigNode.attributes['nolabel']){
				this.nolabel = this.layoutConfigNode.attributes['nolabel'].nodeValue;
			}			
			if(this.layoutConfigNode.attributes['rowspan']){
				this.rowspan = this.layoutConfigNode.attributes['rowspan'].nodeValue;
			}
			if(this.layoutConfigNode.attributes['colspan']){
				this.colspan = this.layoutConfigNode.attributes['colspan'].nodeValue;
				if(this.nolabel == 'true'){
					this.colspan = parseInt(this.colspan) - 1;
				}
				if(parseInt(this.colspan) > 1){
					this.colspan = (parseInt(this.colspan) + 1) / 2;
				}
			}
			if(this.layoutConfigNode.attributes['styleCSS']){
				this.styleCSS = this.layoutConfigNode.attributes['styleCSS'].nodeValue;
			}
			if(this.layoutConfigNode.attributes['htmlContent']){
				this.htmlContent = this.layoutConfigNode.attributes['htmlContent'].nodeValue;
			}
			
			var questionInfo = null;
			array.forEach(this.contextInfo.context.attrs, function(attr){
				if(attr.question_id == this.layoutConfigNode.attributes['id'].nodeValue){
					questionInfo = attr;
				}
			}, this);
			
			//if questioninfo is not found, try finding it by guid to fix imported layout's.
			if(questionInfo == null){
				array.forEach(this.contextInfo.context.attrs, function(attr){
					if(attr.lib_guid != null){
						var guidParts = attr.lib_guid.split('_');
						if(guidParts[guidParts.length-1] == this.layoutConfigNode.attributes['id'].nodeValue){
							questionInfo = attr;
							alert("Question id "+this.layoutConfigNode.attributes['id'].nodeValue+" converted to:\nID: "+attr.question_id+"\ntext:"+attr.question_text+"\nGUID:"+attr.lib_guid);
							this.layoutConfigNode.attributes['id'].nodeValue = attr.question_id;
						}
					}
				}, this);
			}
			
			//remove from contextInfo, leftover attrs will be for available questions
			if(questionInfo != null){
				var index = this.contextInfo.context.attrs.indexOf(questionInfo);
				this.contextInfo.context.attrs.splice(index, 1);
			}
			
			if(this.layoutConfigNode.attributes['id'].nodeValue >= 0){
				this.movable = new LayouteditorMovable({
					questionId: this.layoutConfigNode.attributes['id'].nodeValue, 
					questionInfo: questionInfo
				});
			}
			
			parser.parse();
		},
		
		setHTMLField: function(){
			if(this.layoutConfigNode.attributes['id'].nodeValue == -2){
				domStyle.set(this.htmlContentRow, 'display', '');
			} else if(this.layoutConfigNode.attributes['id'].nodeValue == -1){
				domStyle.set(this.htmlContentRow, 'display', '');
			} else {
				domStyle.set(this.htmlContentRow, 'display', 'none');
			}
		},
		
		postCreate:function(){
			this.inherited(arguments);
			
			this.setHTMLField();
			
			if(this.layoutConfigNode.attributes['id'].nodeValue >= 0){
				domConstruct.place(this.movable.domNode,this.domNode,"last");		
			}
			
			this.domNode.style = this.styleCSS;
			
			this.htmlContentContainer.innerHTML = this.htmlContent;
			
			this.dndSource = new Source(this.domNode, 
				{ 
					singular: true,
					thisCell: this,
					copyState: function(keyPressed){
						return false;
					},
					onDrop: function(source, sourceNodes, copy){
						if(this == source){
							return;
						}
						if(this.thisCell.layoutConfigNode.attributes['id'].nodeValue == -2){
							alert("Cell has HTML content, can't drop question.");
							return;
						}
						
						var switchNodes = false;
						if(this.thisCell.layoutConfigNode.attributes['id'].nodeValue >= 0){
							switchNodes = true;
						}
												
						var target = this;
						target.onDropExternal(source, sourceNodes, copy);
						
						if(switchNodes){							
							var targetNodes = Array();
							targetNodes[0] = target.thisCell.movable.domNode;
							source.onDropExternal(target, targetNodes, copy);
							source.sync();
						}						
						target.sync();						
						
						//update xmldomconfig
						if(typeof source.thisCell != 'undefined'){
							if(target.thisCell.movable == null){
								source.thisCell.layoutConfigNode.setAttribute('id', -1);
							} else {
								source.thisCell.layoutConfigNode.setAttribute('id',target.thisCell.movable.questionId);
							}
						}
						target.thisCell.layoutConfigNode.setAttribute('id',sourceNodes[0].myMovable.questionId);
						
						//place layouteditor obj references
						if(typeof source.thisCell != 'undefined'){
							source.thisCell.movable = target.thisCell.movable;
						}
						target.thisCell.movable = sourceNodes[0].myMovable;
												
						//update htmlField
						target.thisCell.setHTMLField();
						if(typeof source.thisCell != 'undefined'){
							source.thisCell.setHTMLField();
						}
					}
				}					
			);
			
			this.nolabelField.thisCell = this;
			on(this.nolabelField, "change", function(e){
				if(this.checked) {
					this.thisCell.nolabel = 'true';
					this.thisCell.layoutConfigNode.setAttribute('nolabel','true');
				} else {
					this.thisCell.nolabel = 'false';
					this.thisCell.layoutConfigNode.setAttribute('nolabel','false');
				}
				//change event colspan
				on.emit(this.thisCell.colspanField, "change", {
					bubbles: true,
					cancelable: true
				  });
			});
			if(this.nolabel == 'true'){
				this.nolabelField.checked = true;
			}
			
			this.rowspanField.thisCell = this;
			on(this.rowspanField, "change", function(e){
				this.thisCell.rowspan = this.value;
				this.thisCell.domNode.rowSpan = this.value;
				this.thisCell.layoutConfigNode.setAttribute('rowspan',this.value);
			});
			
			this.colspanField.thisCell = this;
			on(this.colspanField, "change", function(e){
				this.thisCell.colspan = this.value;
				this.thisCell.domNode.colSpan = this.value;
				var realColspan = this.value;
				if(realColspan > 1){
					realColspan = (realColspan * 2) - 1;
				}
				if(this.thisCell.nolabel == 'true'){
					realColspan = realColspan + 1;
				}
				this.thisCell.layoutConfigNode.setAttribute('colspan',realColspan);
			});
			
			this.styleCSSField.thisCell = this;
			on(this.styleCSSField, "change", function(e){
				this.thisCell.styleCSS = this.value;
				this.thisCell.domNode.style = this.value;
				this.thisCell.layoutConfigNode.setAttribute('styleCSS',this.value);
			});
			
			this.htmlContentField.thisCell = this;
			on(this.htmlContentField, "change", function(e){
				if(this.value == ''){
					//is question node
					this.thisCell.layoutConfigNode.attributes['id'].nodeValue = -1;
				} else {
					//is text/content node
					this.thisCell.layoutConfigNode.attributes['id'].nodeValue = -2;
				}
				this.thisCell.htmlContent = this.value;
				this.thisCell.htmlContentContainer.innerHTML = this.value;
				this.thisCell.layoutConfigNode.setAttribute('htmlContent',this.value);
				this.thisCell.nolabelField.checked = true;
				on.emit(this.thisCell.nolabelField, "change", {
					bubbles: true,
					cancelable: true
				  });
			});
			
			this.removeCellButton.thisCell = this;
			on(this.removeCellButton, "click", function(e){
				if(this.thisCell.layoutConfigNode.attributes['id'].nodeValue >= 0){
					alert("Cell is not emptey.");
					return;
				}
				this.thisCell.destroy();
			});
			
			parser.parse();
		},
		
		onStart: function(){
			this.inherited(arguments);
			 
			parser.parse();
		},
		
		destroy:function(){
			this.inherited(arguments);
			this.layoutConfigNode.parentNode.removeChild(this.layoutConfigNode);
		}
	});
});	
