/*
    Copyright (C) 2008  Ivo Toby, Internet Voor Ondernemers, http://www.i-v-o.nl / http://syntacticsugar.nl 

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

	Crudder Version : 0.50b
 */


	var crudderRecord = Class.create(crudderView, {

		initialize:function($super, metaData, container, controller){
			$super(metaData, container, controller);
			this.instID = 'crudderRecord.' + parseInt(Math.random()*1000000);
			this.isNew = false;
		},
		
		draw : function(row){
			if (!row ) this.isNew = true;
			this.controller.handleCustomEvent('beforeopenrecord');
			var table = new Element('table', {className:'crudderRecord'});
			if (this.isNew){
				this.pKeyValue = 0;	
			}else{
				this.pKeyValue = row[this.pKey];
			}
			this.container.update(table);
			var head = new Element('tbody');
			table.insert(head);
			
			this.drawHead(head);
			this.dataContainer = new Element('tbody');
			table.insert(this.dataContainer);
//			var head = this.drawGridHead(table);
			var RPCObj = new crudderRPC(this.controller.config, this.controller.rpcPath);
//			RPCObj.debug = true;

			RPCObj.attachWaiter(this.controller.waiter, this.controller);
			RPCObj.attachUnWaiter(this.controller.unWaiter, this.controller);
			RPCObj.createCall();
			RPCObj.setCallback(this.drawRecord.bind(this));
			RPCObj.setMethod('getData');
			RPCObj.addArgument('pKey', this.pKeyValue);
			RPCObj.call();
		},
		
		drawHead : function(container){
			// create title of table:
			var td = new Element('td', {colspan:this.getColCount() }).update(this.metaData.table.friendlyName);
			var tr = new Element('tr').update(td);
			var tbody = new Element('tbody', {className:'crudderGridTitle'}).update(tr);
			container.insert(tbody);

		},
		
		drawRecord : function(req){
			this.controller.waiter();
			var i=0;
			if (!this.isNew){
				var record = req.responseJSON.data[0];	
			}else{
				var record = new Object();
			}
			
			this.fields.values().each(
				(function(fieldObj){
					if (fieldObj.field.name != this.pKey){
						var tr = new Element('tr');
						this.dataContainer.insert(tr);
						var td = new Element('td', {className:'crudderFieldTitle', id: fieldObj.field.name + "_title"}).insert(fieldObj.getTitle());
						if (i%2==0) td.addClassName('on');
						tr.appendChild(td);
						var td = new Element('td', {className:'crudderFieldTitle', id: fieldObj.field.name + "_editor"});
						if (i%2==0) td.addClassName('on');
						tr.appendChild(td);
						fieldObj.drawEditor(td, record);
						i++;
					}
				}).bind(this)
			)
			// add controls:
			this.drawControls(this.dataContainer);
			this.controller.handleCustomEvent('afteropenrecord');
			this.controller.unWaiter();
		},
		
		drawControls : function(container){
			var cancel = new Element('button', {className:'crudderRecordControl'}).update(this.controller.lang.get('cancelButton'));
			var tr = new Element('tr');
			container.insert(tr);
			var td = new Element('td', {colspan:this.getColCount()}).insert(cancel);
			tr.insert(td);
			cancel.observe('click', this.cancel.bindAsEventListener(this));

			var save = new Element('button', {className:'crudderRecordControl'}).update(this.controller.lang.get('saveButton'));
			td.insert(save);
			save.observe('click', this.save.bindAsEventListener(this));
			
		},
		
		cancel : function(event){
			this.fields.values().each(
					function(field){
						field.close();
					}
			);
			this.controller.closeRecord();
		},
		
		save : function(event){
			// first validate the fields:
			var OK = true;
			try{
				this.fields.values().each(
					function(fieldObj){
	//					if (fieldObj.field.name != this.pKey && fieldObj.field.metaType != 'readonly' && fieldObj.field.metaType != 'auto_datetime'){
						if (fieldObj.field.name != this.pKey ){
							if (!fieldObj.validate()) OK = false;
						}
					}
				)
				if (OK){
					var RPCObj = new crudderRPC(this.controller.config, this.controller.rpcPath);
					RPCObj.debug = true;
					RPCObj.attachWaiter(this.controller.waiter, this.controller);
					RPCObj.attachUnWaiter(this.controller.unWaiter, this.controller);
					RPCObj.createCall();
					if (this.isNew){
						RPCObj.addArgument('add', 'true');
						var func = (function(req){this.setSaved(req, true)}).bind(this)
					}else{
						this.controller.handleCustomEvent('beforeupdate');
						RPCObj.addArgument('pKey', this.pKeyValue);	
						var func = (function(req){this.setSaved(req, false)}).bind(this)
					}
					RPCObj.setCallback(func);
					RPCObj.setMethod('save');
					this.fields.values().each(
						(function(fieldObj){
	//						if (fieldObj.field.name != this.pKey && fieldObj.field.metaType != 'readonly' && fieldObj.field.metaType != 'auto_datetime' ) {
							if (fieldObj.field.name != this.pKey ) {
								if (fieldObj.shouldStore) RPCObj.addArgument(fieldObj.field.name,  fieldObj.getRPCValue() );
							}
						}).bind(this)
					)
					RPCObj.call();
				}
			}catch(e){
				if (window.console) console.log(e);
				return false;
			}
				
		},
		
		setSaved : function(req, isNew){
			// handle UPLOAD-fields
			this.fields.values().each(
					(function(fieldObj){
						if (fieldObj instanceof crudderField.file){
							if (fieldObj.shouldUpload){
								// file has actually changed, so it needs to be uploaded:
								fieldObj.doUpload(req.responseJSON[1].pKey);
							}
							
						}
					}).bind(this)
				)

			if (isNew){
				this.controller.handleCustomEvent('aftercreate');
			}else{
				this.controller.handleCustomEvent('afterupdate');
			}
			
			if (req.responseJSON[0].message=='true'){
				if (this.onUpdate){
					this.onUpdate();
				}else{
					this.controller.table.getData();
					this.cancel();
				}
			}else{
				if (confirm(this.controller.lang.get('ErrorOrNotSaved') + " [ error : " + req.responseJSON[0].message + " ] ")){
					this.cancel();
				}
			}
		},
		
		getColCount : function(){
			return 2;
		}
		
	})