/*
* writen by: aa.temkin@gmail.com
* Last mod: 12.09.2008
* Release: 3
*/

	var showFlash = function(){
		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";
	}
	var hideFlash = function(){
		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";
	}

	tsControl.ReferenceObject = Class.create();
	tsControl.ReferenceObject.prototype = Object.extend(tsControl.ReferenceObject,{
		initialize : function(options){
			// basic options eXtend
			this.options = Object.extend({
				target : false, // место куда вставлять элемент
				inner : false, // место, куда передается список выбраных элементов
				selectorOptions : {},
				sysSelectorOptions : {},
				autocreate : true,
				treeOptions : {},
				width : 700,
				height : 300,
				textDelete : 'Удалить',
				textNoTranslate : 'Нет перевода',
				textCode : 'Код :',
				textTitle : 'Название :',
				country : false,
				selectAll : false,
				data : [],
				removeItems : true,
				title : '', // заголовок для окошка
				dataUrl : false, // ссылка от куда сосать
				control : null, // управляющий элемент для всплывающего окошка
				name : 'selector[]', // имена для селектов в окошке (опционально)
				multiple : true, // режим работы: один/много
				input : false, // объект в который будут отдаваться IDшник(и) выбраных элементов
				items : [], // итемы для инициализации (выбранных элементов)
				chooseParent : false,
				clear : false,
				onLoad : Prototype.emptyFunction,
				iframeshim : false,
				hideFlash : false,
				ajax : false
			}, options || {});
			if (this.options.country){
				//this.options.multiple = true;
				this.options.selectAll = true;
			}
			this.items = this.options.items;
			this.target = this.options.target;
			$( this.target ).addClassName( 'loading' );
			
			// fetching component options
			options.treeOptions = this.options.treeOptions = Object.extend({
				//target : this.options.control,
				title : this.options.title,
				multiple : this.options.multiple,
				chooseParent : this.options.chooseParent,
				dataUrl : this.options.dataUrl,
				data : this.options.data,
				input : this.options.input,
				parent : this,
				country : this.options.country,
				selectAll : this.options.selectAll,
				ajax : this.options.ajax,
				onUpdate : function( id, info ){
					//this.Selector.updateItemList( this.Tree.getFullItemsInfo() );
					if (this.sysSelector.target.visible()){
						this.Tree.updateInput();
						this.sysSelector.updateItemList( this.Tree.items );
					}
					if ( this.Tree.items.length>=1 ){
						if ( !this.options.multiple ) this.control_window.close();
					}
				}.bind( this ),
				onLoad : this.options.onLoad
			},this.options.treeOptions || {});
			
			this.options.windowOptions = Object.extend({
				parent : this,
				height : this.options.height,
				width : this.options.width,
				title : this.options.title,
				iframeshim : this.options.iframeshim,
				hideFlash : false
			}, this.options.windowOptions || {});

			this.options.selectorOptions = Object.extend({
				parent : this,
				target : this.options.inner,
				name : this.options.name,
				items : this.items,
				country : this.options.country,
				removeItems : this.options.removeItems,
				multiple : this.options.multiple,
				textDelete : this.options.textDelete,
				textNoTranslate : this.options.textNoTranslate,
				autocreate : this.options.autocreate,
				haveTwins : true
			}, this.options.selectorOptions || {});
			
						
			
			// fetching component options

			// selector window
			var window_header = new Element( 'div', { className: 'window_header' } );
			var window_title = new Element( 'div', { className: 'window_title' } );
			var window_close = new Element( 'div', { className: 'window_close' } );
			var window_contents = new Element( 'div', { className: 'window_contents' } );
			var uid = Math.random();
			var window_inner = new Element( 'div', { className: 'window_contents', id : 'window_'+uid } );
			var tab_panel = new Element( 'div', { className: 'tab_panel_cont' } );
			var search_tab = new Element( 'div', { className: 'window_searchbg' } );
			var clear = new Element( 'div', {className : 'divclear' } );
			
			this.options.sysSelectorOptions = Object.extend({
				target : tab_panel,
				haveTwins : false
			}, this.options.selectorOptions || {});
			this.options.sysSelectorOptions.items = [];
			this.options.sysSelectorOptions.target = tab_panel;
			this.options.sysSelectorOptions.country = false;
			
			window_contents.appendChild( window_inner );
			
			this.control_window = new Control.Window( this.options.control, Object.extend({
				className: 'window',
				closeOnClick: window_close,
				draggable: window_header,
				insertRemoteContentAt: window_inner,
				height: options.height,
				width: options.width,
				beforeClose : function(){
					this.Selector.updateItemList( this.Tree.items );
					this.Tree.close();
					if (options.hideFlash) showFlash();
				},
				afterInitialize : function(){
					var tmp_option = Object.extend({
						target : window_inner,
						controlComponent : this
					},options.treeOptions || {});
					this.Tree = new tsTree(tmp_option);
				},
				beforeOpen : function(){
				},
				afterOpen: function(){
					this.Tree.open();
					window_title.update(options.treeOptions.title);
					if (options.hideFlash) hideFlash();
				}
			},this.options.windowOptions || {}));
			
			this.control_window.container.insert(window_header);
			window_header.insert(window_title);
			window_header.insert(window_close);
			window_header.appendChild( clear );
			
			this.control_window.container.insert( search_tab );
			this.control_window.container.insert( tab_panel );

			var codeSpan = new Element('span').update(this.options.textCode);
			var codeSearch = new Element('input', { 'type':'text' });
			var titleSpan = new Element('span').update(this.options.textTitle);
			var titleSearch = new Element('input', { 'type':'text' });
			search_tab.insert(codeSpan);
			search_tab.insert(codeSearch);
			search_tab.insert(titleSpan);
			search_tab.insert(titleSearch);
			
			this.control_window.container.insert(window_inner);


			// ТУТ ОТКРЫВАЕТСЯ!!!! 
			var chromeIE = false;
			try{
  			if (/Chrome/.test(navigator.userAgent)) chromeIE = true;
  			if ($.Browser.IE || /MSIE/.test(navigator.userAgent)) chromeIE = true;
  		}catch(e){}
			if (!chromeIE){
  			this.control_window.open();
  	  }
			
			this.Tree = this.control_window.Tree;
			
			new tsControl.Autocomplete( codeSearch,{ 'url' : this.options.dataUrl+'&mode=search', Tree : this.Tree } );
			new tsControl.Autocomplete( titleSearch,{ 'url' : this.options.dataUrl+'&mode=searchTitle', Tree : this.Tree } );
			
			this.sysSelector = new tsControl.Selector(this.options.sysSelectorOptions);
			this.Selector = new tsControl.Selector(this.options.selectorOptions);

			/*if (!this.options.multiple || this.options.country){
				tab_panel.hide();
				if (this.options.country) search_tab.hide();
			}*/
			this.Tree.sysSelector = this.sysSelector;
			this.control_window.Selector = this.Selector;
			this.control_window.sysSelector = this.sysSelector;
			
			if (this.options.clear){
				if ($(this.options.clear)){
					$(this.options.clear).observe('click',function(){
						this.Tree.emptyItemList();
						this.Selector.target.update();
						if (this.options.multiple && this.sysSelector) this.sysSelector.target.update();
					}.bind(this));
				}
			}
			/*if (this.options.country){
				
			}*/
								
			if (this.options.country){
				//var info = this.Tree.getFullItemsInfo();
				//this.Selector.updateItemList(info);
			}
			//this.Selector.updateItems(this.Tree.items);
			$(this.target).removeClassName('loading');
		}
	});

