/*

  UNI RA JS Pack

*/

// --------------------------------------------------------------------------------------------------------

// --- strings

function ltrim (s) {
  return s.replace(/^\s+/, '');
}

function rtrim (s) {
  return s.replace(/\s+$/, '');
}

function trim (s) {
  return rtrim(ltrim(s));
}

// ---

var lsBlockLoaderClass = new Class({
                                           
        Implements: Options,

        options: {    
        		classes_nav: {
        				nav: 	 'block-nav',
        				content: 'block-content',
                        active:  'active'                        
                }                           
        },
       
        type: {
                comment_stream: {
                        url: DIR_WEB_ROOT+'/include/ajax/stream_comment.php'                       
                },
                topic_stream: {
                        url: DIR_WEB_ROOT+'/include/ajax/stream_topic.php'                        
                },
                blogs_top: {
                        url: DIR_WEB_ROOT+'/include/ajax/blogs_top.php'                        
                },
                blogs_join: {
                        url: DIR_WEB_ROOT+'/include/ajax/blogs_join.php'                        
                },
                blogs_self: {
                        url: DIR_WEB_ROOT+'/include/ajax/blogs_self.php'                        
                },
                /*
                * Modules "Event" and "Place"
                */
                place_block_PlacesByRating: {
                        url: DIR_WEB_ROOT+'/include/ajax/place_block_places.php?sortby=rating'
                },
                place_block_PlacesByVisitors: {
                        url: DIR_WEB_ROOT+'/include/ajax/place_block_places.php?sortby=visitors'
                },
                /* user tweets */
                tweet_stream: {
                        url: DIR_WEB_ROOT+'/include/ajax/stream_user_tweets.php'
                }
        },

        initialize: function(options){         
                this.setOptions(options);                      
        },
        
        toggle: function(obj,type,params) {
        	if (!this.type[type]) {
            	return false;
            }
            thisObj=this;
            this.obj=$(obj);
            
            var liCurrent=thisObj.obj.getParent('li');
            var blockNav=liCurrent.getParent('ul.'+thisObj.options.classes_nav.nav);
            var liList=blockNav.getChildren('li');
            
            liList.each(function(li,index) {   
            	li.removeClass(thisObj.options.classes_nav.active);        	
        	});
        	
        	liCurrent.addClass(this.options.classes_nav.active);
            
        	var blockContent=blockNav.getParent('div').getChildren('div.'+this.options.classes_nav.content)[0].set('html','');
        	this.showStatus(blockContent);
        	        	
            
            JsHttpRequest.query(
            	this.type[type].url,                       
                params,
                function(result, errors) {     
                	thisObj.onLoad(result, errors, blockContent);                               
                },
                true
            );
            
		},
		
		onLoad: function(result, errors, blockContent) {
			blockContent.set('html','');
			if (!result) {
                msgErrorBox.alert('Error','Сталася помилка. Спробуйте знову');           
        	}
        	if (result.bStateError) {
                //msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        	} else {
        		blockContent.set('html',result.sText);
        	}
		},
		
		showStatus: function(obj) {
			var newDiv = new Element('div');
			newDiv.setStyle('text-align','center');
			newDiv.set('html','<img src="'+DIR_STATIC_SKIN+'/images/loader.gif" >');
			
			newDiv.inject(obj);
		}
});


// --------------------------------------------


function ajaxJoinLeaveBlog (obj,idBlog) {
	obj = $(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/joinLeaveBlog.php',                       
        { idBlog: idBlog },
        function(result, errors) {  
        	if (!result) {
                msgErrorBox.alert('Error', 'Сталася помилка. Спробуйте знову');
        	}
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj) {

            		divMainB = $ ('MainButton_' + idBlog);
            		divEnterOrLeave = $ ('EnterOrLeave_' + idBlog);
            		
            		if (divMainB) divMainB.removeClass ('UserHasJoined');
            		
            		if ((divMainB) && (divEnterOrLeave)) {
                  if (result.bState) {
                    divMainB.addClass ('UserHasJoined');
                    divEnterOrLeave.set ('text', 'Вийти');
                  } else {
                    divEnterOrLeave.set ('text', 'Приєднатися');
                  }
                }
            		
            		divCount = $ ('blog_user_count_' + idBlog);
            		if (divCount) {
            			divCount.set ('text', result.iCountUser);
            		}
            	}
            }
        },
        true
    );
}


function ajaxBlogInfo(idBlog) { 	
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/blogInfo.php',                       
        { idBlog: idBlog },
        function(result, errors) {  
        	if (!result) {
                msgErrorBox.alert('Error','Сталася помилка. Спробуйте знову');           
        	}
            if (result.bStateError) {
            	
            } else {            	
            	if ($('block_blog_info')) {
            		$('block_blog_info').set('html',result.sText);            		
            	}
            }                               
        },
        true
    );
}

// ---------------------------------------------------------------------

var lsCmtTreeClass = new Class({
					   
	Implements: Options,	
	
	options: {
		img: {
			path: 		'images/',			
			openName:  	'open.gif', 
			closeName: 	'close.gif'
		},
		classes: {
			visible: 	'lsCmtTree_visible',
			hidden:  	'lsCmtTree_hidden',			
			openImg:  	'lsCmtTree_open',			
			closeImg:  	'lsCmtTree_close'			
		}		
	},

	initialize: function(options){		
		this.setOptions(options);		
		this.make();		
		this.aCommentNew=[];
		this.iCurrentShowFormComment=0;	
		this.iCommentIdLastView=null;	
		this.countNewComment=0;
		this.docScroller = new Fx.Scroll(document.getDocument());	
		this.hideCommentForm(this.iCurrentShowFormComment);
	},

	make: function(){
		var thisObj = this;
		var aImgFolding=$$('img.folding');
		aImgFolding.each(function(img, i){
			var divComment = img.getParent('div').getChildren('div.comment-children')[0];			
			if (divComment && divComment.getChildren('div.comment')[0]) {
				thisObj.makeImg(img);
			} else {
				img.setStyle('display','none');
			}
		});		
	},
	
	makeImg: function(img) {
		var thisObj = this;
		img.setStyle('cursor', 'pointer');
		img.setStyle('display','inline');
		img.addClass(this.options.classes.closeImg);
		img.removeEvents('click');
		img.addEvent('click',function(){
			thisObj.toggleNode(img);		
		});
	},
	
	toggleNode: function(img) {	
		var b = img.hasClass(this.options.classes.closeImg);		
		if (b) {				
			this.collapseNode(img);
		} else {					
			this.expandNode(img);
		}
	},
	
	expandNode: function(img) {				
		var thisObj = this;
		img.setProperties({'src': this.options.img.path + this.options.img.closeName});
		img.removeClass(this.options.classes.openImg);
		img.addClass(this.options.classes.closeImg);		  
		var divComment = img.getParent('div').getChildren('div.comment-children')[0];		
		
		divComment.removeClass(thisObj.options.classes.hidden);
		divComment.addClass(thisObj.options.classes.visible);		
	},
	
	collapseNode: function(img) {
		var thisObj = this;
		img.setProperties({'src': this.options.img.path + this.options.img.openName});
		img.removeClass(this.options.classes.closeImg);
		img.addClass(this.options.classes.openImg);		    
		var divComment = img.getParent('div').getChildren('div.comment-children')[0];		
		
		divComment.removeClass(thisObj.options.classes.visible);
		divComment.addClass(thisObj.options.classes.hidden);		
	},
	
	expandNodeAll: function() {
		var thisObj = this;
		var aImgFolding=$$('img.'+this.options.classes.openImg);		
		aImgFolding.each(function(img, i){			
			thisObj.expandNode(img);
		});
	},
	
	collapseNodeAll: function() {
		var thisObj = this;
		var aImgFolding=$$('img.'+this.options.classes.closeImg);		
		aImgFolding.each(function(img, i){			
			thisObj.collapseNode(img);
		});
	},
	
	injectComment: function(idCommentParent,idComment,sHtml) {		
		var newComment = new Element('div',{'class':'comment', 'id': 'comment_id_'+idComment});
		newComment.set('html',sHtml);		
		if (idCommentParent) {
			this.expandNodeAll();	
			var divChildren = $('comment-children-'+idCommentParent);		
			var imgParent = divChildren.getParent('div').getChildren('img.folding')[0];		
			this.makeImg(imgParent);
			divChildren.appendChild(newComment);
		} else {
			var divChildren = $('comment-children-0');
			newComment.inject(divChildren,'before');
		}	
	},	
	
	responseNewComment: function(idTopic,objImg,selfIdComment,bNotFlushNew) {
		var thisObj=this;		
		
		if (!bNotFlushNew) {
			var aDivComments=$$('.comment');
			aDivComments.each(function(item,index){
				var divContent=item.getChildren('div.content')[0];
				if (divContent) {
					divContent.removeClass('new');
					divContent.removeClass('view');
				}
			});
		}
		
		var idCommentLast=this.idCommentLast;
		objImg=$(objImg);
		objImg.setProperty('src',DIR_STATIC_SKIN+'/images/update_act.gif');	
		(function(){		
		JsHttpRequest.query(
        	DIR_WEB_ROOT+'/include/ajax/commentResponse.php',
        	{ idCommentLast: idCommentLast, idTopic: idTopic },
        	function(result, errors) {        		
        		objImg.setProperty('src',DIR_STATIC_SKIN+'/images/update.gif'); 
            	if (!result) {
                	msgErrorBox.alert('Error','Please try again later');           
        		}      
        		if (result.bStateError) {
                	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        		} else {   
        			var aCmt=result.aComments;         			
        			if (aCmt.length>0 && result.iMaxIdComment) {
        				thisObj.setIdCommentLast(result.iMaxIdComment);
        				if ($('block_stream_comment') && lsBlockStream) {
        					lsBlockStream.toggle($('block_stream_comment'),'comment_stream');
        				}
        			}        	
        			var iCountOld=0;
        			if (bNotFlushNew) {		      	       			       			
        				iCountOld=thisObj.countNewComment;        				
        			} else {
        				thisObj.aCommentNew=[];
        			}
        			if (selfIdComment) {
        				thisObj.setCountNewComment(aCmt.length-1+iCountOld);
        				thisObj.hideCommentForm(thisObj.iCurrentShowFormComment); 
        			} else {
        				thisObj.setCountNewComment(aCmt.length+iCountOld);
        			}        			
        			aCmt.each(function(item,index) {   
        				if (!(selfIdComment && selfIdComment==item.id)) {
        					thisObj.aCommentNew.extend([item.id]);
        				}        				 				
        				thisObj.injectComment(item.idParent,item.id,item.html);
        			}); 
        			
        			if (selfIdComment && $('comment_id_'+selfIdComment)) {
						thisObj.scrollToComment(selfIdComment);
					}
        		}                           
	        },
        	true
       );
       }).delay(1000);
	},
	
	setIdCommentLast: function(id) {
		this.idCommentLast=id;
	},
	
	setCountNewComment: function(count) {
		this.countNewComment=count;		
		var divCountNew=$('new-comments');
        if (this.countNewComment>0) {
        	divCountNew.set('text',this.countNewComment); 
        	divCountNew.setStyle('display','block');        	
        } else {
        	this.countNewComment=0;
        	divCountNew.set('text',0);         	
        	divCountNew.setStyle('display','none');
        }
	},
	
	goNextComment: function() {		
		if (this.aCommentNew[0]) {
			if ($('comment_id_'+this.aCommentNew[0])) {
				this.scrollToComment(this.aCommentNew[0]);
			}			
			this.aCommentNew.erase(this.aCommentNew[0]);
		}		
		this.setCountNewComment(this.countNewComment-1);
	},
	
	scrollToComment: function(idComment) {
		this.docScroller.setOptions({ 
			duration:500, 
			offset: {
        		'x': 0,
        		'y': 0
   			}
 		}); 		
 		var cmt = $ ('comment_content_id_' + idComment);
 		var deltaY=cmt.getDimensions().height/2-window.getSize().y/2;
 		if (deltaY>0) {
 			deltaY=0;
 		}
		this.docScroller.start(0,cmt.getPosition().y+deltaY);
		if (this.iCommentIdLastView) {
			$ ('comment_text_container_id_' + this.iCommentIdLastView).removeClass ('view');
		}
		$ ('comment_text_container_id_' + idComment).addClass ('view');
		this.iCommentIdLastView = idComment;
	},
	
	addComment: function(formObj,topicId) {
		var thisObj=this;
		formObj=$(formObj);			
		JsHttpRequest.query(
        	DIR_WEB_ROOT+'/include/ajax/commentAdd.php',
        	{ params: formObj },
        	function(result, errors) {         		 
            	if (!result) {
            		thisObj.enableFormComment();
                	msgErrorBox.alert('Error','Please try again later');           
        		}      
        		if (result.bStateError) {        			
					thisObj.enableFormComment();        			
                	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        		} else {       
        			$('form_comment_text').disabled=true; 			
        			thisObj.responseNewComment(topicId,$('update-comments'),result.sCommentId,true);        			   								
        		}                           
	        },
        	true
      	);
      	$('form_comment_text').addClass('loader');		
	},
	
	enableFormComment: function() {
		$('form_comment_text').removeClass('loader');
		$('form_comment_text').disabled=false; 
	},
	
	addCommentScroll: function(commentId) {
		this.aCommentNew.extend([commentId]);
		this.setCountNewComment(this.countNewComment+1);
	},
	
	toggleComment: function(obj,commentId) {
		var divContent=$('comment_content_id_'+commentId);
		if (!divContent) {
			return false;
		}
		
		var thisObj=this;			
		JsHttpRequest.query(
        	DIR_WEB_ROOT+'/include/ajax/commentToggle.php',
        	{ idComment: commentId },
        	function(result, errors) {         		 
            	if (!result) {
                	msgErrorBox.alert('Error','Please try again later');           
        		}      
        		if (result.bStateError) {        			
                	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        		} else {   
        			msgNoticeBox.alert(result.sMsgTitle,result.sMsg);     			
        			divContent.removeClass('old').removeClass('self').removeClass('new').removeClass('del');
        			obj.removeClass('delete').removeClass('repair');
        			if (result.bState) {
        				divContent.addClass('del');
        				obj.addClass('repair');
        			} else {
        				obj.addClass('delete');
        			}
					obj.set('text',result.sTextToggle);        			        								
        		}                           
	        },
        	true
       );
	},
	
	toggleCommentForm: function(idComment) {
		if (!$('reply_'+this.iCurrentShowFormComment) || !$('reply_'+idComment)) {
			return;
		} 
		divCurrentForm=$('reply_'+this.iCurrentShowFormComment);
		divNextForm=$('reply_'+idComment);
				
		var slideCurrentForm = new Fx.Slide(divCurrentForm);
		var slideNextForm = new Fx.Slide(divNextForm);
		
		$('comment_preview_'+this.iCurrentShowFormComment).set('html','').setStyle('display','none');
		if (this.iCurrentShowFormComment==idComment) {
			slideCurrentForm.toggle();
			//$('form_comment_text').focus();
			return;
		}
		
		slideCurrentForm.slideOut();
		divNextForm.set('html',divCurrentForm.get('html'));
		divCurrentForm.set('html','');		
		divNextForm.setStyle('display','block');
		slideNextForm.hide();
		
		slideNextForm.slideIn();
				
		//$('form_comment_text').focus();
		$('form_comment_text').setProperty('value','');
		$('form_comment_reply').setProperty('value',idComment);
		this.iCurrentShowFormComment=idComment;
	},
	
	hideCommentForm: function(idComment) {
		if ($('reply_'+idComment)) {
			this.enableFormComment();
			$('comment_preview_'+this.iCurrentShowFormComment).set('html','').setStyle('display','none');
			var slideForm = new Fx.Slide('reply_'+idComment);							
			slideForm.hide();
		}
	},
	
	preview: function() {
		ajaxTextPreview('form_comment_text',false,'comment_preview_'+this.iCurrentShowFormComment);		
	},
	
	goToParentComment: function(obj) {
		var idCmt = obj.href.substr(obj.href.indexOf('#')+8);
		var objCmtParent=$('comment_id_'+idCmt);
		var objCmt=obj.getParent('div.comment');
		objCmtParent.getElement('.goto-comment-child').removeClass('hidden');
		objCmtParent.getElement('.goto-comment-child a').href = '#comment' + objCmt.id.substr(11);
		this.docScroller.setOptions({ 			
			offset: {'y': 0}
 		});
		this.docScroller.toElement(objCmtParent);
		return false;
	},
	
	goToChildComment: function(obj) {
		var idCmt = obj.href.substr(obj.href.indexOf('#')+8);
		var objCmtChild=$('comment_id_'+idCmt);
		var objCmt=obj.getParent('div.comment');
		objCmt.getElement('.goto-comment-child').addClass('hidden');
		this.docScroller.setOptions({ 			
			offset: {'y': 0}
 		});
		this.docScroller.toElement(objCmtChild);
		return false;
	}
});


var lsCmtTree;
var formCommentSlide;

window.addEvent('domready', function() {
    lsCmtTree = new lsCmtTreeClass({
    	img: {
    		path: DIR_STATIC_SKIN+'/images/'
    	},
    	classes: {
    		openImg: 'folding-open',
    		closeImg: 'folding'
    	}
    });
});


// -------------------------------------------------------------------------


var lsFavourite;

var lsFavouriteClass = new Class({
                                           
        Implements: Options,

        options: {
                classes_action: {                        
                        active:    'active',
                        quest:     'quest'
                },
                classes_element: {
                        favorite:  'favorite'                        
                }              
        },
       
        typeFavourite: {                
                topic: {
                        url: DIR_WEB_ROOT+'/include/ajax/topicFavourite.php',
                        targetName: 'idTopic'
                }
        },

        initialize: function(options){         
                this.setOptions(options);                      
        },
       
        toggle: function(idTarget,objFavourite,type) {          
                if (!this.typeFavourite[type]) {
                        return false;
                }
                               
                this.idTarget=idTarget;
                this.objFavourite=$(objFavourite);
                this.value=value;
                this.type=type;        
                thisObj=this;
                  
                var value=1;      
                if (this.objFavourite.getParent('.'+this.options.classes_element.favorite).hasClass(this.options.classes_action.active)) {
                	value=0;
                } 
                
                var params = new Hash();
                params['type']=value;
                params[this.typeFavourite[type].targetName]=idTarget;
                
                JsHttpRequest.query(
                        this.typeFavourite[type].url,                       
                        params,
                        function(result, errors) {     
                                thisObj.onToggle(result, errors, thisObj);                               
                        },
                        true
                );             
        },
       
        onToggle: function(result, errors, thisObj) {            
        	if (!result) {
                msgErrorBox.alert('Error','Please try again later');           
        	}      
        	if (result.bStateError) {
                msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        	} else {
                msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
               
                var divFavourite=thisObj.objFavourite.getParent('.'+thisObj.options.classes_element.favorite);
                divFavourite.removeClass(thisObj.options.classes_action.active);
                if (result.bState) {
                	divFavourite.addClass(thisObj.options.classes_action.active);
                }
        	}      
        }
       
});

window.addEvent('domready', function() {
      lsFavourite=new lsFavouriteClass();
});


// ---------------------------------------------------------------------


function ajaxToggleUserFrend (obj,idUser) {   
	obj=$(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/userFriend.php',                       
        { idUser: idUser },
        function(result, errors) {  
        	if (!result) {
            msgErrorBox.alert('Error','Please try again later');
        	}
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj) {
            		if (result.bState) {
            			obj.removeClass('add');
            			obj.addClass('del');
            		} else {
            			obj.removeClass('del');
            			obj.addClass('add');
            		}
            	}
            }
        },
        true
    );
}


// ---------------------------------------------------------------



function showLoginForm() {	
	if (Browser.Engine.trident) {
		return true;
	}	
	if (!winFormLogin) {		
		winFormLogin=new StickyWin.Modal({content: $('login-form'), closeClassName: 'close-block', useIframeShim: false});
	}
	winFormLogin.show();
	winFormLogin.pin(true);
	return false;
}

function hideLoginForm() {
	winFormLogin.hide();
}

var winFormLogin=false;


// --------------------------------------------------------------------------


function ajaxTextPreview(textId,save,divPreview) {
	var text;
	if (BLOG_USE_TINYMCE && tinyMCE && (ed=tinyMCE.get(textId))) {
		text = ed.getContent();
	} else {
		text = $(textId).value;
	}
	if (trim (text) == '') {
    text = "Зранку - текст, ввечері - попередній перегляд :)";
	}
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/textPreview.php',                       
        { text: text, save: save },
        function(result, errors) {  
        	if (!result) {
                msgErrorBox.alert('Error','Please try again later');           
        	}
            if (result.bStateError) {
            	msgErrorBox.alert('Error','Please try again later');
            } else {    	
            	if (!divPreview) {
            		divPreview='text_preview';
            	}            	
            	if ($(divPreview)) {
            		$(divPreview).set('html',result.sText).setStyle('display','block');
            	}
            }                               
        },
        true
    );
}


// для опроса
function addField(btn){
        tr = btn;
        while (tr.tagName != 'TR') tr = tr.parentNode;
        var newTr = tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
        checkFieldForLast();
}
function checkFieldForLast(){	
        btns = document.getElementsByName('drop_answer');      
        for (i = 0; i < btns.length; i++){
        	btns[i].disabled = false;            
        }
        if (btns.length<=2) {
        	btns[0].disabled = true;
        	btns[1].disabled = true;
        }
}
function dropField(btn){	
        tr = btn;
        while (tr.tagName != 'TR') tr = tr.parentNode;
        tr.parentNode.removeChild(tr);
        checkFieldForLast();
}



function checkAllTalk(checkbox) {
	$$('.form_talks_checkbox').each(function(chk){
		if (checkbox.checked) {
			chk.checked=true;
		} else {
			chk.checked=false;
		}		
	});	
}


function showImgUploadForm() {	
	if (Browser.Engine.trident) {
		//return true;
	}	
	if (!winFormImgUpload) {		
		winFormImgUpload=new StickyWin.Modal({content: $('window_load_img'), closeClassName: 'close-block', useIframeShim: false});
	}
	winFormImgUpload.show();
	winFormImgUpload.pin(true);
	return false;
}

function hideImgUploadForm() {
	winFormImgUpload.hide();
}

var winFormImgUpload;


function ajaxUploadImg(value,sToLoad) {
	sToLoad=$(sToLoad);
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS.bStateError) {
				msgErrorBox.alert(req.responseJS.sMsgTitle,req.responseJS.sMsg);				
			} else {				
				sToLoad.insertAtCursor(req.responseJS.sText);
				hideImgUploadForm();
			}
		}
	}
	req.open(null, DIR_WEB_ROOT+'/include/ajax/uploadImg.php', true);
	req.send( { value: value } );
}

// --- RA MOD

var winFormHowtoInfo;

function showHowToInfoForm() {
	if (!winFormHowtoInfo) {
		winFormHowtoInfo=new StickyWin.Modal({content: $('window_howto'), closeClassName: 'close-block', useIframeShim: false});
	}
	winFormHowtoInfo.show();
	winFormHowtoInfo.pin(true);
	return false;
}

function hideHowToInfoForm() {
	winFormHowtoInfo.hide();
}

// --- upload mp3 files

var winFormUploadMP3;

function showAddMP3Form () {
	if (!winFormUploadMP3) {
		winFormUploadMP3 = new StickyWin.Modal({content: $('window_uploadmp3'), closeClassName: 'CloseButton', useIframeShim: false});
	}
	winFormUploadMP3.show();
	winFormUploadMP3.pin(true);
	return false;
}

function hideAddMP3Form () {
	winFormUploadMP3.hide();
}


// -------------------------------------------------------------------------------------


var lsPanelClass = new Class({	
	initialize: function(){
		
	},
	
	putText: function(obj,text) {
		obj=$(obj);
		var scrollLeft=obj.scrollLeft;
		var scrollTop=obj.scrollTop;		
		if (Browser.Engine.trident && document.selection) {
			obj.focus();
			sel=document.selection.createRange();
			sel.text=text;
		} else {
			obj.insertAtCursor(text);
		}		
		obj.scrollLeft=scrollLeft;
		obj.scrollTop=scrollTop;
	}, 
	
	putTag: function(obj,tag) {
		this.putText(obj,'<'+tag+'/>');
	},
	
	putTextAround: function(obj,textStart,textEnd) {
		obj=$(obj);
		var scrollLeft=obj.scrollLeft;
		var scrollTop=obj.scrollTop;	
		if (Browser.Engine.trident && document.selection) {
			obj.focus();
			sel=document.selection.createRange();
			sel.text = textStart+sel.text+textEnd;
		} else {
			obj.insertAroundCursor({
				before: textStart,
				defaultMiddle: '',
				after: textEnd
			});
		}
		obj.scrollLeft=scrollLeft;
		obj.scrollTop=scrollTop;
	},
	
	putTagAround: function(obj,tagStart,tagEnd) {
		if (!tagEnd) {
			tagEnd=tagStart;
		}
		this.putTextAround(obj,'<'+tagStart+'>','</'+tagEnd+'>');
	},
	
	putTagUrl: function(obj,sPromt) {
		obj=$(obj);
		if (url=prompt(sPromt,'http://')) {
			var sel=obj.getSelectedText();
        	this.putText(obj,'<a href="'+url+'">'+sel+'</a>');
        }
	},
	
	putQuote: function(obj) {
		obj=$(obj);
		if (selText=this.getSelectedText()) {			
			this.putText(obj,'<blockquote>'+selText+'</blockquote>');
		} else {
			this.putTagAround(obj,'blockquote');
		}
	},
	
	getSelectedText: function(){
		if (Browser.Engine.trident) return document.selection.createRange().text;
		//if (window.khtml) return window.getSelection();
		return document.getSelection();
	}
});

var lsPanel;

window.addEvent('domready', function() {
    lsPanel = new lsPanelClass();
});


// ----------------------------------------------------------------------------


/*
---------------------------------------------------------
*
*	Module "Place"
*	Author: Alexander Zinchuk ( Ajaxy ) 
*	Contact e-mail: hey@ajaxy.ru
*
---------------------------------------------------------
*/

ls_Place = {
  placeId : 0,
  selectedTypes : Array(),
  selectedTypesMaxLength : 0,
  Rating_current : 0,
  Rating_countVote : 0,
  Rating_userIsVote : 0,
  GMapLat : 0.0,
  GMapLng : 0.0,
  catalogueCity : '',
  catalogueType : '',
  catalogueDiv : '',
  catalogueTitleLike : '',
  
  setField : function(fieldName, value) {
    $('place_'+ fieldName).value = value;
  },
  
  create_addType : function(checkbox) {
    if(this.selectedTypesMaxLength == 0) return true;
  
    var type = checkbox.id.substring(checkbox.id.lastIndexOf('_')+1);
    if(this.selectedTypes.contains(type)) {
      this.selectedTypes.erase(type);
    } else if(this.selectedTypes.length < this.selectedTypesMaxLength) {
      this.selectedTypes.push(type);
    }
    checkbox.parentNode.getElements('input[type=checkbox]').each(function(chbox) {
      chbox.disabled = chbox.checked ? false : this.selectedTypes.length >= this.selectedTypesMaxLength;
    }, this);
  },
  
  Rating_move : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    div.firstChild.style.width = ((e.layerX||e.offsetX)/120*100) + '%';
    $('place_rating').innerHTML = parseInt((e.layerX||e.offsetX)*500/120);
  },

  Rating_out : function(e) {
    e = e||window.event;
    var target = e.target||e.srcElement;
    if((target.className && target.className == 'stars')) {
      return false;
    }
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
  },
  
  Rating_click : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    var value = Math.round((e.layerX||e.offsetX)*500/120);
    this.Rating_userIsVote = value;
    return lsVote.vote(this.placeId, div, value, 'place');
  },

  Rating_voted : function(result) {
    this.Rating_current = Math.round(result.iRating);
    this.Rating_countVote = result.iCountVote;
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
    $('place_count_vote').innerHTML = result.iCountVote;
    this.Rating_userIsVote = true;
  },
  
  joinLeave : function(obj,idPlace) {   
	obj=$(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/place_joinLeave.php',                       
        { idPlace: idPlace },
        function(result, errors) {  
        	if (!result) {
            msgErrorBox.alert('Error','Please try again later');           
        	} else {
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj)  {          		
            		if (result.bState) {            			
            			$('place_join_true').style.display = 'none';
            			$('place_join_false').style.display = 'inline';
            		} else {            			
            			$('place_join_true').style.display = 'inline';
            			$('place_join_false').style.display = 'none';
            		}
            		var divCount=$('place_user_count_'+idPlace);
            		if (divCount) {
            			divCount.set('text',result.iCountUser);
            		}
            	}
            }
          }
        },
        true
    );
  },
  
  toggleEdit : function(n, item) {
    var divs = $('place_edit_form').getChildren('div');
    divs.each(function(div) {
      div.setStyle('display', 'none');
    });
    $('placeEdit_div'+n).setStyle('display', 'block');
    var menus = $('place_edit_menu').getChildren('li');
    menus.each(function(div) {
      div.toggleClass('active');
    });
    if(ls_Event && (n == 1 && !ls_Event.GMapsInited)) {
      ls_Event.GMapInit($('gmap_canvas'), this.GMapLat, this.GMapLng, true);
    }
  },
  
  /* Catalogue */
  
  selectCity : function(input) {
    setTimeout(function() {
      if(!input.focused) {
        if(input.value != ls_Place.catalogueCity) {
          ls_Place.catalogueCity = input.value;
          if(!input.value || input.value == '*' || input.value == ls_Place.lang_cities_all) {
            input.value = ls_Place.lang_cities_all;
            ls_Place.catalogueCity = '*';
          }
          ls_Place.loadCatalogue();
        }
        input.removeClass('focused');
      }
    }, 100)
  },
  
  selectType : function(type, bySearchString) {
    types = type.split(',').map(function(v) { return v.trim(); });
    var links = $('place_types').getElements('a');
    links.each(function(link) {
      if(types.contains(link.get('text'))||types.contains(link.get('nativetext'))) {
        link.addClass('active');
      } else {
        link.removeClass('active');
      }
    });
    this.catalogueType = type == this.lang_types_all ? '*' : type;
    if(bySearchString) { // no need to load places if no location.hash params set
      return;
    }
    this.loadCatalogue();
  },
  
  loadCatalogue : function(filters, catalogueDiv) {
    catalogueDiv = $(catalogueDiv||this.catalogueDiv);
    filters = filters||{},
    filters.city = ls_Place.catalogueCity||'*';
    filters.type = ls_Place.catalogueType||'*';
    filters.sortby = ls_Place.catalogueSortBy;
    filters.titlelike = ls_Place.catalogueTitleLike;
    
    var hash = new Hash(filters);
    location.hash = hash.filter(function(v, k){ return v != '*'; }).toQueryString();
    
    catalogueDiv.getChildren()[1].setStyle('display','none');        	
    catalogueDiv.getChildren()[0].setStyle('display','block');        	
    JsHttpRequest.query(
      DIR_WEB_ROOT+'/include/ajax/place_loadCatalogue.php',                       
      filters,
      function(result, errors) {  
        if (!result) {
          msgErrorBox.alert('Error','Please try again later');           
        } else {
          if (result.bStateError) {
            msgErrorBox.alert(result.sMsgTitle,result.sMsg);
          } else {  
            catalogueDiv.getChildren()[0].setStyle('display','none');        	
            catalogueDiv.getChildren()[1].set('html', result.sText);
            catalogueDiv.getChildren()[1].setStyle('display', 'block');
          }
        }
      },
      true
    );
  },
  
  profile_EventsFilter : function(filter) {
    var menus = $('place_events_filter').getChildren('li');
    menus.each(function(div) {
      div.removeClass('active');
    });
    var active = $('place_events_filter').getFirst('li.'+filter)||$('place_events_filter').getFirst('li.all');
    active.addClass('active');
    var dates = ls_Event.parseWordsInDate(filter).split('-');
    var date = dates.map(function(date){ return ls_Event._convertDate(date, true); }).join('~');
    ls_Event.loadBill({place_id:this.placeId, date:date});
  }
 
}


// ------------------------------------------------------------------------------



function ajaxQuestionVote(idTopic,idAnswer) {	
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/questionVote.php',                       
        { idTopic: idTopic, idAnswer: idAnswer },
        function(result, errors) {  
        	if (!result) {
                msgErrorBox.alert('Error','Please try again later');           
        	}
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if ($('topic_question_area_'+idTopic)) {
            		$('topic_question_area_'+idTopic).set('html',result.sText);
            	}  
            }                               
        },
        true
    );	
}


// ----------------------------------------------------------------------------------


var lsVote;

var lsVoteClass = new Class({
                                           
        Implements: Options,

        options: {
                classes_action: {
                        voted:          'voted',                       
                        plus:           'plus',
                        minus:          'minus',
                        positive:       'positive',
                        negative:       'negative',
                        quest:          'quest'
                },
                classes_element: {
                        voting:         'voting',
                        count:          'count',                       
                        total:          'total',                       
                        plus:           'plus',
                        minus:          'minus'
                }              
        },
       
        typeVote: {
                topic_comment: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteComment.php',
                        targetName: 'idComment'
                },
                topic: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteTopic.php',
                        targetName: 'idTopic'
                },
                blog: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteBlog.php',
                        targetName: 'idBlog'
                },
                user: {
                        url: DIR_WEB_ROOT+'/include/ajax/voteUser.php',
                        targetName: 'idUser'
                },
                /**
                 * Modules "Place" and "Event"
                 */
                place: {
                        url: DIR_WEB_ROOT+'/include/ajax/place_vote.php',
                        targetName: 'idPlace'
                },
                event_comment: {
                        url: DIR_WEB_ROOT+'/include/ajax/bill_voteComment.php?act=event',
                        targetName: 'idEvent'
                },
                place_comment: {
                        url: DIR_WEB_ROOT+'/include/ajax/bill_voteComment.php?act=place',
                        targetName: 'idPlace'
                }
        },

        initialize: function(options){         
                this.setOptions(options);                      
        },
       
        vote: function(idTarget,objVote,value,type) {          
                if (!this.typeVote[type]) {
                        return false;
                }
               
                this.idTarget=idTarget;
                this.objVote=$(objVote);
                this.value=value;
                this.type=type;        
                thisObj=this;
                        
                var params = new Hash();
                params['value']=value;
                params[this.typeVote[type].targetName]=idTarget;
                
                JsHttpRequest.query(
                        this.typeVote[type].url,                       
                        params,
                        function(result, errors) {     
                                thisObj.onVote(result, errors, thisObj);                               
                        },
                        true
                );             
        },
       
        onVote: function(result, errors, thisObj) {            
        	if (!result) {
                msgErrorBox.alert('Error','Please try again later');           
        	}      
        	if (result.bStateError) {
                msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        	} else {
                msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
                /**
                 * Hack for module "Place"
                 */
                if(thisObj.type == 'place') {
                  return ls_Place.Rating_voted(result);
                }
                
                var divVoting=thisObj.objVote.getParent('.'+thisObj.options.classes_element.voting);                
                divVoting.addClass(thisObj.options.classes_action.voted);
               
                if (this.value>0) {
                        divVoting.addClass(thisObj.options.classes_action.plus);
                }
                if(this.value<0) {
                        divVoting.addClass(thisObj.options.classes_action.minus);
                }              
                var divCount=divVoting.getChildren('.'+thisObj.options.classes_element.count);
                if (divCount && divCount[0]) {
                	divCount.set('text',result.iCountVote);
                }
               
                var divTotal=divVoting.getChildren('.'+thisObj.options.classes_element.total);              
                result.iRating=parseFloat(result.iRating);  
                divVoting.removeClass(thisObj.options.classes_action.negative);    
                divVoting.removeClass(thisObj.options.classes_action.positive);         
                if (result.iRating>0) {                        
                        divVoting.addClass(thisObj.options.classes_action.positive);
                        divTotal.set('text','+'+result.iRating);
                }
                if (result.iRating<0) {                        
                        divVoting.addClass(thisObj.options.classes_action.negative);
                        divTotal.set('text',result.iRating);
                }
                if (result.iRating==0) {
                        divTotal.set('text','0');
                }
                
                if (thisObj.type=='user' && $('user_skill_'+thisObj.idTarget)) {
                	$('user_skill_'+thisObj.idTarget).set('text',result.iSkill);
                }
        	}      
        }
       
});

window.addEvent('domready', function() {
      lsVote=new lsVoteClass();
});


// --------------------------------------------------------------


/*
---------------------------------------------------------
*
*	Module "Event/Place"
*	Author: Alexander Zinchuk ( Ajaxy ) 
*	Contact e-mail: hey@ajaxy.ru
*
 RA MOD
---------------------------------------------------------
*/

window.addEvent('domready', function() {
  lsCmtTree.responseNewCommentBill = lsCmtTreeBill.responseNewCommentBill;
  lsCmtTree.addCommentBill = lsCmtTreeBill.addCommentBill;
  lsCmtTree.toggleCommentBill = lsCmtTreeBill.toggleCommentBill;
});

lsCmtTreeBill = {

	responseNewCommentBill: function(actId,objImg,selfIdComment,bNotFlushNew) {
		var thisObj=this;		
		
		if (!bNotFlushNew) {
			var aDivComments=$$('.comment');
			aDivComments.each(function(item,index){
				var divContent=item.getChildren('div.content')[0];
				if (divContent) {
					divContent.removeClass('new');
					divContent.removeClass('view');
				}
			});
		}
		
		var idCommentLast=this.idCommentLast;
		objImg=$(objImg);
		objImg.setProperty('src',DIR_STATIC_SKIN+'/images/update_act.gif');	
		(function(){		
		JsHttpRequest.query(
        	DIR_WEB_ROOT+'/include/ajax/bill_commentResponse.php',
        	{ idCommentLast: idCommentLast, act: thisObj.actionType, actId: actId },
        	function(result, errors) {        		
        		objImg.setProperty('src',DIR_STATIC_SKIN+'/images/update.gif'); 
            	if (!result) {
                	msgErrorBox.alert('Error','Please try again later');           
        		}      
        		if (result.bStateError) {
                	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        		} else {   
        			var aCmt=result.aComments;         			
        			if (aCmt.length>0 && result.iMaxIdComment) {
        				thisObj.setIdCommentLast(result.iMaxIdComment);
        				if ($('block_stream_comment') && lsBlockStream) {
        					lsBlockStream.toggle($('block_stream_comment'),'comment_stream');
        				}
        			}        	
        			var iCountOld=0;
        			if (bNotFlushNew) {		      	       			       			
        				iCountOld=thisObj.countNewComment;        				
        			} else {
        				thisObj.aCommentNew=[];
        			}
        			if (selfIdComment) {
        				thisObj.setCountNewComment(aCmt.length-1+iCountOld);
                $('form_comment_text').value = '';
        				thisObj.hideCommentForm(thisObj.iCurrentShowFormComment); 
        			} else {
        				thisObj.setCountNewComment(aCmt.length+iCountOld);
        			}        			
        			aCmt.each(function(item,index) {   
        				if (!(selfIdComment && selfIdComment==item.id)) {
        					thisObj.aCommentNew.extend([item.id]);
        				}        				 				
        				thisObj.injectComment(item.idParent,item.id,item.html);
        			}); 
        			
        			if (selfIdComment && $('comment_id_'+selfIdComment)) {
                thisObj.scrollToComment(selfIdComment);
              }
        		}
	        },
        	true
       );
       }).delay(1000);
	},
  
	addCommentBill: function(formObj,actId) {
		var thisObj=this;
    
      		p = {};
          $(formObj).getElements('*').each(function(s){
            p[s.name] = s.value;
          });
          
		JsHttpRequest.query(
      DIR_WEB_ROOT+'/include/ajax/bill_commentAdd.php',
      (new Hash({ act: thisObj.actionType })).extend(p),
      function(result, errors) {
        if (!result) {
          thisObj.enableFormComment();
          msgErrorBox.alert('Error','Please try again later');   
        }    
        else if (result.bStateError) {
          thisObj.enableFormComment();        			
          msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        } else {       
          $('form_comment_text').disabled=true;
          thisObj.responseNewCommentBill(actId,$('update-comments'),result.sCommentId,true);        			   								
        }                           
      },
      true
    );
    $('form_comment_text').addClass('loader');		
	},
	
	toggleCommentBill: function(obj,commentId) {
		var divContent=$('comment_content_id_'+commentId);
		if (!divContent) {
			return false;
		}
		
		var thisObj=this;			
		JsHttpRequest.query(
        	DIR_WEB_ROOT+'/include/ajax/bill_commentToggle.php',
        	{ idComment: commentId, act: thisObj.actionType },
        	function(result, errors) {         		 
            	if (!result) {
                	msgErrorBox.alert('Error','Please try again later');           
        		}      
        		if (result.bStateError) {        			
                	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
        		} else {   
        			msgNoticeBox.alert(result.sMsgTitle,result.sMsg);     			
        			divContent.removeClass('old').removeClass('self').removeClass('new').removeClass('del');
        			obj.removeClass('delete').removeClass('repair');
        			if (result.bState) {
        				divContent.addClass('del');
        				obj.addClass('repair');
        			} else {
        				obj.addClass('delete');
        			}
              obj.set('text',result.sTextToggle);
        		}                           
	        },
        	true
       );
	}
};


// --------------------------------------------------------------


/*
---------------------------------------------------------
*
*	Module "Event"
*	Author: Alexander Zinchuk ( Ajaxy ) 
*	Contact e-mail: hey@ajaxy.ru
*
---------------------------------------------------------
*/

// Mootools more plugin
String.implement({

	parseQuery: function(){
		var vars = this.split(/[&;]/), res = {};
		if (vars.length) vars.each(function(val){
			var index = val.indexOf('='),
				keys = index < 0 ? [''] : val.substr(0, index).match(/[^\]\[]+/g),
				value = decodeURIComponent(val.substr(index + 1)),
				obj = res;
			keys.each(function(key, i){
				var current = obj[key];
				if(i < keys.length - 1)
					obj = obj[key] = current || {};
				else if($type(current) == 'array')
					current.push(value);
				else
					obj[key] = $defined(current) ? [current, value] : value;
			});
		});
		return res;
	},

	cleanQuery: function(method){
		return this.split('&').filter(function(val){
			var index = val.indexOf('='),
			key = index < 0 ? '' : val.substr(0, index),
			value = val.substr(index + 1);
			return method ? method.run([key, value]) : $chk(value);
		}).join('&');
	}

});


ls_Event = {
  eventId : 0,
  today : '',
  menuAct : 0,
  billDate : '',
  billCity : '',
  billDiv : '',
  billActiveColor : '#99CCEE',
  billRollOverColor : '#CFFF9F',
  billInActiveColor : '#EEEEEE',
  Rating_current : 0,
  Rating_countVote : 0,
  Rating_userIsVote : 0,  
  Respanel_weeksCount : 1,
  Respanel_currentWeek : 0,
  Respanel_weeksOrder : new Array(),
  Respanel_weeksTime : new Array(),
  GMapsInited : false,
  GMapLat : 0.0,
  GMapLng : 0.0,
  
  setField : function(fieldName, value) {
    $('event_'+ fieldName).value = value;
  },
  
  Respanel_init : function(serverTime) {
    this.Respanel_currentTime = serverTime || (new Date()).getTime();
    this.Respanel_weekBox = $$('#event_respanel div.week-box')[0];
    this.Respanel_weeks = $('event_respanel_weeks');
    this.Respanel_weekWidth = this.Respanel_weekBox.offsetWidth;
    this.Respanel_weeks.setStyle('width', this.Respanel_weekWidth);
    var firstWeek = $$('#event_respanel_weeks div.week')[0];
    if(!firstWeek) return alert('Can\'t find week panel.');
    firstWeek.setStyle('width', this.Respanel_weekWidth);
    this.Respanel_weekTpl = firstWeek.innerHTML;
    this.Respanel_weeksOrder.push(1);
    this.Respanel_weeksTime.push(serverTime*1000 - 1000*60*60*24);
  },
  
  Respanel_addWeek : function(destination) {
    var week = "<div class='week' style='width:"+ this.Respanel_weekWidth +"px;' id='event_respanel_week"+ (this.Respanel_weeksCount++) +"'>"+ this.Respanel_weekTpl +"</div>";
    this.Respanel_weeks.setStyle('width', this.Respanel_weekWidth*this.Respanel_weeksCount);
    if(destination == 'next') {
      var time = this.Respanel_weeksTime[this.Respanel_currentWeek] + 1000*60*60*24*7;
      this.Respanel_weeksTime.push(time);
      this.Respanel_weeksOrder.push(this.Respanel_weeksCount);
      // remove div.clearer
      this.Respanel_weeks.removeChild(this.Respanel_weeks.getLast());
      this.Respanel_weeks.innerHTML = this.Respanel_weeks.innerHTML + week + '<div class="clearer">&nbsp;</div>';
    } else {
      var time = this.Respanel_weeksTime[this.Respanel_currentWeek] - 1000*60*60*24*7;
      this.Respanel_weeks.innerHTML = week + this.Respanel_weeks.innerHTML;
      this.Respanel_weeksTime.unshift(time);
      this.Respanel_weeksOrder.unshift(this.Respanel_weeksCount);
      this.Respanel_move_next(true);
    }
    this.Respanel_putDays($('event_respanel_week'+(this.Respanel_weeksCount-1)), time);
  },
  
  Respanel_putDays : function(week, fromTime) {
    week = $(week);
    var time, date, monthDay, month, weekDay, isHoliday;
    var days = week.getElements('div.day');
    var t = this;
    $each(days, function(day, i) {
      day.removeClass('today');
      day.removeClass('holiday');
      day.removeClass('active');
      time = fromTime + 1000*60*60*24*i;
      date = new Date();
      date.setTime(time);
      monthDay = date.getDate();
      if(monthDay < 10) monthDay = '0'+monthDay;
      month = date.getMonth()+1;
      if(month < 10) month = '0'+month;
      weekDay = date.getDay();
      if(weekDay == 0 || weekDay == 6) {// || in_array($iMonthDay.'.'.$iMonth, $LS_EVENT_HOLIDAYS) );
        day.addClass('holiday');
      }
      day.id = 'date_'+ date.getFullYear() +'-'+ month  +'-'+ monthDay;
      day.getElement('a.monthday').innerHTML = monthDay;
      if(date.getMonth() != (new Date()).getMonth()) {
        day.getElement('a.monthday').innerHTML += ('.'+ month);
      }
      day.getElement('a.weekday').innerHTML = ls_Event.Respanel_langWeekDays[weekDay];
    });
  },
  
  Respanel_day_over : function(div) {
    div = $(div);
    if(div.hasClass('active')) return;
    var collection = this.menuAct == 0 ? [div] : $(div.parentNode).getChildren('div.day');
    collection.each(function(day) {
      day.set('morph', {'duration' : 'short'});
      day.morph({backgroundColor: ls_Event.billRollOverColor});
    });
  },
  
  Respanel_day_out : function(div) {
    div = $(div);
    if(div.hasClass('active')) return;
    var collection = this.menuAct == 0 ? [div] : $(div.parentNode).getChildren('div.day');
    collection.each(function(day) {
      day.set('morph', {'duration' : 'short'});
      day.morph({backgroundColor: ls_Event.billInActiveColor});
    });
  },

  Respanel_arrow_over : function(div, fase) {
    (new Fx.Tween($(div))).set('opacity', '1'); 
  },
  
  Respanel_arrow_out : function(div) {
    (new Fx.Tween($(div))).set('opacity', '0.7'); 
  },

  Respanel_move_next : function(fast) {
    fast = fast||false;
    if(this.menuAct == 1) {
      var week = $('event_respanel_week'+(this.Respanel_weeksOrder[this.Respanel_currentWeek]-1));
      var days = week.getChildren();
      days.each(function(s){
        s.removeClass('active');
        s.setStyle('background-color', this.billInActiveColor);
      });
    }
    if(!fast && this.Respanel_currentWeek >= this.Respanel_weeksCount-1) {
      this.Respanel_addWeek('next');
    }
    var d = parseInt(this.Respanel_weeks.getElement(':first-child').getStyle('width')) * ++this.Respanel_currentWeek;
    if(!fast) {
      (new Fx.Tween(this.Respanel_weeks)).start('left', -d);
      if(this.menuAct == 1) {
        this.billToggle(1);
      }
    } else {
      this.Respanel_weeks.setStyle('left', -d);
    }
  },
  
  Respanel_move_prev : function(fast) {
    fast = fast||false;
    if(this.menuAct == 1) {
      var week = $('event_respanel_week'+(this.Respanel_weeksOrder[this.Respanel_currentWeek]-1));
      var days = week.getChildren();
      days.each(function(s){
        s.removeClass('active');
        s.setStyle('background-color', this.billInActiveColor);
      });
    }
    if(!fast && this.Respanel_currentWeek <= 0) {
      this.Respanel_addWeek('prev');
    }
    var d = parseInt(this.Respanel_weeks.getElement(':first-child').getStyle('width')) * --this.Respanel_currentWeek;
    if(!fast) {
      (new Fx.Tween(this.Respanel_weeks)).start('left', -d);
      if(this.menuAct == 1) {
        this.billToggle(1);
      }
    } else {
      this.Respanel_weeks.setStyle('left', d);
    }
  },
  
  Respanel_setDate : function(obj) {
    if(obj.hasClass('active')) {
      return false;
    }
    if(this.menuAct == 1) {
      return this.billToggle(1);
    }
    var dateDiv = $('date_'+ this.billDate);
    dateDiv.removeClass('active');
    dateDiv.set('morph', {duration : 'short'});
    dateDiv.morph({backgroundColor: this.billInActiveColor});
    obj.addClass('active');
    obj.set('morph', {duration : 'short'});
    obj.morph({backgroundColor: this.billActiveColor});
    ls_Event.billDate = obj.id.replace('date_','');
    this.loadBill();
  },
  
  Rating_move : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    div.firstChild.style.width = ((e.layerX||e.offsetX)/120*100) + '%';
    $('place_rating').innerHTML = parseInt((e.layerX||e.offsetX)*500/120);
  },

  Rating_out : function(e) {
    e = e||window.event;
    var target = e.target||e.srcElement;
    if((target.className && target.className == 'stars')) {
      return false;
    }
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
  },
  
  Rating_click : function(div, e) {
    e = e||window.event;
    if(!div.className) div = div.parentNode;
    var value = Math.round((e.layerX||e.offsetX)*500/120);
    this.Rating_userIsVote = value;
    return lsVote.vote(this.placeId, div, value, 'place');
  },

  Rating_voted : function(result) {
    this.Rating_current = Math.round(result.iRating);
    this.Rating_countVote = result.iCountVote;
    $('place_rating').innerHTML = this.Rating_current;
    $('place_rating_stars').style.width = ( this.Rating_current/500*100 + '%' );
    $('place_count_vote').innerHTML = result.iCountVote;
    this.Rating_userIsVote = true;
  },
  
  loadBill : function(filters, billDiv) {
    billDiv = $(billDiv||this.billDiv);
    filters = filters||{
      place_id : '*',
      date : ls_Event.billDate,
      time : '*',
      type : '*',
      limit : null
    },
    filters.city = ls_Event.billCity||'*';
    filters.type = ls_Event.billType||'*';
    
    var hash = new Hash(filters);
    if(hash.date) {
      var hashdates = hash.date.split('~');
      hash.date = hashdates.map(function(date){ return ls_Event._convertDate(date, false); }).join('-');
    }
    location.hash = hash.filter(function(v, k){ return v != '*'; }).toQueryString();
    
    billDiv.getChildren()[1].setStyle('display','none');        	
    billDiv.getChildren()[0].setStyle('display','block');        	
    JsHttpRequest.query(
      DIR_WEB_ROOT+'/include/ajax/event_loadBill.php',                       
      filters,
      function(result, errors) {  
        if (!result) {
          msgErrorBox.alert('Error','Please try again later');           
        } else {
          if (result.bStateError) {
            msgErrorBox.alert(result.sMsgTitle,result.sMsg);
          } else {  
            billDiv.getChildren()[0].setStyle('display','none');        	
            billDiv.getChildren()[1].set('html', result.sText);
            billDiv.getChildren()[1].setStyle('display', 'block');
          }
        }
      },
      true
    );
  },
  
  billToggle : function(menuAct) {
    $('event_bill_menu'+this.menuAct).removeClass('active');
    $('event_bill_menu'+menuAct).addClass('active');
    this.menuAct = menuAct;
    if(menuAct < 2) {
      $('event_respanel').style.display = 'block';
      $('event_time_select').style.display = 'none';
      if(lastday = $('date_'+ this.billDate)) {
        lastday.removeClass('active');
        lastday.setStyle('background-color', this.billInActiveColor);
      }
      var week = $('event_respanel_week'+(this.Respanel_weeksOrder[this.Respanel_currentWeek]-1));
      var days = week.getChildren();
      days.each(function(s){
        if(menuAct == 1) {
          s.addClass('active');
          s.set('morph', {duration : 'short'});
          s.morph({backgroundColor: this.billActiveColor});
        } else {
          s.removeClass('active'); 
          s.set('morph', {duration : 'short'});
          s.morph({backgroundColor: this.billInActiveColor});
        }
      });
      if(menuAct == 0) {
        days[1].addClass('active');
        days[1].setStyle('background-color', this.billActiveColor);
        this.billDate = days[1].id.replace('date_','');
      } else {
        this.billDate = days[0].id.replace('date_','')+'~'+days[days.length-2].id.replace('date_','');
      }
      this.loadBill();
    } else {
      var dates = this.billDate.split('~');
      if(dates.length < 2) {
        dates[1] = dates[0];
      }
      dates.each(function(date, i) {
        dates[i] = ls_Event._convertDate(date, false);
      });
      $('event_time_select_from').value = dates[0];
      $('event_time_select_to').value = dates[1];
      $('event_respanel').style.display = 'none';
      $('event_time_select').style.display = 'block';
    }
  },
  
  selectCity : function(input) {
    setTimeout(function() {
      if(!input.focused) {
        if(input.value != ls_Event.billCity) {
          ls_Event.billCity = input.value;
          if(!input.value || input.value == '*' || input.value == ls_Event.lang_cities_all) {
            input.value = ls_Event.lang_cities_all;
            ls_Event.billCity = '*';
          }
          ls_Event.loadBill();
        }
        input.removeClass('focused');
      }
    }, 100)
  },
  
  selectType : function(type, bySearchString) {
    types = type.split(',').map(function(v) { return v.trim(); });
    var links = $('event_complexpanel').getElements('a');
    links.each(function(link) {
      if(types.contains(link.get('text'))) {
        link.addClass('active');
      } else {
        link.removeClass('active');
      }
    });
    this.billType = type == this.lang_types_all ? '*' : type;
    if(bySearchString) { // no need to load events if no location.hash params set
      return;
    }
    this.loadBill();
  },
  
  dateSelect : function(input) {
    var from, to;
    var t = this;
    setTimeout(function() {  
      from = $('event_time_select_from').value;
      to = $('event_time_select_to').value;
      t.billDate = t._convertDate(from, true) +'~'+ t._convertDate(to, true);
      t.loadBill();
    }, 500);
  },
  
  _convertDate : function(date, toMySQL) {
    if(date == '*') return date;
    toMySQL = toMySQL||(date.indexOf('.') != -1);
    var newDate;
    var arr;
    if(toMySQL) {
      arr = date.split('.');
      newDate = arr[2] +'-'+ arr[1] +'-'+ arr[0];
    } else {
      arr = date.split('-');
      newDate = arr[2] +'.'+ arr[1] +'.'+ arr[0];
    }
    return newDate;
  },
  
  parseWordsInDate : function(date) {
    var hashdates = date.split('-');
    var date = hashdates.map(function(date){ return ls_Event._wordToDate(date); }).join('-');
    if(date.indexOf('-') != date.lastIndexOf('-')) {
      date = date.substring(0,date.indexOf('-', date.indexOf('-')+1));
    }
    return date;
  },
  
  _wordToDate : function(word) {
    var date, date2;
    var now = (new Date()).getTime();
    var day = 1000*60*60*24;
    var d,m;
    switch(word) {
      case 'today' : date = new Date(); break;
      case 'tomorrow' : date = new Date(now+1*day); break;
      case 'yesterday' : date = new Date(now-1*day); break;
      case 'thisweek' :
        date = new Date();
        date2 = new Date(now+6*day);
      break;
      case 'nextweek' :
        date = new Date(now+7*day);
        date2 = new Date(now+13*day);
      break;
      case 'lastweek' :
        date = new Date(now-7*day);
        date2 = new Date(now-1*day);
      break;
      case 'thismonth' :
        date = new Date();
        date2 = new Date(now+30*day);
      break;
      case 'nextmonth' :
        date = new Date(now+30*day);
        date2 = new Date(now+60*day);
      break;
      case 'lastmonth' :
        date = new Date(now-30*day);
        date2 = new Date(now-1*day);
      break;
      default : return word;
    }
    d = date.getDate();
    m = date.getMonth()+1;
    date = (d<10?'0'+d:d) +'.'+ (m<10?'0'+m:m) +'.'+ date.getFullYear();
    if(date2) {
      d = date2.getDate();
      m = date2.getMonth()+1;
      date = date +'-'+ ( (d<10?'0'+d:d) +'.'+ (m<10?'0'+m:m) +'.'+ date2.getFullYear() );
    }
    return date;
  },
  
  joinLeave : function(obj,idEvent) {   
	obj=$(obj);
	JsHttpRequest.query(
    	DIR_WEB_ROOT+'/include/ajax/event_joinLeave.php',                       
        { idEvent: idEvent },
        function(result, errors) {  
        	if (!result) {
            msgErrorBox.alert('Error','Please try again later');           
        	} else {
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj)  {          		
            		if (result.bState) {            			
            			$('event_join_true').style.display = 'none';
            			$('event_join_false').style.display = 'inline';
            		} else {            			
            			$('event_join_true').style.display = 'inline';
            			$('event_join_false').style.display = 'none';
            		}
            		var divCount=$('event_user_count_'+idEvent);
            		if (divCount) {
            			divCount.set('text',result.iCountUser);
            		}
            	}
            }
          }
        },
        true
    );
  },
  
  /* Google Maps support  */
  GMapInit : function(div_canvas, lat, lng, editMode) {
    if(this.GMapsInited) {
      return true;
    } else {
      this.GMapsInited = true;
    }
    /*
    var gmapscript = document.createElement('script');
    gmapscript.type = 'text/javascript';
    gmapscript.src = 'http://maps.google.com/maps?file=api&v=2&ln=ru&key=' + this.GMapKey;
    document.getElementsByTagName('BODY')[0].appendChild(gmapscript);
    */
    if (!GBrowserIsCompatible()) {
      return;
    }
    ls_Event.GMap = new GMap2(div_canvas);
    ls_Event.GMap.setCenter(new GLatLng(lat, lng), 13);
    ls_Event.GMap.addControl(new GLargeMapControl());
    ls_Event.GMap.addControl(new GMapTypeControl());
    ls_Event.GMap.enableScrollWheelZoom();
    ls_Event.GMapMarker = new GMarker(ls_Event.GMap.getCenter());
    ls_Event.GMap.addOverlay(ls_Event.GMapMarker);
    if(editMode) {
      GEvent.addListener(ls_Event.GMap, 'click', function(overlay, latlng) {
        ls_Event.GMapMarker.setLatLng(latlng);
        $('form_gmap_lat').value = latlng.lat();
        $('form_gmap_lng').value = latlng.lng();
      });
    }
    window.addEvent('unload', function() { GUnload(); });
  },
  
  toggleEdit : function(n, item) {
    var divs = $('event_edit_form').getChildren('div');
    divs.each(function(div) {
      div.setStyle('display', 'none');
    });
    $('eventEdit_div'+n).setStyle('display', 'block');
    var menus = $('event_edit_menu').getChildren('li');
    menus.each(function(div) {
      div.toggleClass('active');
    });
    if(ls_Event && (n == 1 && !ls_Event.GMapsInited)) {
      ls_Event.GMapInit($('gmap_canvas'), this.GMapLat, this.GMapLng, true);
    }
  }
}

//
//  --- RA Mod for Guru ---
//  Pou Le Serg
//

function JoinOrLeaveArtist () {
  InArtistName = $('IFollowButton').getAttribute ('artist');
  FollowOrNot = $('IFollowButton').getAttribute ('followArtistOrNot');
  TransferAJAXData (DIR_WEB_ROOT + '/guru/' + InArtistName + '/' + FollowOrNot, function (FollowOrNot) {
    if (FollowOrNot == 'follow') {
      $('IFollowButton').set ('text', 'Відписатися');
      $('IFollowButton').setAttribute ('followArtistOrNot', 'unfollow');
      msgNoticeBox.alert ('Підписка', 'Тепер ви слідкуєте за артистом');                                  // Text : follow
    } else if (FollowOrNot == 'unfollow') {
      $('IFollowButton').set ('text', 'Слідкувати');
      $('IFollowButton').setAttribute ('followArtistOrNot', 'follow');
      msgNoticeBox.alert ('Відмова від новин', 'Ви відписались від новин артиста');                       // Text : unfollow
    }
	}, FollowOrNot
	);
}

// --- RA AJAX Mod ---

var reqSpecAjax;

function TransferAJAXData (url01, targetDataContainer, Param2) {
    reqSpecAjax = null;
    if (window.XMLHttpRequest) {
        try { reqSpecAjax = new XMLHttpRequest(); } catch (e) {}
    } else if (window.ActiveXObject) {
        try { reqSpecAjax = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {
            try { reqSpecAjax = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
        }
    }
    if (reqSpecAjax) {
        reqSpecAjax.open("GET", url01, true);
        reqSpecAjax.onreadystatechange = function() { processReqChangeOnTransferData (targetDataContainer, Param2); };
        reqSpecAjax.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        reqSpecAjax.send(null);
    }
}

function processReqChangeOnTransferData (targetDataContainer, Param2) {
  try {
    // "complete"
    if (reqSpecAjax.readyState == 4) {
        // "OK"
        if (reqSpecAjax.status == 200) {
          if (Param2 != undefined) {
            ThisParameter = Param2;
          } else {
            ThisParameter = reqSpecAjax.responseText;
          }
          eval ('targetDataContainer (\'' + ThisParameter + '\')');
        } else {
          alert ("Не вдалося відправити дані:\n" + reqSpecAjax.statusText);
        }
    }
  }
  catch (e) {}
}

// -------------------------------------------------------------

function getElementComputedStyle (elem, prop) {
  if (typeof elem != "object") elem = $ (elem);
  // external stylesheet for Mozilla, Opera 7+ and Safari 1.3+
  if (document.defaultView && document.defaultView.getComputedStyle) {
    if (prop.match(/[A-Z]/)) prop = prop.replace(/([A-Z])/g, "-$1").toLowerCase();
    return document.defaultView.getComputedStyle(elem, "").getPropertyValue(prop);
  }
  // external stylesheet for Explorer and Opera 9
  if (elem.currentStyle) {
    var i;
    while ((i = prop.indexOf("-")) != -1) prop = prop.substr(0, i) + prop.substr(i + 1, 1).toUpperCase() + prop.substr(i + 2);
    return elem.currentStyle[prop];
  }
  return "";
}

function RealValue (elem, prop) {
  var CurValue = getElementComputedStyle (elem, prop);
  return parseInt (CurValue.substring (0, CurValue.length - 2));
}

// --- used by controls or auto by script

//
//  Auto Field Size Changing
//  (P) Pou Le Serg, 2010
//  http://rafrica.net
//  http://pouleserg.com
//

function DoObjectBiggerOrSmaller (ObjID, UpOrDown, MinSize, MaxSize, ChangeValue, ClearFarParent) {
  RealHeight = RealValue (ObjID, 'height');
  if (UpOrDown == 'up') {
    RealHeight += ChangeValue;
    if (RealHeight > MaxSize) return false;
  } else if (UpOrDown == 'down') {
    RealHeight -= ChangeValue;
    if (RealHeight < MinSize) return false;
  }
  if (ClearFarParent) $ (ObjID).getParent().getParent().getParent().style.height = '';
  $ (ObjID).style.height = RealHeight + 'px';
}


function CountLines (ObjID) {
  LinesCount = 0;
  // count true lines and line length
  WidthOfLetterInPX = 8;                                       // 8 is width of letter in px. Choose manually (font)
  TTextValue = $ (ObjID).value;
  TTextLeng = TTextValue.length;
  CurrentStringCharCount = 0;   // chars per string
  for (ic = 0; ic < TTextLeng; ic ++) {
    if ((TTextValue.charCodeAt (ic) == 13) || (TTextValue.charCodeAt (ic) == 10)) {
      LinesCount ++;
      CurrentStringCharCount = 0;
    } else {
      CurrentStringCharCount ++;
      if ((((CurrentStringCharCount * WidthOfLetterInPX) / $ (ObjID).clientWidth) + 0.1) >= 1) {
        LinesCount ++;
        CurrentStringCharCount = 0;
      }
    }
  }
  if (TTextLeng > 0) {
    if ((TTextValue.charCodeAt (TTextLeng - 1) != 13) && (TTextValue.charCodeAt (TTextLeng - 1) != 10)) LinesCount ++;
  }
  // count char number/perline
  NumLines = parseInt ((($ (ObjID).textLength * WidthOfLetterInPX ) / $ (ObjID).clientWidth) + 0.1);
  if (NumLines > LinesCount) LinesCount = NumLines;
  return LinesCount;
}

// --- text fields init ---

function CheckUpTextFields (TFieldID, TClearFarParent, MinHeightValue) {
  TextFieldID = $ (TFieldID);
  LinesOn50px = 3;                                                    // 3 lines on 50px (height)
  LinesByPX = 50;                                                     // 3 lines on 50px
  MaxHeightValue = 500;
  if (TextFieldID != null) {
    TextFieldID.onkeyup = function () {
      CurTextFieldLines = CountLines (TFieldID);
      
      CurRealHeight = RealValue (TFieldID, 'height');
      PossibleLines = (CurRealHeight / LinesByPX) * LinesOn50px;      // 3 lines on 50px

      if ((CurTextFieldLines + 1) >= PossibleLines) {
        // do bigger
        DoObjectBiggerOrSmaller (TFieldID, 'up', MinHeightValue, MaxHeightValue, LinesByPX, TClearFarParent);
      } else {
        if ((PossibleLines - LinesOn50px - 1) > CurTextFieldLines) {
          // do smaller
          DoObjectBiggerOrSmaller (TFieldID, 'down', MinHeightValue, MaxHeightValue, LinesByPX, TClearFarParent);
        }
      }
    }
  }
}

window.onload = function () {
  CheckUpTextFields ('form_comment_text', true, 100);                       // auto size changing
  CheckUpTextFields ('topic_text', false, 250);                             // RealValue ('topic_text', 'height'); // doesnt work
  PrepareUserStatus ();                                                     // user status init
}

//
//  Auto Field Size Changing
//  (P) Pou Le Serg, 2010
//  http://rafrica.net
//  http://pouleserg.com
//

//
//  Far AJAX
//  Pou Le Serg
//  2010
//

function FarDomainAJAXCall (InURL, ProcessToExecuteAfter, IsXML) {
  try {
    var XHR = window.XDomainRequest || window.XMLHttpRequest;
    var XHRObj = new XHR ();
    XHRObj.open ('GET', InURL, true);               // async
    if (IsXML) {
      XHRObj.onload = function () { ProcessToExecuteAfter (XHRObj.responseXML); }
    } else {
      XHRObj.onload = function () { ProcessToExecuteAfter (XHRObj.responseText); }
    }
    XHRObj.onerror = function () {
      //alert ("Error transfering data");
    }
    XHRObj.send ();
  } catch (e) {
    //alert ("Error with creating object. Old browser!");
  }
}

// --- user status ---

function PrepareUserStatus () {
  UserStatusField = $ ('TCurrentUserStatusField');
  if (UserStatusField != null) {
    UserStatusValue = trim (UserStatusField.value);
    if (UserStatusValue == '') {
      UserStatusField.value = DefaultUserStatusString;
    }
    UserStatusField.onfocus = function () {
      if (trim ($ ('TCurrentUserStatusField').value) == DefaultUserStatusString) {
        $ ('TCurrentUserStatusField').value = '';
      }
    }
    UserStatusField.onblur = function () {
      if (trim ($ ('TCurrentUserStatusField').value) == '') {
        $ ('TCurrentUserStatusField').value = DefaultUserStatusString;
      } else {
        UpdateUserStatus ();
      }
    }
  }
}

function AfterUserStatusUpdate (ParamStr) {
  IconPerLetterWidth = 4;
  $ ('TCurrentUserStatusField').addClass ("StatusUpdated");
  $ ('TCurrentUserStatusField').size = $ ('TCurrentUserStatusField').size - IconPerLetterWidth;
  StrToExec = "$ ('TCurrentUserStatusField').removeClass ('StatusUpdated'); $ ('TCurrentUserStatusField').size = $ ('TCurrentUserStatusField').size + " + IconPerLetterWidth + ";";
  $ ('UserStatusCommentCountID').innerHTML = '&nbsp;';                                // clear comment count
  $ ('UserStatusCommentCountID').title = DefaultNoCommentOnUserStatus;                // set default title
  if (trim (ParamStr) != 'ERROR') {
    $ ('UserStatusCommentCountID').parentNode.href = trim (ParamStr);                 // set new url to comments
  }
  setTimeout (StrToExec, 3000);
}

function UpdateUserStatus () {
  URLReq = DIR_WEB_ROOT + '/include/ajax/update_user_status.php?s=' + trim ($ ('TCurrentUserStatusField').value);
  FarDomainAJAXCall (URLReq, AfterUserStatusUpdate, false);
  return false;
}

// --- Smiles form ---

function getXYOffset (GetCurObj) {
  var TNObj = GetCurObj;
  var x = y = 0;
  while (TNObj) {
    x += TNObj.offsetLeft;
    y += TNObj.offsetTop;
    TNObj = TNObj.offsetParent;
  }
  return { "x" : x, "y" : y };
}

// ---

var IsSmileFormOpened = false;

function ToggleSmilesFormOnOff (InObj) {
  IsSmileFormOpened = (IsSmileFormOpened ? false : true);
  if (IsSmileFormOpened) {
    $ ('SmilesContainer').style.display = "block";
    if (InObj != undefined) {
      $ ('SmilesContainer').style.left = getXYOffset ($ (InObj)) ['x'] + "px";
      $ ('SmilesContainer').style.top = getXYOffset ($ (InObj)) ['y'] + "px";
    }
  } else {
    $ ('SmilesContainer').style.display = "none";
  }
}

function getElementsByClass (searchClass, node, tag) {
  var classElements = new Array();
  if (node == null)
    node = document;
  if (tag == null)
    tag = '*';
  var els = node.getElementsByTagName (tag);
  var elsLen = els.length;
  var pattern = new RegExp ("(^|\\s)" + searchClass + "(\\s|$)");
  for (i = 0, j = 0; i < elsLen; i ++) {
    if (pattern.test (els [i].className)) {
      classElements [j] = els [i];
      j ++;
    }
  }
  return classElements;
}

function PutSmileIntoForm (InParam) {
  if ($ ('topic_text') != null) {
    $ ('topic_text').insertAtCursor (InParam);
  }
  
  if ($ ('form_comment_text') != null) {
    $ ('form_comment_text').insertAtCursor (InParam);
  }
}

function SmilesFormInit () {
  TSmileList = getElementsByClass ('OneSmileFullContainer');
  TSmileCount = TSmileList.length;
  for (i = 0; i < TSmileCount; i++) {
    TSmileList [i].onclick = function () {
      PutSmileIntoForm (this.getElementsByTagName ('img') [0].getAttribute ('SmileAction'));
      ToggleSmilesFormOnOff ();
    };
    TSmileList [i].title = TSmileList [i].getElementsByTagName ('img') [0].getAttribute ('SmileAction');
  }
}

// --- NY added ---

var NY_OrigX = 132;   // left value (px)
var NY_OrigY = -20;   // top value (px)
var NY_OpacityStart = 1;
var NY_a = 0;
var NY_DaysBeforeAndAfter = 7;
var NY_OpacityStep = - 0.01;

function NY_CheckNightMode (NY_TObjID) {
  var NY_TCH = new Date ().getHours ();
  if (NY_TCH <= 6) {
    NY_OpacityStart += NY_OpacityStep;
    if ((NY_OpacityStart <= 0) || (NY_OpacityStart >= 1)) NY_OpacityStep = - NY_OpacityStep;
    $ (NY_TObjID).style.opacity = NY_OpacityStart;
  }
}

function NY_ShowThisAtNYOnly (NY_TObjID, NY_WidenessX, NY_WidenessY) {
  var NY_NewX = parseInt (NY_OrigX + (Math.sin (NY_a)) * NY_WidenessX);
  var NY_NewY = parseInt (NY_OrigY + (Math.sin (NY_a)) * NY_WidenessY);
  NY_a = ((NY_a > Math.PI) ? 0 : (NY_a + 0.3));
  $ (NY_TObjID).style.left = NY_NewX + 'px';
  $ (NY_TObjID).style.top = NY_NewY + 'px';
  NY_CheckNightMode (NY_TObjID);
}

window.addEvent ('domready', function () {
  var NY_TCDV = new Date ();
  if ( ((NY_TCDV.getMonth() == 11) && ((31 - NY_DaysBeforeAndAfter) <= NY_TCDV.getDate())) ||
      ((NY_TCDV.getMonth() == 0) && (NY_DaysBeforeAndAfter >= NY_TCDV.getDate())) ) {
    setInterval ('NY_ShowThisAtNYOnly (\'CoolTipOnRA\', 1, 2);', 450);
  }
});

