define([
    "dojo/_base/declare",
    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dojo/request/iframe",
    "dojo/_base/window",
    "dojo/_base/sniff",
    "dojo/dom",
    "dojo/on",
    "dojo/_base/array",
    "dojo/text!./templates/FileUpload.html"
], function(declare, _WidgetBase, _TemplatedMixin,iframe,win,has,dom,on,array,template) {
	return declare("form.FileUpload",[_WidgetBase, _TemplatedMixin], {
		//properties
		templateString: template,
		url:"cheyenne?cddid=xam.handle_document",
		value:"",
		id:"",
		readonly:false,
		answerNumber:null,
		sessionId:"",
		doc_id:null,
		doc_path:null,
		fileBase:"",
		app_path:"",
		
		
		//constructor
		constructor: function(args){
		    //this.loadItems();
			declare.safeMixin(this,args);
		},
		
		//overwrite postCreate
		postCreate:function(){
			this.inherited(arguments);
			
			var _this=this;
			//connect onchange event of the filepicker to handle upload
			on(this.selNode,"change",function(e){
				_this.handleUpload();
			});
		},
		
		_setValueAttr: function(val){
			console.log("_setValueAttr called",val);
			var parts=val.split('^^');
			this.doc_id=parts[0];
			if (parts[1]!='') {
				this.doc_path=parts[1];
				this.answerNumber=this.doc_id;
			}
			this.dataNode.value=val;
		},
		
		handleUpload: function(){
			console.log("handle upload");
			this.onStart(this);
			var filename=this.selNode.value.replace("C:\\fakepath\\", "");
			//sanatize filename
			filename=filename.replace(/\s/g,"_").replace(/[^0-9A-Za-z\.\-_]/gi, '_');
			var _url=this.url;
			_url += "&sid=" + this.sessionId;
			_url += "&P_DOC_ID=" + this.doc_id;
			_url += "&P_DOC_NAME=" + this.fileBase + encodeURIComponent(filename); //.replace(/[^0-9A-Za-z\-_]/gi, '_');
			_url += "&P_APP_PATH=" + encodeURIComponent(this.app_path);
			_url += "&METHOD=post&cmode=wrappedJSON"
			console.log("post url",_url);

			//create form
			var _newForm;
			var _this=this;
			if(has('ie') < 9 || (has('ie') && has('quirks'))){
				// just to reiterate, IE is a steaming pile of code.
				_newForm = document.createElement('<form enctype="multipart/form-data" method="post" >');
				_newForm.encoding = "multipart/form-data";
				
			}else{
				// this is how all other sane browsers do it
				_newForm = document.createElement('form');
				_newForm.setAttribute("enctype","multipart/form-data");

			}
			
			var orgSelParent=this.selNode.parentNode
			_newForm.appendChild(this.selNode);
			win.body().appendChild(_newForm);
			this.progressNode.innerHTML="uploading...<input type=\"hidden\" name=\"upload_form\" />";	
			//submit
			iframe(_url, {
			    handleAs: "json",
			    form: _newForm,
			    debug:true
			  }).then(function(xmldoc){
			    console.log(xmldoc);
			    _this.dataNode.value=xmldoc.id + "^^" + xmldoc.name;
			    _this.progressNode.innerHTML="";
			    _this.onStop(_this);
				_this.onFinish(_this);
			  }, function(err){
			    // Handle the error condition
			    _this.progressNode.innerHTML="<span class=\"error\">Upload mislukt, probeer opnieuw</span>";
			    console.error(err);
			    _this.onStop(_this);
			  },function(prog){
				  console.log("progress:",prog);
			  });
			console.log('remove form');
			orgSelParent.appendChild(this.selNode);  
			win.body().removeChild(_newForm);
		},
		
		onStart: function(obj){
			console.debug("FileUpload.onStart called");
			array.forEach(this.selNode.form,function(inputObj){
				if ("type" in inputObj && inputObj.type=="button"){
					inputObj.disabled=true;
				}
			});
		},
		
		onStop: function(obj){
			console.debug("FileUpload.onStop called");
			array.forEach(this.selNode.form,function(inputObj){
				if ("type" in inputObj && inputObj.type=="button"){
					inputObj.disabled=false;
				}
			});
		},
		
		onFinish: function(obj){
			
		}		
	});
});



function uploadsdone() {
	
	var cnt = document.getElementsByName('upload_form');
	console.log(cnt.length);
	return (cnt.length == 0);
}