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'                        
                },
                micro_stream: {
						url: DIR_WEB_ROOT+'/include/ajax/stream_micro.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'                        
                }
        },

        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','Please try again later');           
        	}
        	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','Please try again later');           
        	}
            if (result.bStateError) {
            	msgErrorBox.alert(result.sMsgTitle,result.sMsg);
            } else {            	
            	msgNoticeBox.alert(result.sMsgTitle,result.sMsg);
            	if (obj)  {     
            		obj.getParent().removeClass('active');       		
            		if (result.bState) {            			
            			obj.getParent().addClass('active');
            		}
            		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','Please try again later');           
        	}
            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);
        				var countComments=$('count-comments');
        				countComments.set('text',parseInt(countComments.get('text'))+aCmt.length);
        				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_content_id_'+this.iCommentIdLastView).removeClass('view');
		}				
		$('comment_content_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'
                },
                micro: {
						url: DIR_WEB_ROOT+'/include/ajax/microFavourite.php',
                        targetName: 'idMicro'
				}
        },

        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)  {
            		obj.set('text',result.sToggleText);
            		if (result.bState) {
            			obj.getParent('li').removeClass('add');
            			obj.getParent('li').addClass('del');
            		} else {
            			obj.getParent('li').removeClass('del');
            			obj.getParent('li').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;	
	}	
	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 } );
}

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+'" target="_blank">'+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();   
});

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'
                }
        },

        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);
               
                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();
});




var dWindowZIndex = 100;

var dWindow = new Class({
	options: {
		minWidth : 150,
		minHeight : 150,
		width : 200,
		height : 200,
		top : 0,
		left : 0,
		resizable : true,
		statusBar : true,
		content : '',
		id : ''
	},
	
	handle : null,
	drag : null,
	dragParams : {},

	// конструктор класса
	initialize: function(options){
		this.setOptions(options);
	},
	
	
	_create : function(id){
		var target = $(id);
		if (!target)
			return;
		
		this.handle = new Element('div', {
								'class':'dWindow',
								'id' : this.options.id,
								styles : {
									'width':this.options.width + 2,
									'left':this.options.left,
									'top':this.options.top,
									'z-index':dWindowZIndex
								}
							});
		dWindowZIndex++;
		this.handle.addEvent('mousedown', this.up.bind(this));
		
		var bar = new Element('div', {'class':'topBar'});
		var closeBtn = new Element('div', {'class':'closeBtn'});
		closeBtn.addEvent('click', this.close.bind(this));
		closeBtn.injectInside(bar);

		var table = new Element('table',{
			'class':'dContainer',
			'cellpadding':0,
			'cellspacing':0,
			'border':0
		});

		var tbody = new Element('tbody');

		// первый ряд
		var row = new Element('tr');
		var leftBorder = new Element('td', {'rowspan':2,'class':'leftBorder'});
		var rightBorder = new Element('td', {'rowspan':2,'class':'rightBorder'});
		var center = new Element('td');
		var content = new Element('div',{'class':'centralArea', styles : {'width':this.options.width, 'height':this.options.height}});
		
		if($type(this.options.content) == 'object') content.adopt(this.options.content);
		else content.set('html',this.options.content);
		
		center.adopt(content);
		this.cont = content;
		
		row.adopt([leftBorder, center, rightBorder]);

		var row2 = new Element('tr');
		var statusBar = new Element('td',{'class':'statusBar'});
		var brResize = new Element('div', {'class':'resize'});
		brResize.injectInside(statusBar);
		statusBar.injectInside(row2);
		
		var row3 = new Element('tr');
		var bottomBorder = new Element('td', {'colspan':3,'class':'bottomBorder'});
		bottomBorder.injectInside(row3);
		
		row.injectInside(tbody);
		row2.injectInside(tbody);
		row3.injectInside(tbody);
		
		tbody.injectInside(table);
		
		this.handle.adopt([bar, table]);

		
		this.handle.injectInside(target);
		
		this.drag = new Drag.Move(this.handle, {
		    snap: 0,
		    handle: bar,
			container: target,
		    onSnap: function(el){
		        el.addClass('dragging');
		    },
		    onComplete: function(el){
		        el.removeClass('dragging');
		    }
		});
		
		var that = this;
		this.rbDrag = new Drag(rightBorder, {
			onSnap : function(elem){
				that.dragParams.w = content.getSize().x;
				that.dragParams.W = that.handle.getSize().x;
				that.dragParams.target = content;
			},
			
			onDrag : function(elem){
				var delta = this.mouse.now.x - this.mouse.start.x;
				var w = that.dragParams.w + delta;
				var targetPos = that.dragParams.target.getPosition();
				
				if (w < that.options.minWidth || (W + targetPos.x) > (window.getScrollLeft() + window.getWidth())) {
					return;
				}
				
				var W = that.dragParams.W + delta;
				that.dragParams.target.setStyle('width', w);
				that.handle.setStyle('width', W)
			}
		});
		
		this.lbDrag = new Drag(leftBorder, {
			onSnap : function(elem){
				that.dragParams.w = content.getSize().x;
				that.dragParams.W = that.handle.getSize().x;
				that.dragParams.pos = content.getPosition();
				that.dragParams.target = content;
			},
			
			onDrag : function(elem){
				var delta = this.mouse.now.x - this.mouse.start.x;
				var w = that.dragParams.w - delta;
				var W = that.dragParams.W - delta;
				var L = this.mouse.start.x + delta;
				if (w < that.options.minWidth || L < target.getPosition().x) {
					return;
				}
				that.dragParams.target.setStyle('width', w);
				that.handle.setStyle('width', W);
				that.handle.setStyle('left', L);
			}
		});
		
		this.bDrag = new Drag(bottomBorder, {
			onSnap : function(elem){
				that.dragParams.h = content.getSize().y;
				that.dragParams.H = that.handle.getSize().y;
				that.dragParams.target = content;
			},
			
			onDrag : function(elem){
				var delta = this.mouse.now.y - this.mouse.start.y;
				var h = that.dragParams.h + delta;
				var H = that.dragParams.H + delta;
				var targetPos = that.dragParams.target.getPosition();

				if (h < that.options.minHeight || (H + targetPos.y) > (window.getScrollTop() + window.getHeight())) {
					return;
				}
				that.dragParams.target.setStyle('height', h);
				that.handle.setStyle('height', H);
			}
		});
		
		
		this.resizeDrag = new Drag(brResize, {
			preventDefault: true,
			style: false,
			onSnap : function(elem){
				that.dragParams.h = content.getSize().y;
				that.dragParams.H = that.handle.getSize().y;
				that.dragParams.w = content.getSize().x;
				that.dragParams.W = that.handle.getSize().x;
				that.dragParams.target = content;
			},
			
			onDrag : function(){
				var deltay = this.mouse.now.y - this.mouse.start.y;
				var deltax = this.mouse.now.x - this.mouse.start.x;
				var h = that.dragParams.h + deltay;
				var H = that.dragParams.H + deltay;
				var w = that.dragParams.w + deltax;
				var W = that.dragParams.W + deltax;
				var targetPos = that.dragParams.target.getPosition();
				
				if (h < that.options.minHeight || (H + targetPos.y) > (window.getScrollTop() + window.getHeight())
					|| w < that.options.minWidth || (W + targetPos.x) > (window.getScrollLeft() + window.getWidth())) {
					return;
				}

				that.dragParams.target.setStyle('height', h);
				that.handle.setStyle('height', H);
				that.dragParams.target.setStyle('width', w);
				that.handle.setStyle('width', W);
			}
		});
	},
	
	_destroy : function(){
		if ($type(this.handle) == 'element'){
			this.handle.destroy();
		}
		this.handle = null;
	},
	
	open : function(elem){
		if (!this.handle)
			this._create(elem);
	},
	
	close : function(){
		this._destroy();
	},

	up : function(){
		this.handle.setStyle('z-index', ++dWindowZIndex);
	},
	
	// заимствуем методы классов Options и Events
	Implements : [Options, Events]
});



window.addEvent('domready', function() {

	$$('#mainmenu a').each(function(el) {
		
		var fx = new Fx.Tween(el, {
			duration: 500,
			link: 'cancel'
		});

		if(!el.getParent().hasClass('active')) {
			
			el.setStyle('background-position','0px 0px').addEvents({
				mouseenter: function(e) {
					//e.stop();
					fx.start('background-position','-150px 0px');
				},
				mouseleave: function(e) {
					//e.stop();
					fx.start('background-position','0px 0px');
				}
			});
		}
	});
	
	
	$$('#content a').each(function(item, idx) {
	
		if(item.href.test('.swf')) {
			item.addEvent('click', function(event) {
			
				event.stop();
				
				var obj = new Swiff(item.href, {
				    id: 'flash_' + idx,
				    width: '100%',
				    height: '100%'
				});
				
				var w = new dWindow({
					width: 640,
					height: 480,
					minWidth: 320,
					minHeight: 240,
					left: (window.getSize().x / 2) - 320,
					top: (window.getSize().y / 2) - 240,
					content: obj
				}).open($(document.body));
				
			});
		}	
		
	});
	
});


function addImageToTopic(path, img, title) {
	$('topic_text').insertAtCursor('<a href="'+path+'" title="'+title+'"><img src="'+img+'" alt="'+title+'" /></a>');
	return false;
}

function submitSearch(sText) {		
	window.location=DIR_WEB_ROOT+'/search/?searchfor='+sText;
	return false;
}

function submitGenerator(sText) {		
	window.location=DIR_WEB_ROOT+'/generator/'+sText;
	return false;
}


