TSButtons = Class.create();
TSButtons.instances = [];

TSButtons.prototype = Object.extend(TSButtons,{
	initialize : function(options){
		TSButtons.instances[TSButtons.instances.length] = this;
		this.run(options);
	},
	run : function(options){
		this.options = Object.extend({
			type : 'edit',
			item : null,
			parent : null,
			url : null,
			level : null,
			langs : ['ru','en'],
			delay : .1,
			alt : '',
			src : false,
			target : false
		},options || {});
		this.options.img = '/img/'+this.options.type+'_16.gif';
		this.delay = this.options.delay;
		this.create();
	},
	create : function(){
		var tmp_id = parseInt(Math.random()*1000);
		if (this.options.target){
			this.target = $(this.options.target);
		}else if (!this.options.src){
			document.write('<span id="btn__'+tmp_id+'">_runtime-created element</span>');
			try {this.target = $($('btn__'+tmp_id).up());}catch(e){};
			$('btn__'+tmp_id).remove();
		}else{
			try{
				this.target = $(this.options.src).up();
				$(this.options.src).remove();
			} catch(e){};
			
		}
		this.control = new Element('img',{src:this.options.img,border:0,alt:this.options.alt});
		try{
			$(this.target).appendChild(this.control);
		}catch(e){};
		this.control.observe('mouseover',function(event){
			this.cntr=0;
			this.holding = true;
			if (this.menu) $(this.menu).hide();
			this.execut = new PeriodicalExecuter(function(pe){
				if(++this.cntr>4){
					pe.stop();
					if(this.holding) this._menu(event);
				}
			}.bind(this),this.delay);
		}.bind(this));
		this.control.observe('mouseup',function(event){
			this.holding = false;
			this.cntr2 = 0;
			if (this.menu) if (this.menu.visible()) Event.stop(event);
			new PeriodicalExecuter(function(pe){
				if (++this.cntr2>2){
					//if (this.menu && !this.holding) $(this.menu).hide();
					pe.stop();
				}
			}.bind(this),this.delay);
			if (!this.holding) edit_item(this.control,this.options.item,this.options.parent,this.options.url,this.options.level);
		}.bind(this));
		this.control.observe('mouseover',function(event){
			/*this.holding = false;
			this.cntr2 = 0;
			new PeriodicalExecuter(function(pe){
				if (++this.cntr2>2){
					//if (this.menu && !this.holding) $(this.menu).hide();
					pe.stop();
				}
			}.bind(this),this.delay);*/
		}.bind(this));
		this.control.observe('mouseout',function(event){
			this.holding = false;
			this.cntr2 = 0;
			new PeriodicalExecuter(function(pe){
				if (++this.cntr2>1){
					//if (this.menu && !this.holding) $(this.menu).hide();
					pe.stop();
				}
			}.bind(this),this.delay);
		}.bind(this));
	},
	_menu : function(event){
		var pos = (Prototype.Browser['IE']?$(this.control).positionedOffset():$(this.control).cumulativeOffset());
		var elm = Event.element(event);
		if (!this.menu){
			this.menu = new Element('table');
			for(i=0;i<this.options.langs.length;i++){
				var tr = $(this.menu).insertRow(-1);
				var td = tr.insertCell(-1);
				$(td).update().addClassName('lang');
				$(td).writeAttribute('lang',this.options.langs[i]);
				var a = new Element('a',{'href':'javascript:void(0);'});
				$(td).appendChild(a);
				$(a).update(this.options.langs[i]);
				$(a).observe('click',function(event){
					edit_item(this.control,this.options.item,this.options.parent,this.options.url,this.options.level,Event.element(event).up().readAttribute('lang'));
				}.bind(this));
			}
			$(elm.up()).appendChild(this.menu);
			$(this.menu).observe('mouseover',function(event){
				this.holding = true;
				if (this.per) this.per.stop();
			}.bind(this));
			$(this.menu).observe('mouseout',function(event){
				this.holding = false;
				this.cntr2 = 0;
				var el = Event.element(event);
				this.per = new PeriodicalExecuter(function(pe){
					if (++this.cntr2 > 1 ){
						$(this.menu).hide();
						pe.stop();
					}
				}.bind(this),.1);
			}.bind(this));
			$(this.control).observe('mouseup',function(event){
				var elm = Event.element(event);
				if ($(elm).hasClassName('lang')){
				}
			}.bind(this));
			$(this.menu).observe('mousemove',function(event){
				var elm = Event.element(event);
				this.holding = true;
			}.bind(this));
		}else{
			$(this.menu).show();
		}
		if (this.menu){
			$(this.menu).setStyle({'background':'#FFFFFF','position':'absolute','left':pos[0],'top':pos[1],'border':'1px solid #000000','cursor':'hand'});
			this.holding = true;
		}
	}
});


TSMenu = Class.create();
TSMenu.instances = [];

TSMenu.prototype = Object.extend(TSMenu,{
	initialize : function(options){
		TSMenu.instances[TSMenu.instances.length] = this;
		this.run(options);
	},
	load_config : function(){
	},
	run : function(options){
		this.iframe = false;
		this.options = Object.extend({
			control : false,
			item : null,
			img_path : '/img/',
			admin : false,
			level : 0,
			sort_branch : 'Сортировать ветку ',
			lang : 'ru',
			delay : .7,
			delay1: .2
		}, options || {});
		this.hidden = true;
		this.children = [];
		this.is_flash = true;
		if (this.control = $(this.options.control)){
			this.options.level = $(this.control).readAttribute('level');
			this.control.observe('mouseover',function(event){
				this.period = 0;
				this.show = true;
				this.shower = new PeriodicalExecuter(function(pe){
					if (++this.period>1){
						this.period=0;
						if (this.show && this.hidden) this._draw_first(this.control);
						pe.stop();
					}
				}.bind(this),this.options.delay1);
				
			}.bind(this));
			this.control.observe('mouseout', function(event){
				this.show = false;
				this.period = 0;
				this.hider = new PeriodicalExecuter(function(pe){
					if (++this.period>2){
						this.period =0;
						if (!this.show){
							for(i=0,n=this.children.length;i<n;i++) this.children[i]._hide();
							this._hide(this.control);
							pe.stop();
						}
					}
				}.bind(this),this.options.delay);
			}.bind(this));
		}// else p('no element',1);
	},
	_draw_first : function(elm){
		this.hidden = false;
		this.hideFlash();
		//this.hide_level = this.options.level;
		if (!this.table){

			if (Prototype.Browser['IE']) this.iframe = new Element('iframe');

			this.table = new Element('table').addClassName('menu_table');
			/*if (elm.readAttribute('have_sub')){
				$$('.menu_table .menu_sub').invoke('hide');
				this.table.addClassName('menu_sub');
			} */
			this.target = $(this.control).up();
			if (Prototype.Browser['IE']){
				this.target.appendChild(this.iframe);
				$(this.iframe).writeAttribute('frameborder','0');
			}
			try{
				this.target.appendChild(this.table);
			}catch(e){};
			var cl = this._extract_id(elm);
			var items = $$('#my_menu a.parent-'+cl['item']);
			
			for(i=0,n=items.length;i<n;i++){
				var tr = $(this.table).insertRow(-1);
				have_sub = false;
				if (it = items[i].readAttribute('item')){
					var sub = $$('#my_menu a.parent-'+it);
					if (sub.length>0) have_sub = true;
				}
				if (this.options.admin){
					var par = $(items[i]).readAttribute('parent');
					var td1 = tr.insertCell(-1);
					new TSButtons({item:it,parent:par,url:items[i],target:td1});
					var txt = '';//'<img src="'+this.options.img_path+'edit_16.gif" border="0" alt="Редактировать" onclick="edit_item(this,\''+it+'\',\''+par+'\',\''+items[i]+'\',\''+this.options.level+'\');" title="Редактировать" />';
					txt+='  <img src="'+this.options.img_path+'del_16.gif" border="0" onclick="del_item(this,\''+it+'\',\''+par+'\',\''+items[i]+'\',\''+this.options.level+'\',\''+this.options.lang+'\');" alt="Удалить" title="Удалить" />';
					txt+='  <img src="'+this.options.img_path+'docs_16.gif" border="0" onclick="new_item(this,\''+it+'\',\''+par+'\',\''+items[i]+'\',\''+this.options.level+'\,\''+this.options.lang+'\');" alt="Новый" title="Новый" />';
					$(td1).writeAttribute('parent',par);
					$(td1).writeAttribute('item',it);
					$(td1).writeAttribute('link',items[i]);
					var del = new Element('img',{'src':this.options.img_path+'del_16.gif','border':0});
					$(td1).appendChild(del);
					$(del).observe('click',function(event){
						var em = Event.element(event);
						var t = $(em).up();
						del_item(em,$(t).readAttribute('item'),$(t).readAttribute('parent'),$(t).readAttribute('link'),this.options.level,this.options.lang);
					}.bind(this));
					var add = new Element('img',{'src':this.options.img_path+'docs_16.gif','border':0});
					$(td1).appendChild(add);
					$(add).observe('click',function(event){
						var em = Event.element(event);
						var t = $(em).up();
						new_item(em,$(t).readAttribute('item'),$(t).readAttribute('parent'),$(t).readAttribute('link'),this.options.level);
					}.bind(this));
					//$(td1).innerHTML+=txt;
					$(td1).addClassName('spec').writeAttribute('nowrap','nowrap');
				}
				var td = tr.insertCell(-1);
				if (have_sub){
					$(items[i]).addClassName('accept_child');
				}
				$(td).update(('<a id="'+items[i].id+'" style="width:100%;display:block;" class="'+($A(items[i].classNames()).join(' '))+'" '+(have_sub?'have_sub="1"':'')+' item="'+items[i].readAttribute('item')+'" parent="'+items[i].readAttribute('parent')+'" href="'+items[i]+'">'+items[i].innerHTML+(have_sub?' ':'')+'</a>'));

			}
			if (items.length>1 && this.options.admin){
				var tr = $(this.table).insertRow(-1);
				var td = tr.insertCell(-1);
				$(td).writeAttribute('colspan',2).setStyle({'border-top':'1px solid black !important'});
				var a = new Element('a',{'href':'#'}).update(this.options.sort_branch+'&#9650; &#9660;');
				$(td).appendChild(a);
				$(a).observe('click',function(event){
					var par = $(items[0]).readAttribute('parent');
					var lang = this.options.lang;
					Modalbox.show('/ajax.php?act=docs&mode=sort_branch&branch='+par+'&le='+lang);
					Event.stop(event);
				}.bind(this));
			}

			if (this.iframe) $(this.iframe).absolutize();
			$(this.table).absolutize();
			if (this.iframe) $(this.iframe).setStyle({'z-index':'-100'});
			

			$(this.table).observe('mouseover',function(event){
				this.show = true;
				var elm = Event.element(event);
				if (elm.tagName.toLowerCase()=='td') $(elm).addClassName('hilite');
				else if(elm.tagName.toLowerCase()=='a'){
					$(elm.up()).addClassName('hilite');
					if (elm.readAttribute('have_sub') && !elm.readAttribute('loaded')){
						$(elm).writeAttribute('loaded',1);
						var opts = Object.extend(this.options, {control : elm,delay : this.options.delay/2} || {});
						this.children[this.children.length] = new TSMenu(opts);
						this.children[this.children.length-1]._draw_first(elm);
					}
				}
			}.bind(this));

			$(this.table).observe('mouseout',function(event){
				this.show = false;
				var elm = Event.element(event);
				if (elm.tagName.toLowerCase()=='td') $(elm).removeClassName('hilite');
				else if(elm.tagName.toLowerCase()=='a') $(elm.up()).removeClassName('hilite');
			}.bind(this));
		}else{
			this.table.show();
			if (this.iframe){
				this.iframe.show();
				Position.clone(this.table,this.iframe);
			}
		}
		//var pos = Prototype.Browser['IE']?$(elm).cumulativeOffset():$(elm).cumulativeOffset();
		Position.prepare();
		var pos = Position.cumulativeOffset(elm);
		//alert(pos);
		var dim = $(elm).getDimensions();
		if ($(elm).hasClassName('menu_link')){
			var position = {'left':parseInt(pos[0]),'top':parseInt(pos[1]+dim.height)};
		}else{
			//alert(dim.width+'+'+pos[0]+'='+(dim.width+pos[0]));
			var dim = $(elm).up().getDimensions();
			var pos2 = Position.cumulativeOffset($(elm).up(1));
			//alert(pos2);
			if (Prototype.Browser['IE']){
				var position = {'left':parseInt(dim.width+pos[0]-pos2[0])+'px','top':parseInt(pos[1]-pos2[1])+'px'};
			}else{
				var position = {'left':parseInt(dim.width+pos[0])+'px','top':parseInt(pos[1])+'px'};
			}
		}
		
		$(this.table).setStyle(position);
		if(this.iframe) Position.clone(this.table,this.iframe);
	},
	_extract_id : function(elm){
		var classes = $A($(elm).classNames());
		var ret = [];
		for(i=0,n=classes.length;i<n;i++){
			if (/(.*?)\-(\d+)/.test(classes[i])){
				t = classes[i].split('-');
				ret[t[0]] = t[1];
			}
		}
		return ret;
	},


	showFlash: function(){
		this.is_flash = true;
		var flashObjects = document.getElementsByTagName("object");
		for (i = 0; i < flashObjects.length; i++) {
			flashObjects[i].style.visibility = "visible";
		}
		var flashEmbeds = document.getElementsByTagName("embed");
		for (i = 0; i < flashEmbeds.length; i++) {
			flashEmbeds[i].style.visibility = "visible";
		}
		if (elm = $('inner_top_1')) $(elm).show();
	},

	hideFlash: function(){
		this.is_flash = false;
		if (elm = $('inner_top_1')) $(elm).hide();
		var flashObjects = document.getElementsByTagName("object");
		for (i = 0; i < flashObjects.length; i++) {
			flashObjects[i].style.visibility = "hidden";
		}
		var flashEmbeds = document.getElementsByTagName("embed");
		for (i = 0; i < flashEmbeds.length; i++) {
			flashEmbeds[i].style.visibility = "hidden";
		}
	},

	_hide : function(elm){
		this.hidden = true;
		if (this.table) this.table.hide();
		if (this.iframe) this.iframe.hide();
		var k = true;
		//console.dir((document.getElementsByClassName('menu_table')));
		$A(document.getElementsByClassName('menu_table')).each(function(elm){if ($(elm).visible()) k=false;});
		if (k && !this.is_flash) this.showFlash();
	}

});