/**
 * @author uruk
 */
var PlateEditor = new Class({
	'Implements': [Options, Events],
	'Config': { 'charsPerRow': 15 }, 
	'options': { 'text': '', 'productid': null }, 
	
	'initialize': function(options) {
		this.setOptions(options);
		this.Cover = new Element('div', { 'id': 'plateCover', 'events': { 'click': function() { this.deactivate(); }.bind(this) }}); 
		this.Body = $$('body')[0]; 
		this.Center = new Element('div', { 'id': 'plateCenter' }); 
		this.Container = new Element('div', { 'id': 'plateContainer' }); 
		this.Image = new Element('img', { 'id': 'plateImage' }); 
		this.Rows = this.getRowCount();
		this.InputContainer = new Element('div', { 'id': 'inputContainer' });
		this.SaveButton = new Element('a', { 
			'text': 'Speichern', 
			'href': 'javascript:;',
			'id': 'ple_speichern', 
			'events': {
				'click': function() {
					var t = '';
					$$('#inputContainer input').each(function(inp) {
						var val = inp.get('value');
						t += val + "**********";
					});
					t = t.substr(0, t.length-10);
					addToCart({
						'zuckertext': t,
						'zid': parseInt(this.options.productid)
					});
					$('zuckertext').set('value', t);
					this.deactivate();
				}.bind(this)
			}
		})
	}, 
	
	'activate': function() {
		if($chk($('plateCover'))) $('plateCover').dispose();
		if($chk($('plateCenter'))) $('plateCenter').dispose();
		this.Cover.inject(this.Body);
		this.Cover.setStyle('height', this.Body.getScrollSize().y + 200);
		this.Center.inject(this.Body);
		this.Container.inject(this.Center);
		this.InputContainer.inject(this.Container);
		this.Image.inject(this.Container);
		this.SaveButton.inject(this.Container);
		this.render();
	}, 
	
	'render': function() {
		this.Image.set('src', 'sub/onlineshop/ple/plate-'+this.Rows+'.jpg');
		this.InputContainer.empty();
		for(var i=0;i<this.Rows;i++) {
			var inp = new Element('input', { 
				'id': 'ple_'+(i+1)+'_'+this.Rows,
				'value': this.options.text.substr(i*this.Config.charsPerRow, this.Config.charsPerRow),
				'class': 'ple', 
				'events': {
					'keyup': function() {
						this.renderTextFields();
					}.bind(this)
				}
			}).inject(this.InputContainer);
			inp.focus();
		}
	}, 
	
	'renderTextFields': function() {
		var t = '';
		var ren = 0;
		$$('#inputContainer input').each(function(inp) {
			var val = inp.get('value');
			t += val;
			if(val.length == 0) ren++;
		});
		if(t.length > 3 * this.Config.charsPerRow) {
			t = t.substr(0, 3 * this.Config.charsPerRow);
			ren++;
		}
		this.options.text = t;
		var nr = Math.ceil(this.options.text.length / this.Config.charsPerRow);
		if(nr != this.Rows) ren++;
		if(ren > 0) {
			this.Rows = this.getRowCount();
			this.render();
		}
	}, 
	
	'getRowCount': function () {
		var n = Math.ceil(this.options.text.length / this.Config.charsPerRow);
		if(n < 1) n = 1;
		return n;
	}, 
	
	'deactivate': function() {
		this.Cover.dispose();
		this.Center.dispose();
	}
	
	
	
	
});