var activityShareClass = Class.create({
	initialize: function(config) {
		this.config = Object.extend({
			'shareBoxTools': $('shareBoxTools'),
			'shareBoxTextarea': $('shareBoxTextarea'),
			'shareBut': $('share_button'),
			'form': $('shareBoxForm'),
			'busyContainer': $('processmessage'),
			'shareButton': $('submit_button'),
			'backButton': $('back_button'),
			'shareLinkButton': $('share-link-button'),
			'shareExternalVideoButton': $('shareExternalVideoSearch'),
			'shareExternalVideoDivAdder': $('shareBoxVideo').down('#shareBoxVideoDivAdder'),
			'shareLinkDivAdder': $('shareBoxLink').down('#shareBoxLinkDivAdder'),
			'shareExternalVideoDiv': $('shareBoxVideoDivAdder'),
			'linkC': $('link-container'),
			'videoC': $('extVideosContainer'),
			'iframe': $('uploadIframe'),
            'iiframe': $('instantIframe'),
			'dummyDiv': $('dummy-div'),
			'dummyLoading': $('dummy-loading-old'),
			'activityList': 'activity-list',
			'textCommandsErrors': $('error-messages-container'),
			'charsLimitContainer': $('activity-chars-limit'),
			'sbOrkutPost':$('sbOrkutPost'),
			'toolId': {
				'video': $('shareBoxVideo'),
				'photo': $('shareBoxPhoto'),
				'link': $('shareBoxLink')
			},
			'linkId': {
				'video': $('video-tool'),
				'photo': $('photo-tool'),
				'link': $('link-tool')
			},
			'inputId': {
				'video': $('shareBoxVideoInput'),
				'video_id': $('sbVideoId'),
                'video_name': $('sbVideoName'),
				'photo': $('shareBoxPhotoInput'),
                'photo_id': $('sbPhotoId'),
                'photo_name': $('sbPhotoName'),
				'link': $('shareBoxLinkInput'),
				'extvideo': $('shareExtVideo')
			}
		}, config);
	this.activeBoxId = null;
	this.charsLimitReached = false;
	this.inputHasBeenCleared = 0;
	this.isYouTubeQSearch = false;
	},
	
	isBusy: function() {
		return this.config.busyContainer.visible();
	},
	
	showShareBoxTools: function() {
		if (! this.isBusy() && ! this.config.shareBoxTools.visible()) {
			new Effect.BlindDown(this.config.shareBoxTools);
		}
	},
	
	hideShareBoxTools: function() {
		if (this.config.shareBoxTools.visible()) {
			new Effect.BlindUp(this.config.shareBoxTools);
		}
	},
	
	hardReset: function(noArea) {
//		window.console.log('hardReset');
		if (activityShare.disableAutohideTools == undefined) {
			this.hideShareBoxTools();
		}
		this.toolsToEssentials();
		with (this.config.shareBoxTextarea) {
			this.followCharsLimit();
			if (! noArea) {
				fire('text-command:test');
				clear();
				this.followCharsLimit();
			}
			if (getValue().strip().blank()) {
				setStyle({'height':'22px'});
			}
		}
		if (this.config.shareBut.getStyle('display') == 'block'){
			new Effect.Fade(this.config.shareBut);
		}
	},
	
	toolsToEssentials: function() {
		function c() {
			//чистим Share-инпуты
			this.config.form.select('input[type=text]', 'input[type=file]').invoke('clear');
			//this.config.form.select('input[id^="share"]').invoke('clear');
			//показать спрятанный input
			this.config.inputId.link.show();
			// показать спряттаный shareBoxVideo div.adder
			this.config.shareExternalVideoDivAdder.show();
			this.config.shareExternalVideoButton.show();
			this.config.shareExternalVideoDiv.show();
			//очистить контейнер с результатами, спрятать
			this.config.linkC.update(null).hide();
			this.config.videoC.update(null).hide();
			this.config.shareLinkButton.show();
			this.config.shareLinkDivAdder.show();
			this.cancelInstantUpload()
		};
		if (this.activeBoxId) {
			this.hideToolBox(this.activeBoxId, {
				afterFinish: function() {
					c.call(this);
				}.bind(this)
			});
			this.highLightTool(this.activeBoxId);
			this.activeBoxId = null;
		}
		else {
			c.call(this);
		}
		
	},
	
	showToolBox: function(boxId) {
		new Effect.Appear(this.config.toolId[boxId]);
		new Effect.Appear(this.config.shareBut);
	},
	
	hideToolBox: function(boxId, o) {
		new Effect.Fade(this.config.toolId[boxId], o);
		new Effect.Fade(this.config.shareBut);

	},
	
	onToolBoxClick: function(boxId) {
		if (this.isBusy()) {
			return false;
		}
		if (this.activeBoxId == boxId) {
			this.toolsToEssentials();
			return true;
		}
		this.toolsToEssentials();
		this.highLightTool(boxId);
		this.showToolBox(this.activeBoxId = boxId);
	},
	
	highLightTool: function(boxId) {
		var tool = $(this.config.linkId[boxId]);
		if (tool.hasClassName('on')) {
			tool.removeClassName('on');
		}
		else {
			tool.addClassName('on');
		}
	},
	
	showBusyMessage: function(text) {
		this.config.busyContainer.update(text || 'Processing...');
		this._fade(this.config.shareButton);
		this._appear(this.config.busyContainer);
	},
	
	hideBusyMessage: function(text) {
		this._appear(this.config.shareButton);
		this._fade(this.config.busyContainer);
	},
	
	showTextCommandError: function(message) {
		var e = this.config.textCommandsErrors;
		e.update(message).show();
		Element.hide.delay(3, e);
	},
	
	
	attachRemoteLink: function() {
		if (this.isBusy()) {
			return false;
		}
        if ($F(this.config.inputId.link).match(/http:\/\/(www\.)?youtube.com\/watch\?v=([a-z0-9])/gi)) {
            val = $F(this.config.inputId.link);
			this.onToolBoxClick('video')
			this.config.inputId.extvideo.value = val
            this.searchExternalVideo();
            //this.config.inputId.link.value = '';
            return false;

             //http://www.youtube.com/watch?v=XxyF33W5RjY&feature=popular
        }
		new Ajax.Request(activityShare.linkShareLink, {
			method: 'post',
			evalScripts: true,
			parameters: {
				link: $F(this.config.inputId.link)
			},
			onCreate: function() {
				this.showBusyMessage('Contacting site...');
				new Effect.BlindUp(this.config.shareLinkDivAdder, {
					afterFinish: function() {
						this.config.shareLinkButton
					}.bind(this)
				});
			}.bind(this),
			onSuccess: function(r) {
				var r = r.responseText;
				//показываем то что нам вернул пхп-парсер удаленной страницы
				new Effect.BlindDown(this.config.linkC.update(r));
				this.hideBusyMessage();
			}.bind(this)
		});
	},
	
	orkutPost: function() {
		/*tn = ''
		if ($('iPhotoPreview') && $$('#iPhotoPreview img')[0].src != '' && $('iPhotoPreview').visible()) {
			tn = '&tn='+encodeURIComponent($$('#iPhotoPreview img')[0].src)
		}
		if ($('iVideoPreview') && $$('#iVideoPreview img')[0].src != '' && $('iVideoPreview').visible()) {
			tn = '&tn='+encodeURIComponent($$('#iVideoPreview img')[0].src)
		}*/
		//if posting text, just show orkut wnd, else open window with loader
		if (this.activeBoxId != 'photo' && this.activeBoxId !='video' && this.activeBoxId != 'link') {
			//window.open('http://promote.orkut.com/preview?nt=orkut.com&tt='+encodeURIComponent($F('shareBoxTextarea'))+'&du='+encodeURIComponent('http://kigol.com.br/'+activityShare.currentUserLogin)+'&cn='+encodeURIComponent(activityShare.orkutDescription), 'Orkut', 'width=640,height=480')
			
			//return true;
		}
		this.shareOrkutActivity = 1;
		this.orkutWnd = window.open('/activity/orkutLoading', 'Orkut', 'width=640,height=480')
		
	},
	
	shareActivity: function() {
		/**
		 * Так очень плохо. Надо переделать.
		 **/
		if (window.liveSearch != undefined) {
			window.liveSearch.freeze();
		}
		var l = this.isSubmitLegal();
		if (l === true) {
			if ($F('shareBoxTextarea') == $F('defaultShareBoxMessage')) {
				$('shareBoxTextarea').clear();
			}
			if(this.config.sbOrkutPost && this.config.sbOrkutPost.checked) {
				this.orkutPost();
			}
            if (this.iUpload) {
                this.showBusyMessage()
                this.submitQueued = true
                return true;
            }
			with (this) {
				config.form.submit();
				showBusyMessage();
				config.iframe.stopObserving('load', this.onFrameLoad.bind(this)).observe('load', this.onFrameLoad.bind(this));
				hardReset();
                //cancelInstantUpload()
				config.shareBoxTextarea.blur();
			}
            this.cancelInstantUpload()
		}
		else {
			alert(l);
		}
	},
	
	_fade: function(e, o) {
		if (e.visible()) {
			e.hide();//new Effect.Fade(e, o);
		}
	},
	
	_appear: function(e, o) {
		if (! e.visible()) {
			e.show();//new Effect.Appear(e, o);
		}
	},
	
	
	/**
	 * @private
	 * Навесит всяческие онклики на ответ от поиска на удаленном видео
	 */
	_addSearchExternalVideosEvents: function() {
		var v = this.config.videoC;
		// клики по кнопочкам more
		v.select('a[id^="href-extmore"]').each(function(h) {
			h.observe('click', function() {
				if (! this.isBusy()) {
					this.searchExternalVideoMore(h.id.split('-')[2]);
				}
			}.bind(this));
		}.bind(this));
        this.config.backButton.observe('click', function() {
			if (!this.isYouTubeQSearch) {
				this.searchExternalVideo();
			} else {
				this.onToolBoxClick('video')
				this.isYouTubeQSearch = false
			}
            this.config.backButton.stopObserving('click');
            this.config.backButton.hide();
        }.bind(this));
		// клики по кнопочке back
		v.select('a[id^="href-extback"]').each(function(h) {
			h.observe('click', function() {
				if (! this.isBusy()) {
					this.searchExternalVideo();
				}
			}.bind(this));
		}.bind(this));
		// клики по превьюшкам
        if (v.select('a[id^="href-thumb"]').length == 1) {
            var s = v.select('a[id^="href-thumb"]')[0].next('span.info');
            this.externalVideoClicked(
                s.down('.dbid').innerHTML,
                s.down('.type').innerHTML,
                s.down('.desc').innerHTML,
                s.down('.title').innerHTML
            );
            return false;
        } else {
            v.select('a[id^="href-thumb"]').each(function(h) {
                h.observe('click', function() {
                    if (! this.isBusy()) {
                        var s = h.next('span.info');
                        this.externalVideoClicked(
                            s.down('.dbid').innerHTML,
                            s.down('.type').innerHTML,
                            s.down('.desc').innerHTML,
                            s.down('.title').innerHTML
                        );
                    }
                }.bind(this));
            }.bind(this))
            return true;
        }
	},
	
	externalVideoClicked: function (id, type, description, title) {
		var v = this.config.videoC;
		new Ajax.Request(activityShare.linkExternaVideoShare, {
			method: 'post',
			parameters: {
				'img-src': $(id + '_' + type).src,
				'title': title,
				'code': description
			},
			onCreate: function() {
				this.showBusyMessage('Please, wait ...');
				new Effect.BlindUp(v);
			}.bind(this),
			onComplete: function() {
				this.hideBusyMessage();
			}.bind(this),
			onSuccess: function(r) {
				new Effect.BlindDown(v.update(r.responseText));
                this.config.backButton.show();
			}.bind(this)
		});
	},
	
	searchExternalVideoMore: function(site) {
		new Ajax.Request(activityShare.linkExternaVideoSearch, {
			method: 'post',
			parameters: {
				'search': this.config.inputId.extvideo.getValue(),
				'shareMore': 1,
				'site': site
			},
			onCreate: function() {
				this.showBusyMessage('Getting more videos ...');
				new Effect.BlindUp(this.config.videoC);
			}.bind(this),
			onComplete: function() {
				this.hideBusyMessage();
			}.bind(this),
			onSuccess: function(r) {
				var v = this.config.videoC.update(r.responseText);
				this._addSearchExternalVideosEvents();
				new Effect.BlindDown(v);
			}.bind(this)
		});
	},
	
	searchExternalVideo: function() {
        query = this.config.inputId.extvideo.getValue();
        site = '';
        if (query.match(/http:\/\/(www\.)?youtube.com\/watch\?v=([a-z0-9])/gi)) { //http://www.youtube.com/watch?v=VQDsoYme3Ls&feature=featured
            qq = query.slice(query.indexOf('?')+1)
            if (qq.indexOf('&')>=0) {
                parts = qq.split('&')
            } else {
                parts = [qq]
            }
            for (i = 0; i < parts.length; i++) {
                if ('v=' == parts[i].slice(0,2)) {
                    query = parts[i].slice(2);
                    site = 'youtube';
					this.isYouTubeQSearch = true
                }
            }
        }
		new Ajax.Request(activityShare.linkExternaVideoSearch, {
			method: 'post',
			parameters: {
				'search': query,//this.config.inputId.extvideo.getValue(),
				'shareForm': 1,
                'site': site
			},
			onCreate: function() {
				this.showBusyMessage('Searching for videos...');
				new Effect.BlindUp(this.config.toolId.video, {
					afterFinish: function() {
						this.config.videoC.hide();
						this.config.shareExternalVideoButton.hide();
						this.config.shareExternalVideoDivAdder.hide();
						this.config.shareExternalVideoDiv.hide();
					}.bind(this)
				});
			}.bind(this),
			onComplete: function() {
				this.config.shareExternalVideoButton.show();
				this.hideBusyMessage();
			}.bind(this),
			onSuccess: function(r) {
				r = r.responseText;
				var v = this.config.videoC.update(r);
				show = this._addSearchExternalVideosEvents();
                if (show) {
                    new Effect.BlindDown(this.config.toolId.video, {
                        afterFinish: function() {
                            v.show();
                        }.bind(this)
                    });
                } else {
                    this.config.toolId.video.show();
                }
			}.bind(this)
		});
	},
	
	onFrameLoad: function() {
		var idActivity = activityQ.pop(), self = this;
		/**
		 * Так очень плохо. Надо переделать.
		 **/
		if (window.liveSearch != undefined) {
			window.liveSearch.exclude(idActivity);
			window.liveSearch.unfreeze();
		}
		// возможно были ошибки во время выполнения текстовых комманд
		if (textCommandErrors.values().length > 0) {
			var e = new String();
			textCommandErrors.each(function(pair) {
				//window.console.log([pair.key, textCommandErrors.unset(pair.key)]);
				e += pair.key + ': ' + textCommandErrors.unset(pair.key) + '<br />';
			});
			self.showTextCommandError(e);
			this.hideBusyMessage();
		}
		
		if (typeof idActivity == 'undefined') {
			this.hideBusyMessage();
			return false;
		}
		
		if (shareQ.length > 0) {
			var idMedia = shareQ.pop();
			uQ[idMedia] = new Ajax.PeriodicalUpdater(false,
				activityShare.linkShare, {
				method: 'post',
				decay: 1.2,
				frequency: 2,
				parameters: {
					id_activity: idActivity,
					id_media: idMedia
				},
				onSuccess: function(r) {
					var r = r.responseText.strip();
					if (r.indexOf('transcoded') != -1) {
						uQ[idMedia].stop();
						self.internalUpdate({
							idActivity: idActivity,
							idMedia: idMedia,
							hasMedia: true
						});
					}
					else if (r.empty()) {
						if (Object.isUndefined(uQ[idMedia]._updated)) {
							self.internalUpdate({
								idActivity: idActivity,
								hasMedia: true
							});
							uQ[idMedia]._updated = 1;
						}
					}
					else if (! r.empty()) {
						// что-то пошло не так, показываем текст ошибки
						uQ[idMedia].stop();
						self.hideBusyMessage();
						alert(r);
					}
				}
			});
		}
		else {
			// грузим сообщение без media
			self.internalUpdate({
				idActivity: idActivity,
				hasMedia: false
			});
		}
	},
	
	internalUpdate: function(O) {
		var self = this;
		new Ajax.Request(activityShare.linkUpdate, {
			method: 'post',
			parameters: O,
			evalScripts: true,
			onSuccess: function(r) {
				if ($$('div #no_activity_message').length > 0) {
					$$('div #no_activity_message').each(function(el){el.remove();});
				}				
				var dummyDiv = new Element('div');
				// помещаем ответ в скрытый div
				dummyDiv.update(r.responseText); // <---- это и будет HTML с блоком для отображения

				// activity div который необходимо поместить в нужное место и отобразить
				var rD = $(dummyDiv.down('div').cloneNode(true)).hide();
				
				var appendAfter = null;

				if (! Object.isUndefined(O.idMedia)) {
					// запросить и отобразить новый контент. Медиа уже закодировалось
					// старому содержимому сделать blindUp или в таком духе
					var activityList = $(self.config.activityList);
					var rO = activityList.down('#activity_' + O.idActivity);
					if (rO) {
						appendAfter = rO.previous('.activity_item');
						new Effect.Fade(rO, {
							afterFinish: function() {
								rO.remove();
							}
						});
					}
				}

				function blindRd() {
					// ф-ция лежит в activityCommentor.js
					
					appendActivity(rD, function() {
						self.hideBusyMessage();
						//Element.remove(dummyDiv);
						dummyDiv = null;
					}, appendAfter);
				}

				// анализируем входящие параметры, чтобы определить поведение:
				if (O.hasMedia) {
					if (Object.isUndefined(O.idMedia)) {
						// чистка ответа:
						//var root = rD.getElementsByClassName('wrap')[0]; // safari fix, because of Element.select bug
						var actType = ''
						var root = rD.down('.wrap');
						if (!root.select('img[id=\'act_ext_img_'+O.idActivity+'\']')) {
							// в случае если закачивается видео
							root.select('*[id^="actvi"]').each(function(el) {el.remove()});

							// если изображение
							root.select('a img').each(function(img) {img.remove()});

							// букмарка
							root.select('.bokmark_activity').each(function(el) {el.remove()});
						} else {
							//console.log('has ext media')
							//console.log(root.select('img[id=\'act_img_loader_'+O.idActivity+'\']'))
							//root.select('img[id=\'act_img_loader_'+O.idActivity+'\']')[0].remove()
							root.select('img[id=\'act_img_'+O.idActivity+'\']')[0].src = root.select('img[id=\'act_ext_img_'+O.idActivity+'\']')[0].src+'?i='+Math.random();
						}
						// вставим текст Loading рядом с изображением
						Element.insert(rD.getElementsByClassName('like_comment')[0], {
						//Element.insert(rD.down('#like_comment'), {
							before: self.config.dummyLoading.innerHTML
						});
						
						blindRd();
						//console.log($('act_img_loader_'+O.idActivity))
						return true;
					} 
					
					// prevent image caching
					/*rD.getElementsByClassName('wrap')[0].select('a img').each(function(img) {
						img.src += ('?' + (Math.random()*100).toString().truncate(5, ''))
					});*/
				}
				
				// плавно показываем наш контент
				blindRd();
				try {
					if (self.shareOrkutActivity == 1) {
						window.shareOrkut(O.idActivity, activityShare.currentUserLogin, null, null, self.orkutWnd)
						self.shareOrkutActivity = 0;
					}
				} catch (e) {
					if (self.orkutWnd) {
						self.orkutWnd.close()
					}
				}
			}
		});
	},
	
	isSubmitLegal: function() {
		this.followCharsLimit();
		if (this.charsLimitReached) {
			return 'Your text is too long.';
		}
		if ($F('shareBoxTextarea') && $F('shareBoxTextarea') != $F('defaultShareBoxMessage')) {
			return true;
		}
		switch (this.activeBoxId) {
			case 'link':
				// наличие зафетченной ссылки
				if ($('link-url') && $F('link-url')) {
					return true;
				}
				break;
				
			case 'photo':
				// наличие выбранного фото
				if ($F(this.config.inputId['photo']) || $F(this.config.inputId['photo_id'])) {
					return true;
				}
				break;
			
			case 'video':
				// наличие выбранного в стандартном инпуте видео
				if ($F(this.config.inputId['video'])) {
					return true;
				}
				// либо наличие сфетченного видео
				if ($('share-ext-video-code') && $F('share-ext-video-code')) {
					return true;
				}
				break;
		}
		return 'Write something first!';
	},

    fileInstantUpload: function() {
      var i = 0;
      if (this.activeBoxId == 'photo') {
          i = this.config.inputId['photo']
      } else if (this.activeBoxId == 'video') {
          i = this.config.inputId['video']
      }

      if (i && $F(i)) {
          
          this.iUpload = this.activeBoxId

          $(this.config['iiframe']).observe('load', this.oniLoad.bind(this))
		  $$('#shareBoxTools a.iUploadCancelLnk').each(function(e){e.observe('click', this.cancelInstantUpload.bind(this))}.bind(this))

          oldAction = this.config['form'].action
          oldTarget = this.config['form'].target
          this.config['form'].action = '/file/store'
          this.config['form'].target = 'instantIframe'
          this.config['form'].submit()
          this.config['form'].action = oldAction
          this.config['form'].target = oldTarget
          i.style.display = 'none'

          $('iUploadReplacer'+this.iUpload).show();
          $('iUploadIndicator'+this.iUpload).show()
      }
    },

    oniLoad: function () {
        //console.log('iload')
		j = this.iUpload
		if (!j) return true
        iDoc = (this.config['iiframe'].contentWindow || this.config['iiframe'].contentDocument)
		if (iDoc.document) iDoc = iDoc.document
		data = iDoc.body.innerHTML
        //$('iUploadIndicator'+j).hide()
        eval('data='+data)
		if (data[j] == 'error') {
			$('iUploadFileName'+j).update('Error');
			//return false
			this.submitQueued = false;
			$('iUploadIndicator'+j).hide()
			this.config.inputId[j].value = '';
		} else {
        	this.config.inputId[j+'_id'].value = data[j]['id']
        	this.config.inputId[j+'_name'].value = data[j]['name']
			this.periodical = new PeriodicalExecuter(this.checkFileStatus.bind(this), 2)
        	$('iUploadFileName'+j).update(data[j]['name'])
			this.config.inputId[j].value = '';
			if (this.submitQueued) {
	              this.config.shareButton.fire('share:submit');
				  this.submitQueued = false;
	        }
        }
		this.iUpload = ''
		this.config['iiframe'].stopObserving('load', this.oniLoad.bind(this))
    },

	checkFileStatus: function() {
		//console.log(this)
		j = this.activeBoxId
		id = this.config.inputId[j+'_id'].value
		new Ajax.Request('/file/checkStatus', {
			parameters: 'id='+id,
			onSuccess: function(t) {
				if (t.responseText != 'error' && t.responseText != 'transcoding') {
					//console.log(j)
					$('iUploadIndicator'+j).hide()
					if (j == 'photo') {
						$$('#iPhotoPreview img').each(function(e){e.src = t.responseText});
						$('iPhotoPreview').show();
					} else {
						$$('#iVideoPreview img').each(function(e){e.src = t.responseText});
						$('iVideoPreview').show();
					}
				}
				if (t.responseText != 'transcoding') {
					this.periodical.stop()
				}
			}.bind(this)
		})
	},

    cancelInstantUpload: function () {
    	try {
        $('iUploadReplacerphoto').hide()
        $('iUploadReplacervideo').hide()
		if (this.periodical) this.periodical.stop()
        this.config.inputId['photo_id'].value = ''
        this.config.inputId['photo_name'].value = ''
        this.config.inputId['video_id'].value = ''
        this.config.inputId['video_name'].value = ''
        this.config.inputId['photo'].show()
        this.config.inputId['video'].show()
        $('iUploadFileNamephoto').update('')
        $('iUploadFileNamevideo').update('')
        $('iUploadIndicatorphoto').show()
        $('iUploadIndicatorvideo').show()
		$('iPhotoPreview').hide()
		$$('#iPhotoPreview img').each(function(e){e.src=''})
		$('iVideoPreview').hide()
		$$('#iVideoPreview img').each(function(e){e.src=''})
        //this.config['iiframe'].contentWindow.stop()
		this.config['iiframe'].stopObserving('load', this.oniLoad.bind(this))
		iDoc = (this.config['iiframe'].contentWindow || this.config['iiframe'].contentDocument)
		if (iDoc.window) iDoc = iDoc.window
		//console.log(iDoc)
		if (iDoc.stop) {
			iDoc.stop()
		} else {
			iDoc.execCommand('stop') //as alternative iDoc.location = 'about:blank'
		}
		$$('#shareBoxTools a.iUploadCancelLnk').each(function(e){e.stopObserving('click', this.cancelInstantUpload.bind(this))}.bind(this))
        this.iUpload = ''
    	}
    	catch (e) {}
    },
	
	followCharsLimit: function() {
		var c = this.config.charsLimitContainer;
		if (! c) {
			return false;
		}
		if (! this.inputHasBeenCleared) {
			return false;
		}
		if (typeof this.charsLimit == 'undefined') {
			this.charsLimit = parseInt(c.innerHTML);
			this._charsCountListener = function() {
				updateCounter.call(this);
				count.call(this);
				checkYouTube.call(this)
			}.bind(this);
		}
		function count() {
 			var count = this.config.shareBoxTextarea.getValue().length;
			if (count > this.charsLimit) {
				 c.addClassName('error');
				 this.charsLimitReached = 1;
			}
			else if (c.hasClassName('error')) {
				c.removeClassName('error');
				this.charsLimitReached = 0;
			}
			return count;
		}
		function updateCounter() {
			with (this.config) {
				var c = count.call(this);
				with (charsLimitContainer) {
					update(this.charsLimit - c);
					//window.console.log([this.charsLimit - c, c])
					if (c > 0) {
						if (! visible()) new Effect.Appear(charsLimitContainer); 
					}
					else /*if (visible())*/ {
						new Effect.Fade(charsLimitContainer);
					}
				}
			}
		}
		updateCounter.call(this);

		function checkYouTube() {
			if (!this.activeBoxId && this.config.shareBoxTextarea.getValue().match(/(http:\/\/)?(www\.)?youtube.com\/watch\?v=([a-z0-9])/gi)) {
				//cut off any text before link
				//res = this.config.shareBoxTextarea.getValue().substring(this.config.shareBoxTextarea.getValue().indexOf('http://www.youtube.com/watch')+1)
				re = /(http:\/\/)?(www\.)?youtube.com\/watch\?v=([a-z0-9]+)/gi
				sub = re.exec(this.config.shareBoxTextarea.getValue())
				if (sub) {
					this.onToolBoxClick('video')
					this.config.inputId.extvideo.value = sub[0]
					this.searchExternalVideo();
				}
			}
		}
		checkYouTube.call(this)
		with (this.config.shareBoxTextarea) {
			// обновляем счетчик			
			stopObserving('keyup', this._charsCountListener);
			observe('keyup', this._charsCountListener);
		}
	},

	tubeInstantSearch: function() {
		if (this.activeBoxId == 'link' && $F(this.config.inputId['link']).match(/http:\/\/(www\.)?youtube.com\/watch\?v=([a-z0-9])/gi)) {
			this.attachRemoteLink()
		} else if (this.activeBoxId == 'video' && $F(this.config.inputId['extvideo']).match(/http:\/\/(www\.)?youtube.com\/watch\?v=([a-z0-9])/gi)) {
			this.searchExternalVideo()
		}
	}
});

Effect.DefaultOptions.duration = 0.2;
Effect.DefaultOptions.queue = "end";

window.shareQ = new Array();
window.shareQH = new Hash(); // хранит связь между idMedia и idActivity
window.activityQ = new Array();
window.uQ = {}; // объект с периодикалами для media
window.textCommandErrors = new Hash(); // объект с сообщениями об ошибках

function initShareBox(isCleared) {
	// в области видимости функции эта переменная глобальна
	var activityShare = new activityShareClass({});

	if(isCleared) {
		activityShare.inputHasBeenCleared = isCleared;
	}
	// текстареа по клику покажет shareBoxTools
	activityShare.config.shareBoxTextarea.observe('click', function(e) {
		with (activityShare) {
			showShareBoxTools();
			if (! inputHasBeenCleared) {
				config.shareBoxTextarea.clear();
				inputHasBeenCleared = 1;
				followCharsLimit();
			}						
			new Effect.Appear(config.shareBut);
		}
		
	});



    //photo file select
    //console.log(activityShare.config.inputId['photo']);
    activityShare.config.inputId['photo'].observe('change', function(){activityShare.fileInstantUpload()})
	activityShare.config.inputId['video'].observe('change', function(){activityShare.fileInstantUpload()})

	activityShare.config.inputId['extvideo'].observe('keyup', function(){activityShare.tubeInstantSearch()})
	activityShare.config.inputId['link'].observe('keyup', function(){activityShare.tubeInstantSearch()})

	// CTRL+ENTER засабмитит форму
	activityShare.config.shareBoxTextarea.observe('keydown', function(e) {
//		window.console.log(e)
		if (e.keyCode == 13 && e.ctrlKey) {
			activityShare.config.shareButton.fire('share:submit');
		}
	});

	// клик по body будет возвращать форму к изначальному состоянию
	Event.observe(document.body, 'click', function() {
		activityShare.hardReset(1);		
	});

	// при этом клик по блоку не должен закрывать нашу форму
	$('sharebox-block').observe('click', function(e) {
		e.stopPropagation();
	});

	// клик по ссылкам Photo Video и т.п. должен вызывать метод onToolBoxClick()
	$$('div.add_block a').each(function(el) {
		var boxId = el.id.split('-').first();
		el.observe('click', function() {
			activityShare.onToolBoxClick(boxId);
		});
	});

	// клики по красненьким изображениям должны закрывать инструменты
	$$('img.closeit').each(function(el) {
		el.observe('click', function() {
			activityShare.toolsToEssentials();
		});
	});

	// пусть линка фетчится по ENTER
	activityShare.config.inputId.link.observe('keydown', function(e) {
		if (e.keyCode == 13) {
			activityShare.config.shareLinkButton.fire('share:click');
		}
	});
	// вешаем кастомное событие на клик
	activityShare.config.shareLinkButton.observe('click', function(e) {
		e.preventDefault();
		Event.element(e).fire('share:click')
	});
	// форме не следует сабмититься без спец. команды
	activityShare.config.form.observe('submit', function(e) {
		e.stop();
		return false;
	});
	// слушаем кастомное событие. Все ради ENTER	
	activityShare.config.shareLinkButton.observe('share:click', function() {
		// TODO: проверку на url
		if ($F(activityShare.config.inputId.link)) {
			activityShare.attachRemoteLink();
		}
	});
	
	activityShare.config.shareButton.observe('click', function() {
		activityShare.config.shareButton.fire('share:submit');
	});

	// обработичк кнопки share	
	activityShare.config.shareButton.observe('share:submit', function() {
		activityShare.shareActivity();
	});
	
	activityShare.config.shareExternalVideoButton.observe('click', function(e) {
		Event.element(e).fire('share-ext:click');
	});
	
	activityShare.config.inputId.extvideo.observe('keydown', function(e) {
		if (e.keyCode == 13) {
			activityShare.config.shareExternalVideoButton.fire('share-ext:click');
		}
	});
	
	// клик по кнопке search для external video
	activityShare.config.shareExternalVideoButton.observe('share-ext:click', function() {
		if (! activityShare.isBusy() && $F(activityShare.config.inputId.extvideo)) {
			activityShare.searchExternalVideo();
		}
	});
	
	// будем учитывать лимит на длину сообщения, если есть такой параметр
	//activityShare.followCharsLimit();
	
}
