var dates = [];

function date_switch(emp) {
	var i = emp.id.toString().replace(/:empty$/,'');
	var f;
	if (!dates[i]){
		f = dates[i] = {
			'year'  : $(i + ':year'),
			'month' : $(i + ':month'),
			'day'   : $(i + ':day'),
			'hh'    : $(i + ':hh'),
			'mm'    : $(i + ':mm'),
			'empty' : emp
		};
	}else{
		f = dates[i];
	}
	var dis = f['empty'].checked;
	['year','month','day','hh','mm'].each(function(item){
		f[item].disabled = dis;
	});
	return;
}
function toggle_extended_image(id) {
	var i = $(id + ':extend');
	var div = $(id + ':extended');
	if (!div) return;
	if (div.style.display == 'none') {
		i.innerHTML = '-';
		Element.show(div);
	}else{
		i.innerHTML = '+';
		Element.hide(div);
	}
	return;
}

function listbox_select(id) {
	var d = $(id + ':selected');
	var s = $(id);
	if (!d || !s) return;
	var list = [];
	$A(s.options).each(function(o){
		if (o.selected && o.value != '')
			list.push(o.innerHTML);
	});
	d.innerHTML = list.join(', ');
	return;
}
function check_password2(id, login_id) {
	var a = $(id + ':0');
	var b = $(id + ':1');
	var c = $(id + ':crypt');
	var e = $(id + ':error');
	var login;
	var lgn = $( login_id );
	if (lgn) login = lgn.value.replace(/(?:^\s*|\s*$|@.*$)/ig,'');
	if (a && b && c && e) {
		c.className = '';
		e.innerHTML = '';
		var av = a.value;
		var bv = b.value;
		if (av) {
			// check strongness
			if (login && av == login) {
				e.innerHTML = 'Пароль не должен совпадать с логином';
			}else{
				var l = 0;
				if (av.match(/[a-z]/)) l++;
				if (av.match(/[A-Z]/)) l++;
				if (av.match(/\d/)) l++;
				if (av.match(/\s/)) l++;
				if (av.match(/[\!\@\#\$\%\^\&\*\(\)\[\]]/)) l += 2;
				var states = [ 12,10,8,7,6,6 ];
				var fl = states[l] || states[0];
				var len = av.length;
				var w =  Math.round( 100 * len  / fl );
				if (w > 100) w = 100;
				if (  len > fl ) { l = Math.round( l * 1.2 * len / fl ) }
				if (l > 5) l = 5;
				c.className = 'l' + l;
				c.style.width = w + '%';
			}
			
			// check validity
			if (av && bv && av != bv) {
				e.innerHTML = 'Пароли не совпадают';
			}
		}
	}else{
		alert('no object for ' + id + "\n" + a + "\n" + b + "\n" + c + "\n" + e);
	}
}
if ( Prototype ){
	var FileSet = Class.create();
	FileSet.prototype = {
		getType : function () { return 'FileSet'; },
		toString : function () { return this.getType(); },
		initialize : function (id) {
			var self = this;
			self.sample = $(id);
			self.limit = self.sample.getAttribute("limit") || 10;
			self.sample.id = null;
			self.basket = $(id + ':basket');
			self.hidden = $(id + ':hidden');
			self.current = $(id + ':current');
			self.overflow = null;
			self.bykey   = [];
			self.count   = 0;
			self.sample.parentNode.removeChild(self.sample);
			if (self.sample.value) {
				self.input = self.sample.cloneNode(true);
				self.sample = $file(null,self.sample.name,{ size : self.sample.size });
			}
			self.newInput();
			//cell.onchange = self.on_change.bindAsEventListener( self );
		},
		onDelete : function (e,o) {
			var self = this;
			var fn = o.input.value;
			if (!fn) return;
			if (!self.bykey[fn]) return;
			self.basket.removeChild(o.item);
			self.hidden.removeChild(o.input);
			self.bykey[fn] = null;
			self.count--;
			if (self.overflow) {
				self.current.removeChild(self.overflow);
				self.overflow = null;
				self.newInput();
			}
		},
		newInput : function () {
			var self = this;
			if (self.input) {
				var fn = self.input.value;
				if (!fn) return;
				if (self.bykey[fn]) {
					alert("This file already selected!");
					return;
				}
				self.hidden.appendChild(self.input);
				var sfn = fn.replace(/^.*(?:\\|\/)([^\\\/]+)$/,"$1");
				var btn;
				var item = $div(
					$span(sfn),
					btn = $button(null,null,'x'),
					{ className : 'item' }
				);
				var o = {
					input : self.input,
					item  : item
				};
				btn.onclick = self.onDelete.bindAsEventListener( self, o );
				
				//self.stored.push(o);
				self.basket.appendChild( item );
				self.bykey[fn] = self.input;
				self.count++;
				self.input.onchange = null;
				self.input = null;
			}
			if (self.count >= self.limit) {
				self.overflow = $div("Maximum reached: " + self.count,{className : 'overflow'});
				self.current.appendChild( self.overflow );
				return;
			}
			self.input = self.sample.cloneNode(true);
			self.input.onchange = self.onPick.bindAsEventListener( self );
			self.current.appendChild(self.input);
		},
		onPick : function (e) {
			this.newInput();
		},
		
		noop : function () {}
	};

	var TableEditCreatorClass = Class.create();
	TableEditCreatorClass.prototype = {
		getType : function () { return 'TableEditCreatorClass'; },
		toString : function () { return this.getType(); },
		initialize : function (cls) {
			var self = this;
			if (!cls) var cls = 'tableedit';
			var list = document.getElementsByClassName(cls);
			self.items = [];
			list.each(function(item){
				if (item && item.tagName && item.tagName.match(/textarea/i)) {
					self.items.push(new TableEditClass(item,cls));
				}
			});
		},
		noop : function () {}
	};
	var TableEditClass = Class.create();
	TableEditClass.prototype = {
		getType : function () { return 'TableEditClass'; },
		toString : function () { return this.getType(); },

		row_move_up : function (e) {
			var row = e.target.parentNode.parentNode;
			var prow = row.previousSibling;
			var nrow = row.nextSibling;
			var p = row.parentNode;
			if (prow){
				if (nrow){
					p.insertBefore(prow,nrow);
				}else{
					p.appendChild(prow);
				}
			}
			this.normalize_state();
			this.on_change();
		},

		row_move_dn : function (e) {
			var prow = e.target.parentNode.parentNode;
			var row = prow.nextSibling;
			if (row) {
				prow.parentNode.insertBefore(row,prow);
			}
			this.normalize_state();
			this.on_change();
		},

		row_delete : function (e) {
			var row = e.target.parentNode.parentNode;
			var p = row.parentNode;
			var prow = row.previousSibling;
			var nrow = row.nextSibling;
			if (prow || nrow){
				p.removeChild(row);
				this.normalize_state();
				this.on_change();
			}
		},

		row_add : function (e) {
			//var row = e.target.parentNode.parentNode;
			this.body.appendChild(this.row_create());
			this.normalize_state();
			this.on_change();
		},

		openFileBrowserOnLoad : function ( e, item, win, w, h ) {
			win.setFCallback(
				this.fileBrowserCallback.bind( this,item )
			);
			try { win.resizeTo(w, h); } catch (e) {}
			try { win.focus(); } catch (e) {}
		},
		openFileBrowser : function ( e, item ) {
			var self = this;
			var x,y,width,height;
			width=640;
			height = 480;
			x = parseInt(screen.width / 2.0) - (width / 2.0);
			y = parseInt(screen.height / 2.0) - (height / 2.0);
			
			var win = window.open(
				"/files/:",
				"fileBrowser",
				"dialog=yes,fullscreen=no,resizable=no,modal=yes," + 
				"menubar=no,toolbar=no,scrollbars=no,"+
				"left="+x+",top="+y+",width=" + width + ",height=" + height
			);
			if (!win) {
				alert('Popup blocked');
				return;
			}
			Event.observe(win,'load',self.openFileBrowserOnLoad.bindAsEventListener( self, item, win, width, height ));
			//win.onload = ;
		},
		fileBrowserCallback : function (item,url) {
			item.cell.value = url;
			item.icon.href = url;
			Element.show(item.have);
			Element.hide(item.edit);
		},
		cleanCell : function (e,item) {
			Element.hide(item.have);
			Element.show(item.edit);
			item.cell.value = '';
			item.icon.href = '#';
		},
		row_create : function(data, cells) {
			var self = this;
			if (!data) var data = [];
			if (!cells) var cells = [];
			return $tr([].concat(
				[
					$td( self.left_row_controls() )
				],
				self.columns.map(function(col,idx){
					var x;
					var id,name,attr = { className : 'cell-edit' };
					if (col){
						name = id = self.id + ':' + col.id + ':' + idx;
						attr['size'] = col.size;
					}
					var cell,td;
					if (col.type == 'photo') {
						cells[idx] = cell = $hidden(id,name,data[idx] || '',attr)
						cell.readOnly = true;
						var btn = $button(id+':s',name+':s','?');
						var del = $button(id+':d',name+':d','x');
						//cell.innerHTML = self.getBrowserHTML('hrefbrowser','href','file','advlink');
						var icon,have;
						
						td = $td(
							cell,
							have = $span( 
								icon = $linkicon('#','/lib/css/f/img.gif','',16,16),
								del
							),
							btn
						);
						var item = {
							'cell' : cell,
							'edit' : btn,
							'have' : have,
							'icon' : icon
						};
						btn.onclick = self.openFileBrowser.bindAsEventListener( self,item );
						btn.className = 'button';
						del.onclick = self.cleanCell.bindAsEventListener( self,item );
						del.className = 'button';
						Element.hide(have);
						if (data[idx]) {
							self.fileBrowserCallback(item,data[idx])
						}
					}else{
						td = $td( cells[idx] = cell = $input(id,name,data[idx] || '',attr) );
					}
					//if ( cell )
						cell.onchange = self.on_change.bindAsEventListener( self );
					return td;
				}),
				[
					$td( self.right_row_controls() )
				]
			));
		},
		
		left_row_controls : function (index,total) {
			var b_up = $button('','','^',{className : 'button up' });
			var b_dn = $button('','','v',{className : 'button dn' });
			b_up.onclick = this.row_move_up.bindAsEventListener( this );
			b_dn.onclick = this.row_move_dn.bindAsEventListener( this );
			return [
				b_up,
				b_dn
			];
		},
		right_row_controls : function () {
			var b_dl = $button('','','x',{className : 'button dl'})
			b_dl.onclick = this.row_delete.bindAsEventListener( this );
			return [
				b_dl
			];
		},
		
		normalize_state : function () {
			Element.removeClassName(this.first_row,'first');
			Element.removeClassName(this.last_row,'last');
			Element.addClassName(this.first_row = $A(this.body.childNodes).first(),'first');
			Element.addClassName(this.last_row = $A(this.body.childNodes).last(),'last');
		},
		
		find_form : function () {
			var self=this;
			var node = self.input;
			while (node && node.tagName && !node.tagName.match(/^form$/i)){
				node = node.parentNode;
			}
			if (node && node.tagName && node.tagName.match(/^form$/i)) {
				this.form = node;
				return true;
			}else{
				return false;
			}
		},
		noform_on_change : function ( e ) {
			//alert('test');
			this.serialize();
		},
		initialize : function (item,cls) {
			var self = this;
			self.input = $(item);
			Element.hide(self.input);
			if (!self.find_form()){
				self.on_change = self.noform_on_change;
			}else{
				self.on_change = function () {};
				Event.observe(self.form, 'submit', self.noform_on_change.bindAsEventListener( self ));
			}
			self.id = self.input.id || new Date().getTime().toString();
			var params = self.input.getAttribute(cls);
			var columns = [];
			if (params) {
				var cols = params.split(/;/);
				cols.each(function(col,idx){
					var prm = col.split(/:/);
					var id,title,length,type;
					if (prm.length == 4){
						id = prm[0];
						title = prm[1];
						length = prm[2];
						type = prm[3];
					}else
					if (prm.length == 3){
						id = prm[0];
						title = prm[1];
						length = prm[2];
					}else
					if (prm.length == 2) {
						title = id = prm[0];
						length = prm[1];
					}
					columns[idx] = {
						'id' : id,
						'title' : title,
						'type' : type,
						'size' : length || 10
					};
				});
			}
			self.columns = columns;
			self.rows = [];
			self.cells = [];
			
/*			var rows = self.input.value.split(/\r?\n/);
			if (rows[rows.length - 1]) rows.push('');*/
			var tbody = [];
			self.head = $thead($tr([].concat(
				[
					$td('&nbsp;')
				],
				columns.map(function(col,idx){
					return $th(col.title)
				}),
				[
					$td('&nbsp;')
				]
			)));

			var rows = self.deserialize(self.input.value);
			tbody = rows.map( self.row_create.bind( self ) );

/*			rows.each(function(row,rowidx){
				var cols = row.split('||') || [];
				tbody.push( self.row_create( cols ) );
				//var irow = [];
				//tbody.push( self.row_create( cols, irow ) );
				//self.cells.push(irow);
			});*/
			//Element.addClassName(tbody.first(),'first');
			//Element.addClassName(tbody.last(),'last');
			var foot;
			var b_add = $button('','','+',{className : 'button add' });
			b_add.onclick = this.row_add.bindAsEventListener( this );
			var b_ser = $button('','','serialize',{className : 'button serialize' });
			b_ser.onclick = this.serialize.bindAsEventListener( this );
			
			this.table = $table(
				{
					className : cls,
					border : 0
				},
				self.head,
				self.body = $tbody(tbody),
				self.foot = $tfoot(
					$tr(
						foot = $td(b_ser, b_add)
					)
				)
			);
			foot.colSpan = columns.length + 2;
			foot.align = 'right';
			this.row_add();
			this.normalize_state();
			this.input.parentNode.insertBefore(this.table,this.input);
		},
		serialize : function () {
			var self = this;
			var data = [];
			$A(self.body.childNodes).each(function(row){
				var items = [];
				$A(row.childNodes).each(function(cell){
					//var push = false;
					//alert($A(cell.childNodes).length);
					$A(cell.childNodes).each(function(item){
						if (!Element.hasClassName(item,'cell-edit')) return;
						//if (!item.className.match(/\bcell-edit\b/i)) return;
						//alert(item.className);
						/*
						if (!(item && item.tagName
							&& item.tagName.match(/imput/i)
							&& item.type.match(/text/)
						)) return;
						*/
						//alert(item);
						items.push(item.value);
						//push = true;
					})
					//if (push)
				});
				if (items.without('').length > 0)
					data.push(items);
			});
			this.input.value = self.beautyJSON(data.toJSON());
			/*
			data.map(function(row){
				return row.map(function(item){
					return self.encode(item);
				}).join('||');
			}).join("\n")+ "\n";
			*/
			//return ;
		},
		beautyJSON : function (data,indent){
			return data;
			var self = this;
			if (!ident) var ident = '';
			return data.replace(/\[(.+)\]/g,function(){
				var m = arguments[1];
				if (m.match(/^\s*\[[^\[]+\],/)) {
					m = m.replace(/\],\[/,"],\n[");
				}
				return "[\n" + self.beautyJSON (m,ident + "\t") + "\n]";
			});
		},
		deserialize : function (data) {
			var self = this;
			return Try.these(
				function(){ return data.evalJSON(); },
				function(){ return [[]]; }
			);
			var self = this;
			var result = [];
			var rows = data.split(/\r?\n/);
			if (rows[rows.length - 1]) rows.push('');
			rows.each(function(row,rowidx){
				var cols = $A( row.split(/(?!\\)\|\|/) || [] ).map( self.decode );
				result.push(cols);
			});
			return result;
		},
		noop : function () {}
	};
	Event.observe(window, 'load', function() {
		new TableEditCreatorClass();
	});
}
