/*
 * Initial function
 * 
 */

$(document).ready(function(){
	loadCounter = 0;
	bindHover();
	$.history.init(loadContent);
	if($('.modal a').length){
		$('.modal a').smart_modal();
	}
	if($('#link_help').length){
		$('#link_help').smart_modal();
	}
	$("#entity_label").mouseup(function(e){
        e.preventDefault();
	});
	webSnapr.init();
	$('a.modal').live('click', function(event){
		link = this;
		var link_id = link.id;

                var h2title = $(this).attr('h2title');
                if (h2title) {
                    $('.group_title').html(h2title);
                }
                
		$(link).addClass('modal_link');
		$(link).smart_modal({hide_on_overlay_click:false, hide:function(){
			if($(link).hasClass('group_invite')){
                                groupInvite(link);
			} else {
				groupJoin(link);
			}
		}});
		$(link).smart_modal_show();
		return false;
	});		
	
	bindMoreActions();
	bindAjax();
	favoriteBind();
	followBind();
	rateBind();
	deleteBind();
	reportBind();
	commentBind();
	commentEditBind();
      more_comments();
      getCommentForm();
      commentBind2();
	messageDeleteBind();
	messageSendBind();
	groupInviteSendBind();
	bindMenuLinks();
	paginationModalWindow();
	bindCheckLogin();
	bindInfoLine();
	bindRange();
	bindTabs();
	bindStatus();
	bindGroupsApprove();
	bindBanSticker();
	bindSearchButton(); 
	avatarDDinit();
	changePostStatus();
	removeBlacklist (); 
	addBlacklist ();
	bbcodeModal();
	shareModal();
	commentModal();
        stickerModal();
        bindRelatedClick();
        addgroup ();
        deletegroup();
        bindRelatedSticker();
        bindFullScreen();

	if($.browser.msie){
            $('#mess_reciever').addClass('ie6fix');
	}
	$("a").click(function() {
	  $(this).blur();
	});
})

function bindFullScreen()
{
    $('#inline').click(function(){
        var width = $(this).attr('width');
        var height = $(this).attr('height');

        createModal($(this), 'link', height, width);
    })
}

function bindRelatedSticker(){
    Related.init();
}

function bindRelatedClick(){
    $('.sticker-related').live('click',
        function(){
            var but = $(this).next();
            
            if( but.attr('show') == 1 ){
                but.attr('show', 0);
                but.hide();
                return;
            }
            but.attr('show', 1);
            but.show();
        }
    );
}

/*
 *  Bind post status
 */
function changePostStatus(){
	$('#post').live('click', function(){
		but = $(this);
		if( but.hasClass('public') ){
			privatePostStatus(but)
		}else{
			publicPostStatus(but)
		}
	})
}
function stickerModal(){
    $('.sticker').live('click', function(){
        var height = $(this).attr('height');
        var width = $(this).attr('width');
        createModal(this, 'link', height, width);
    });
}

function windimension(){
    if(window.innerHeight !==undefined)
        A= [window.innerWidth,window.innerHeight]; // most browsers
    else{ // IE varieties
        var D= (document.body.clientWidth)? document.body: document.documentElement;
        A= [D.clientWidth,D.clientHeight];
    }
    return A;
}

function commentModal(){
	$('a.modal_comment').live('click', function(){
		createModal(this, 'link', 500, 700);
	})
}

function shareModal(){
	$('a.modal_share').live('click', function(){
		createModal(this, 'link', 600, 400);
	})
}

function bbcodeModal(){
	$('a.my_box').live('click', function(){
		createModal(this, 'href', 500, 700);
	})
}

function resizeImage(width, height){
    var src = $('#attach_box img').attr('src');

    if ( src && src.match("/http:\/\/[a-zA-Z]\.[a-xA-Z]\/image.*") )
    {
        var winSizes = windimension();
        owidth = winSizes[0];
        oheight = winSizes[1];
            // Check window size:
        if(width >= 800 || height >= 600){
            width = width - 100;
            height = height - 100;
        }
        var newsrc = src+'&width='+width+'&height='+height;
            $('#attach_box img').attr('src', newsrc);
    }
}
   

function createModal(obj, attr, height, width){
	modal = $('#modalwindow2');
	main = $('#stickr-com-site-modal-window-main');
	view = $('#stickr-com-modal-content-view');
	modal.show();
	$('#stickr-com-modal-content #wait').show();
	main.html('');
	SiteModalWindow.slideBySystem('loading');
        modal.children().remove();
	$.get($(obj).attr(attr), function(data){
                    $('#stickr-com-modal-content #wait').hide();
                    modal.html(data);
                    resizeImage(width,height);
                    // Close on ESC
                    $(document).bind('keydown', function(e) {
                             if(e.keyCode == 27){
                               $('#modalwindow2').hide();
                               $(document).unbind('keydown');
                             }
                    })

                    SiteModalWindow.slideElementBySize(height, width);
	});
}

function commentEditBind(){
	$('a.editcomment').live('click', function(event){
		if(event.button != 0) return true;
		this.blur();
		loadCommentEdit(this);
		return false;
	});
}

function loadCommentEdit(obj){
	comment_id = obj.id.replace('ec_', '');
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$('#comment_'+comment_id).removeClass('record');
			$('#comment_'+comment_id).addClass('record-form');
			$('#comment_'+comment_id).html(data.msg);
		}	
	});
}

function cancelEditComment(obj){
	parent_div = $(obj).parent().parent();
	comment_id = $(parent_div).attr('id').replace('comment_', '');
	url = 'http://'+document.location.host+'/comments/edit/'+comment_id+'?cancel=true';
	if($('#comment_blog').length){
		url = url + '&blog=true';
	}
	$.getJSON(url, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$('#comment_'+comment_id).replaceWith(data.msg);
		}	
	});
	return false;
}

function saveEditComment(obj){
	parent_div = $(obj).parent().parent();
	comment_id = $(parent_div).attr('id').replace('comment_', '');
	url = 'http://'+document.location.host+'/comments/update/'+comment_id;
	if($('#comment_blog').length){
		url = url + '?blog=true';
	}
	$.post(url,{data: $('#comment_text_'+comment_id).val()} ,function(data){
		data = eval('('+data+')');
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$('#comment_'+comment_id).replaceWith(data.msg);
		}
	})
}

function bindMoreActions(){
	$('a.more_actions').live('click', function(event){
		if(event.button != 0) return true;
		this.blur();
		loadMoreActions(this);
		return false;
	});
}

function loadMoreActions(obj){
	$('#noajax_page').remove();
	$('#actions_loader').css('display', 'block')
	
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$('#actions_loader').remove();
			$('#last_action').before(data.msg);
		}	
	});
}

function submitDigest(val){
	Set_Cookie('digest', val, '', '/', '', '');
	$('a.modal_link').smart_modal_hide();
	return false;
}

/*
 * Bind Groups
 */
function bindStatus(){
	$('.record a.sticker_status').live('click', function(event){
		if(event.button != 0) return true;
		this.blur();
		changeStickerStatus(this);
		return false;
	});
}

/*
 * Change sticker status
 */
function changeStickerStatus(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$(obj).replaceWith(data.msg);
		}	
	});
}

function privatePostStatus(but){
	lang = but.attr('lang')
	but.toggleClass('public')
	but.css('background-color', '#db9dcb')
	text = ( lang == 'ru' ) ? 'Приватный' : 'Private'
	title = ( lang == 'ru' ) ? 'Установить приватным' : 'Set private';
	but.attr('title', title);
	but.text(text)			
	$selBox = $('#entity_groups_select');
	$selBox.hide();
	$selInput = $('input',$selBox);
	$selInput.val(0);
	$selBtn = $('.b-select-value',$selBox);
	$selBtn.html($('#entity_group_nogroup').html());
	$selBox.hide();
	$('#private-checkbox').val(1)
}
function publicPostStatus(but){
	lang = but.attr('lang')
	but.toggleClass('public')
	but.css('background-color', 'rgb(151, 161, 232)')
	text = ( lang == 'ru' ) ? 'Публичный' : 'Public'
	title = ( lang == 'ru' ) ? 'Установить публичным' : 'Set public';
	but.attr('title', title);
	but.text(text)		
	$selBox = $('#entity_groups_select');
	$selBox.show();
	$('#private-checkbox').val(0)
}

/*
 * Bind Ban Sticker
 */
function bindBanSticker(){
	$('.record a.sticker_ban').live('click', function(data){
		if(data.button != 0) return true;
		if(confirm('Are you sure want to ban this sticker?')){
			this.blur();
			$.getJSON(this.href, function(data){
				if(data.error == true){
					showMessage(data.msg);
				} else {
					$('#sticker_'+data.msg).remove();
					if($('#ajax-content .record').length == 0){
						$('#ajax-content .list-records').remove();
					}
				}	
			});
		}
		return false;
	});
}

/*
 * Bind Groups approve
 */
function bindGroupsApprove(){
	$('.record a.approve_link').live('click', function(data){
		if(data.button != 0) return true;
		this.blur();
		$.getJSON(this.href, function(data){
			if(data.error == true){
				showMessage(data.msg);
			} else {
				$('#user_'+data.msg).remove();
				if($('#ajax-content .record').length == 0){
					$('#ajax-content .list-records').remove();
				}
			}	
		});
		return false;
	});
}

/*
 * Request group invite
 */
function groupInvite(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$(obj).replaceWith(data.msg);
		}	
	});
}

/*
 * Join group
 */
function groupJoin(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$(obj).replaceWith(data.msg);
		}
	});
}

/*
 * Bind hover for msIE
 */
function bindHover(){
	$(".list-records .record").live('mouseover', function(data){
		if($.browser.msie){
			$(this).addClass('hover');
		}
		
	});
	$(".list-records .record").live('mouseout', function(data){
		if($.browser.msie){
			$(this).removeClass('hover');
		}
	});
}

/*
 * Bind tabs
 */
function bindTabs(){
	$('#tabs-navigation .js-tabs a').live('click', function(data){
		if(data.button != 0) return true;
		this.blur();
		//Toggle li class current
		current_id = $('#tabs-navigation .js-tabs li.current a').attr('id');
		click_id = $(this).attr('id');
		//hide current tab
		$('#tabs-navigation li.li-'+current_id).removeClass('current');
		$('#tabs .tab-'+current_id).hide();
		//show click tab
		$('#tabs-navigation li.li-'+click_id).addClass('current');
		$('#tabs .tab-'+click_id).show();
		return false;
	})
}


/*
 * Bind range selector
 */
function bindRange(){
	$('.range').live('click', function(data){
		changeRssUrl(this);
		if(data.button != 0) return true;
		this.blur();
		id = $(this).attr('val');                
		if($(this).parent().parent().hasClass('dateselector')){
			var ul_class = 'dateselector';
			var li_class = 'range';
			var a = $('.info-line ul.langselector a');
			for(var i = 0; i < a.length; i++){
				var curr_a = $(a[i]);
				var string = curr_a.attr('href');
				var curr_range = string.match(/range=([1-3]{1})/)[1];
				var newstring = string.replace('range='+curr_range, 'range='+id);
				curr_a.attr('href', newstring);                                
			}
		} else {
			var ul_class = 'langselector';
			var li_class = 'lang';
			var a = $('.info-line ul.dateselector a');
			for(var i = 0; i < a.length; i++){
				var curr_a = $(a[i]);
				var string = curr_a.attr('href');
				var curr_lang = string.match(/lang=([a-z]{2,3})/)[1];
				var newstring = string.replace('lang='+curr_lang, 'lang='+id);
				curr_a.attr('href', newstring);                                
			}
		}
		$('.info-line ul.'+ul_class+' li.current').toggleClass('current');
		$('.info-line ul.'+ul_class+' li.'+li_class+'-'+id).toggleClass('current');
		activateRange(this);
		return false;
	})
}

/*
 * Activates range via clicking on it
 */
function activateRange(obj){
	hash = obj.href;
	hash = hash.replace(/http:\/\/.*?\//, '');
	$.history.load('/'+hash);
	return false;
}

/*
 * Bind tabs
 */
function bindInfoLine(){
	$('.info-line .toprate a.ajax').live('click', function(data){
		if(data.button != 0) return true;
		this.blur();
		activateInfoLine(this);
		return false;		
	})
}

/*
 * Activate tab
 */
function activateInfoLine(obj){
	hash = obj.href;
	hash = hash.replace(/http:\/\/.*?\//, '');
        var date = $('.info-line ul.dateselector');

        // Hide public/private filter for actions page:
        if(hash.match('.*actions.*')){
            date.hide();
        }else{
            date.show();
        }
        $('.info-line ul.tabs li.current').removeClass('current');
       if(hash == 'publicfeed'){
		var lis = $('.info-line ul.langselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('range='+curr_range, 'range=1');
		}
		var lis = $('.info-line ul.dateselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('commented', 'publicfeed');
		    lis[i].href = lis[i].href.replace('toprated', 'publicfeed');
		}
		$('.li-publicfeed').addClass('current loading');		
		//$('.info-line ul.dateselector').hide();
	} else if(hash == 'toprated'){
		$('.li-toprate').addClass('current loading');
		var lis = $('.info-line ul.dateselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('commented', 'toprated');
		    lis[i].href = lis[i].href.replace('publicfeed', 'toprated');
		}
		var curr_range = $('.info-line ul.dateselector li.current a').attr('val');
		var lis = $('.info-line ul.langselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('range='+curr_range, 'range=1');
		}
		$('.info-line ul.dateselector li.current').removeClass('current');
		$('.info-line ul.dateselector li.range-1').addClass('current');
		//$('.info-line ul.dateselector').show();
	} else if(hash == 'commented'){
		$('.li-commented').addClass('current loading');
		lis = $('.info-line ul.dateselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('toprated', 'commented');
		    lis[i].href = lis[i].href.replace('publicfeed', 'commented');
		}
		var curr_range = $('.info-line ul.dateselector li.current a').attr('val');
		var lis = $('.info-line ul.langselector li a');
		for(i=0; i<lis.length; i++){
		    lis[i].href = lis[i].href.replace('range='+curr_range, 'range=1');
		}
		$('.info-line ul.dateselector li.current').removeClass('current');
		$('.info-line ul.dateselector li.range-1').addClass('current');
		//$('.info-line ul.dateselector').show();
       	} else if(hash.indexOf('actions') >= 0){
            $('.li-actions').addClass('current loading');
            //$('.info-line ul.dateselector').hide();
    } else if(hash.indexOf('appearance') > 0){
    	$('.li-appearance').addClass('current loading');
    } else if(hash.indexOf('profilecolors') > 0){
    	$('.li-bgcolors').addClass('current loading');
    } else if(hash.length == 0){
        $('.li-index').addClass('current loading');
    } else {
        $('.li-index').addClass('current loading');
        //$('.info-line ul.dateselector').show();
    }
	$.history.load('/'+hash);
	return false;
}

/*
 * Bind check login buttons
 */
function bindCheckLogin(){
	$('.check_login').live('click', function(data){
		if(data.button != 0) return true;
		checkLogin(this);
		return false;
	})
}

/*
 * Check login function
 */
function checkLogin(obj){
	$.getJSON(obj.href,{login: $('#nickname').val()}, function(data){
		showMessage(data.msg);	
	});
}


/*
 * Load content from history
 */
function checkAnchor () {
	if(window.location.href.indexOf(window.location.host+'/help') > 0  
		// || window.location.href.indexOf(window.location.host+'/blog') > 0
            ){
		return true;
	}
}
	
function loadContent(hash){
	if (checkAnchor ()) {return true};
	
	if(hash) {
                if((hash.indexOf('comment_') >= 0) && hash.indexOf('storeanet/sticker') <= 0){
                    return true;
		}
                window.scroll(0,0);
                if(hash.indexOf('publicfeed') >= 0){
        	$('.info-line ul.tabs li.current').removeClass('current');
			$('.li-publicfeed').addClass('current');
			//$('.info-line ul.dateselector').hide();
			var lis = $('.info-line ul.langselector li a');
			for(i=0; i<lis.length; i++){
			    lis[i].href = lis[i].href.replace('commented', 'publicfeed');
			    lis[i].href = lis[i].href.replace('toprated', 'publicfeed');
			}
		} else if(hash.indexOf('toprated') >= 0){
                        $('.info-line ul.tabs li.current').removeClass('current');
			var lis = $('.info-line ul.dateselector li a');
			for(i=0; i<lis.length; i++){
			    lis[i].href = lis[i].href.replace('commented', 'toprated');
			}
			var lis = $('.info-line ul.langselector li a');
			for(i=0; i<lis.length; i++){
			    lis[i].href = lis[i].href.replace('commented', 'toprated');
			    lis[i].href = lis[i].href.replace('publicfeed', 'toprated');
			}
			//$('.info-line ul.dateselector').show();
			$('.li-toprate').addClass('current');
		}else if(hash.indexOf('appearance') > 0){
			$('.li-bgcolors').removeClass('current');
	    	$('.li-appearance').addClass('current loading');
	    } else if(hash.indexOf('profilecolors') > 0){
	    	$('.li-bgcolors').addClass('current loading');
	    	$('.li-appearance').removeClass('current');
	    } else if(hash.indexOf('commented') >= 0){
            $('.info-line ul.tabs li.current').removeClass('current');
			var lis = $('.info-line ul.dateselector li a');
			for(i=0; i<lis.length; i++){
			    lis[i].href = lis[i].href.replace('toprated', 'commented');
			}
			var lis = $('.info-line ul.langselector li a');
			for(i=0; i<lis.length; i++){
			    lis[i].href = lis[i].href.replace('publicfeed', 'commented');
			    lis[i].href = lis[i].href.replace('toprated', 'commented');
			}
			//$('.info-line ul.dateselector').show();
			$('.li-commented').addClass('current');
		} else if(hash.indexOf('actions') >= 0){
                    $('.info-line ul.tabs li.current').removeClass('current');
                    $('.li-actions').addClass('current loading');
                    //$('.info-line ul.dateselector').hide();
                } else if(hash.length == 0){
                    $('.info-line ul.tabs li.current').removeClass('current');
                    $('.li-index').addClass('current loading');
                } else {
                    if($('.li-active').length){
                        $('.info-line ul.tabs li.current').removeClass('current');
                        $('.li-index').addClass('current loading');
                        //$('.info-line ul.dateselector').show();
                    }
                }
        if(hash.indexOf('page/0?range=') > 0){
        	var curr_range = hash.match(/range=([1-3]{1})/)[1];
        	var curr_lang = hash.match(/lang=([a-z]{2,3})/)[1];
        	$('.info-line ul.dateselector li.current').toggleClass('current');
    		$('.info-line ul.dateselector li.range-'+curr_range).toggleClass('current');
        	$('.info-line ul.langselector li.current').toggleClass('current');
    		$('.info-line ul.langselector li.lang-'+curr_lang).toggleClass('current');
		} 
		
		$("#ajax-content").empty();				
		$.get( hash, 
			function (data) {
				try {
					json = eval('('+data+')');
					showMessage(json.msg);
				} catch(err){
					$("#ajax-content").html(data);
					webSnapr.init();
                                        Related.initEvents();
				}							  
			}
		)	
	} else {
		if(loadCounter!=0){
                        window.scroll(0,0);
			$("#ajax-content").empty();	
			$.get( window.document.URL, 
				function (data) {
					try {
						json = eval('('+data+')');
						showMessage(json.msg);
					} catch(err){
						$("#ajax-content").html(data);
						webSnapr.init();
                                                Related.initEvents();
					}					  
				}
			)
		}
		loadCounter++;
	}		
}

/*
 * Binding message links
 */
function messageDeleteBind(){
	$("a.messagedel").live('click', function(data) {
		if(data.button != 0) return true;
		deleteMessage(this);
		return false;
	});
}


/*
 * Delete message
 */
function deleteMessage(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			id = obj.id.replace('del_', '');
			$('#message_'+id).remove();
			if($('#ajax-content .record').length == 0){
				$('#ajax-content .list-records').remove();
			}
		}	
	});
}

/*
* ajax pagination pictures in ModalWindow
*/
function paginationModalWindow() { 
	$("#modalpaginator a.pagelink").live('click', function() {
			window.form_inside = true;
//			SiteModalWindow.slideBySystem('loading');
			$('#stickr-com-modal-content #wait').show();
			$('#stickr-com-site-modal-window-main').html('');
//			$('#stickr-com-modal-content-view').html('');
			$.get($(this).attr("href"), function(data){
				$('#stickr-com-modal-content #wait').hide();
				$('#stickr-com-modal-content-view').html(data);
				SiteModalWindow.slideBySystem('current');
			});
			return false;
	}); 
}


	function bindSearchButton() { //change it and die
		onSearchButtonClick('site');
		onSearchButtonClick('modal');
	}
	
	function onSearchButtonClick(type) {//do not touch it
		var addClass = '.search-button'
		if(type == 'modal') {
			addClass = '.search-button-modal';
		}
		$(addClass).live('click', function (data) {
			window.form_inside = true;
			$('#modalwindow2').show(); 
			if(type == 'site'){
				$('#stickr-com-modal-content-view').html('');
				SiteModalWindow.slideBySystem('loading');// slide site modal window loader
			}
			$('#stickr-com-modal-content #wait').show();
			$('#stickr-com-site-modal-window-main').html('');
			searchByTagWindow(this, type);
				return false;}
				)
	}

	function searchByTagWindow(obj, type){//want problems? change it!
		var services = new Array();
		services['flickr'] = new Array('flickr/images');	
	    services['vimeo'] = new Array('vimeo/videos');	
		services['youtube'] = new Array('youtube/videos');

		var obj_jq = $(obj);
		var service = services[$(obj).attr('service')];
		
		var input = obj_jq.parent().find('.inp-text');
		var q = input.val();
	    var href = service[0] + '?tag=' + encodeURIComponent(q);
	    var top = input.offset().top + input.height();
	    var left = input.offset().left;
		if(type == 'modal') {
			href += '&page=0';
		}
		$.get(href, function(data){
			window.form_inside = true;
			$('#stickr-com-modal-content #wait').hide();
			if (type == 'modal') {
				$('#stickr-com-modal-content-view').html(data);
			} else {
				$('#modalwindow2').html(data);
			}
			SiteModalWindow.slideBySystem(service[0].replace('/images', '').replace('/videos', ''));
		});
		return false;
	}

/*
 * Bindnig menu links
 * Ajax pagination
 */
function bindMenuLinks() {	
	$("#paginator a.pagelink").live('click', function(evt) {
		if(evt.button != 0) return true;
		var hash = this.href;
		hash = hash.replace(/http:\/\/.*?\//, '');
		$.history.load('/'+hash);
		return false;
	});

}


/*
 * Comment bind
 */
function messageSendBind(){
	$('#mess_reciever option').remove();
	$('form.send_message').live('submit', function(data){
                submitMessage(this);
		return false;
	})
}

function groupInviteSendBind(){
	$('#invite_reciever option').remove();
	$('form.invite_users').live('submit', function(data){
		submitInvites(this);
		return false;
	})
}

function submitInvites(obj){
	recievers = $('#invite_reciever option.selected');
	var param = Array();
	if(recievers){
		for($i=0; $i < recievers.length; $i++){
			param[$i] = recievers[$i].value;
		}
	}
	$.post(obj.action, {recievers: param.join('|')} ,function(data){
		data = eval('('+data+')');
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$('.bit-box').remove();
			$('#invite_reciever option').remove();
                        if($('body').attr('lang') == 'ru'){mess = 'Сообщение успешно отправлено';
                            } else {mess = 'Message sent successfully';}
                        $('#ajax_resp').html('<p class="infomessage">'+mess+'</p>');
		}
	})
}

/*
 * Submit message
 */
function submitMessage(obj){
	recievers = $('#mess_reciever option.selected');
	var param = Array();
	if(recievers){
		for($i=0; $i < recievers.length; $i++){
			param[$i] = recievers[$i].value;
		}
	}
        
	$('#submit').attr('disabled', true);
	$.post(obj.action, {message: $('#mess_body').val(), recievers: param.join('|')} ,function(data){
		
		data = eval('('+data+')');
		if(data.error == true){
                        $('#submit').attr('disabled', false);
			showMessage(data.msg);
		} else {
			$('.bit-box').remove();
			$('#mess_body').css('height', '50px');
			$('#mess_reciever option').remove();
			$('#mess_body').val('');

                        if($('body').attr('lang') == 'ru'){mess = 'Сообщение успешно отправлено';
                        } else {mess = 'Message sent successfully';}

			$('#ajax_resp').html('<p class="infomessage">'+mess+'</p>');
			$('.info-line li.inbox').removeClass('current');
			$('.info-line li.outbox').addClass('current');
			$.history.load('/message/outbox');
			$('#submit').attr('disabled', false);
		}
	})
}
/*
 * Comment bind
 */
function commentBind(){
	$('form.send_comment #send').live('click', function(data){
		submitComment(this);
		return false;
	})
}

//////////////////////////////////////////////////////////// comment inline

function commentBind2(){
	$('form.form_inline input[type=submit]').live('click', function(data){
                submitComment2(this);
		return false;
	})

        $('form.form_inline textarea').blur(function(data){
                window.form_id = ''; // erarse form_id, in focus have not got inline comments
	})

        $('#body').live('click',function(data){
           close_inline_form();
        })
}

function close_inline_form() {
            $('.form_inline').each(function(a){
                obj = $(this);
                comment_id = obj.parent().parent().attr('id').replace('form_sticker_', '');
                if(window.form_id!=comment_id) {
                    $('#stickr_'+comment_id+' .b-add-comment').show();
                    $('#form_sticker_'+comment_id).hide();
                };
            });
}

function submitComment2(obj){
        action = $(obj).parent().attr('action');
        stickr_id =action.replace(/(http:\/\/.*\/)/, '');

        parent_div = '#stickr_'+stickr_id;
        $(parent_div+' form.form_inline input[type=submit]').attr('disabled',true);
        $.post(action,{data: $(parent_div+' form.form_inline textarea').val()} ,function(data){
		data = eval('('+data+')');
		if(data.error == true){
                    showMessage(data.msg);
                   $(parent_div+' form.form_inline input[type=submit]').attr('disabled',false);
		} else {
                    $(parent_div+' form.form_inline input[type=submit]').attr('disabled',false);
                    $(parent_div+' .last_comment').before(data.msg);
                    $(parent_div+' form.form_inline textarea').val('');
                    $(parent_div+' form.form_inline textarea').height('17px');

                    $('#stickr_'+stickr_id+' .b-add-comment').show();
                    $('#form_sticker_'+stickr_id).hide();
		}
	})
}

/*
 * get all commets one first & last
 */
function more_comments(){
	$('div.b-rc-more-link a').live('click', function(event){
        comment_id = $(this).parents('div.b-record-comments').attr('id').replace('stickr_', '');
        count_commetns = $(this).attr('count_comments');
        $('#stickr_'+comment_id+' .loading').show();
        $('#stickr_'+comment_id+' .b-rc-more-link a').hide();
       	url =  '/comments/getAllcomments/'+comment_id+'/'+count_commetns;
       	$.get(url, function(data){
                $('#stickr_'+comment_id+' .loading').hide();
		$('#stickr_'+comment_id+' .b-rc-more').html(data);
            }
        );
        return false;
    })
}

function getCommentForm(){
	$('div.b-add-comment-link a').live('click', function(event){
       	comment_id = $(this).parents('div.b-record-comments').attr('id').replace('stickr_', '');
        $('#stickr_'+comment_id+' .b-add-comment').hide();
        $('#form_sticker_'+comment_id).show();
        $('#form_sticker_'+comment_id+' textarea').focus();


        window.form_id = comment_id; // save form_id in focus
        close_inline_form();
        
        $('#form_sticker_'+window.form_id+' textarea').bind('keydown', function(e) {
                if(e.ctrlKey && e.keyCode == 13){
                    submitComment2 (this);
                    $('#form_sticker_'+window.form_id+' textarea').unbind('keydown');
                }
            });
        return false;
    })
}


/////////////////////////////////////////

function submitComment(obj){
        action = $(obj).parent().attr('action');
	$('#send').attr('disabled', true);
  	$.post(action,{data: $('form.send_comment textarea').val()} ,function(data){
		data = eval('('+data+')');
		if(data.error == true){
			showMessage(data.msg);
			$('#send').attr('disabled', false);
		} else {
			if($('#comment_preview').length){
				$('#comment_preview').remove();
			}
			$('#send').attr('disabled', false);
			$('#comments_count').html(data.comments);
			$('#last_comment').before(data.msg);
			$('#hidden_comments').show();
			$('#comment').css('height', '50px');
			$('form.send_comment textarea').val('');
			$('#symbol_limit').html($('#symbol_limit_real').html());
		}
	})
}

/*
 * Ajax bind href
 */
function bindAjax(){

	$(".info-line li.ajax").ajaxStart(function(){
		$(this).addClass('loading');
	});
	$(".info-line li.ajax").ajaxStop(function(){
		$(this).removeClass('loading');
		avatarDDinit();
	});
}

/*
 * Favorites href bind
 */
function favoriteBind(){
	 $('a.makefav').live('click',function (data){
		 if(data.button != 0) return true;
		 addFavorite(this);
		 return false;
	 })
} 
 

/*
 * Adding favorite
 */ 
 
function addFavorite(obj){
	$.getJSON(obj.href, function(data){
		  if(data.error == true){
			  showMessage(data.msg);
		  } else {
			  $('#fav_'+obj.id).toggleClass('fv-on');
			  obj = $('#'+obj.id);
			  href = obj.attr('href');
			  if (obj.hasClass('fv-on')) {
				  obj.attr('href', href.replace('deletefavorite', 'makefavorite'));
			  } else {
				  obj.attr('href', href.replace('makefavorite', 'deletefavorite'));
			  } 
			  obj.toggleClass('fv-on');  
		  }
	});
}

/*
 * Follow bind
 */

function followBind(){
	$('a.follow-on').live('click',function(data){
		if(data.button != 0) return true;
		addFollower(this);
		return false;
	})
}

/*
 * Adding follower
 */
function addFollower(obj){
	$.getJSON(obj.href, function (data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			user_id = $(obj).attr('user');
			id = $(obj).attr('id');
			$('a#'+id).each(function(a){
				if(!$(this).hasClass('follow-user-'+user_id)){
					$(this).replaceWith(data.msg);
				}
			})			
			$('.follow-user-'+user_id).remove();
		}
	})	
}

/*
 * Rate bind
 */
function rateBind(){
	$('a.rate').live('click', function(data){
		if(data.button != 0) return true;
		changeRate(this);
		return false;
	})
	$('.rt-notactive a').live('click', function(data){
		if(data.button != 0) return true;
		if($('body').attr('lang') == 'ru'){
			showMessage('Вы не можете голосовать за этот стикер');
		} else {
			showMessage('You can\'t vote for this sticker');
		}
		return false;
	})
}

/*
 * Change rating
 */
function changeRate(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			id = obj.id.replace('rp_', '').replace('rm_', '');
			if(data.rate == '+'){
				$($('#rate_'+id)).html(parseInt($($('#rate_'+id)).html()) + 1);
			} else {
				$($('#rate_'+id)).html(parseInt($($('#rate_'+id)).html()) - 1);	
			}		
			$('#rating_'+id).addClass('rt-notactive');
		}	
	});
}

/*
 * Delete bind
 */
function deleteBind(){
	$('a.sticker-delete').live('click',function(data){
		if(data.button != 0) return true;
		lang=$('#body').attr('lang');
		message = ( lang == 'ru' ) ? 'Уверены, что хотите удалить этот стикер?' : 'Are you sure want to delete this sticker?';

		if(confirm(message)){
			deleteSticker(this);
		}
		return false;
	})
}

/*
 * Delete sticker
 */

function deleteSticker(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			id = obj.id.replace('del_', '');			
			parent = $('#sticker_'+id).parent();
			count = parseInt($(parent).attr('count'));
			count = count -1;
			if(count == 0){
				$(parent).remove();
			} else {
				$(parent).attr('count', count);
			}
			$('#sticker_'+id).remove();
		}	
	});
}

/*
 * Report bind
 */
function reportBind(){
	$('a.i-report').live('click',function(data){
		if(data.button != 0) return true;
		if(confirm('Are you sure want to report this sticker?')){
			reportSticker(this);
		}
		return false;
	})
}

/*
 * Report sticker
 */
function reportSticker(obj){
	href = obj.href;
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
			$("#"+obj.id).remove();
			showMessage(data.msg);
		}	
	});
}

function showMessage(text){
	obj = $('#notifications');
	obj.html(text);
	obj.slideDown('slow');
	setTimeout("hideMessage()",5000); 
}

function hideMessage(){
	$('#notifications').slideUp('slow');
}

function Set_Cookie( name, value, expires, path, domain, secure ) {
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function resizeTextarea(textarea){
   var dif = textarea.scrollHeight - textarea.clientHeight
    if (dif && dif > 0){
        if (isNaN(parseInt(textarea.style.height))){
            newsize = textarea.scrollHeight;
        }else{
            newsize = parseInt(textarea.style.height) + dif;
        }
        textarea.style.height = newsize + "px"
        return (newsize);
    }
}

var busyCounters = Array(); 

function showTimeLimit(id){
	seconds = parseInt($('#'+id).html());
	if(seconds <= 0){
		$('#'+id+'_link').remove();
		return;
	}
	$('#'+id).html(seconds-1);
//	busyCounters[id] = setInterval('showTimeLimit("'+id+'")', 1000);			
}

function fbs_click(obj) {
    window.open(obj.href,'sharer','toolbar=0,status=0,width=626,height=436');
    return false;
}
/*
 * avatar hover dropdown (DD)
 */
function avatarDDinit(){
	
	var showDD = function($sticker){
		var $avatar = $('.b-record-avatar',$sticker),
			$dd = $('.b-record-dropdown',$sticker);

		$('.record').css({'z-index':0});
		$('.b-record-dropdown').hide();
		$('.b-record-avatar-hover').removeClass('b-record-avatar-hover');

		$sticker.css({'z-index':1});
		$avatar.addClass('b-record-avatar-hover');
		$dd.show();
	}
	var hideDD = function($sticker){
		var $avatar = $('.b-record-avatar',$sticker),
			$dd = $('.b-record-dropdown',$sticker);

		$sticker.css({'z-index':0});
		$avatar.removeClass('b-record-avatar-hover');
		$dd.hide();
	}
	
	$('.b-record-avatar').each(function(){
		var $avatar = $(this),
			$sticker = $avatar.parents('.record'),
			$dd = $('.b-record-dropdown',$sticker),
			$author = $('.author-nickname',$sticker);

		$avatar.hover(
			function(){showDD($sticker);},
			function(e){
				var target = $(e.relatedTarget);
				if (!(target.parents('.b-record-dropdown').length || target.is('.b-record-dropdown'))){
					hideDD($sticker);
				}
			}
		)
		
		$dd.hover(
			function(){},
			function(e){
				var target = $(e.relatedTarget);
				if (!(target.parents('.b-record-avatar').length || target.is('.b-record-avatar'))){
					hideDD($sticker);
				}
			}
		)
		
		$author.hover(
			function(){showDD($sticker);},
			function(){}
		)
	});
}



/**
 * modal window
 */
var SiteModalWindow = {
//	element : null,
	id: 'stickr-com-modal',
	currentSystem:null,
	
	hide:function() {
		window.form_inside = true;
		$('#modalwindow2').hide();
		return false;
	},
	
	/**
	 * slide element by size
	 * @param {integer} height
	 * @param {integer} width
	 */
	slideElementBySize:function(height, width) {
		var element = document.getElementById(this.id);
		var element_size = SiteObjectHTML.getSize(element);
		var element_newposition = this.getObjectCenterPosition(element_size.h, element_size.w);
		// move object to center
		element.style.left = element_newposition.x + 'px';
		element.style.top = element_newposition.y + 'px';
		var stepsData = this.prepareSlideSteps(element_size, {h:height, w:width});
		$("#stickr-com-modal").animate({
			"left": "-=" + stepsData.p.x +  "px", 
			"top": "-=" + stepsData.p.y +  "px",
			"height": "+=" + stepsData.s.h +  "px",
			"width": "+=" + stepsData.s.w +  "px"}, "slow");
	},
	
	slideBySystem:function(system) {
		var height = 0, width = 0;
		switch(system) {
			case"flickr":
				this.currentSystem = "flickr";
				height= 370;
				width = 630;
			break;
			case"youtube":
				this.currentSystem = "youtube";
				height= 370;
				width = 780;
			break;
			case"vimeo":
				this.currentSystem = "vimeo";
				height= 370;
				width = 630;
			break;
			case"loading":
				height= 90;
				width = 240;
			break;
			case"current":
				this.slideBySystem(this.currentSystem);
				return false;
			break;
			default:
				height= 100;
				width = 250;
		}
		SiteModalWindow.slideElementBySize(height, width);
	},
	
	/**
	 * prepare steps to move and resize object
	 * @param {height integer, width integer} oldsize
	 * @param {height integer, width integer} newsize
	 * @return {s:{h, w}, w:{x,y}}
	 */
	prepareSlideSteps:function(oldsize, newsize) {
		var oldposition = this.getObjectCenterPosition(oldsize.h, oldsize.w);
		var newposition = this.getObjectCenterPosition(newsize.h, newsize.w);
		var position = {
			x: oldposition.x - newposition.x,
			y: oldposition.y - newposition.y
		}
		var size = {
			h: newsize.h - oldsize.h,
			w: newsize.w - oldsize.w
		}
		return {s:size, p:position}
	},
	
	/**
	 * get center position by height and width
	 * @param {Object} height
	 * @param {Object} width
	 * @return {x,y}
	 */
	getObjectCenterPosition:function(height, width){
		var screen = SiteObjectHTML.getClientScreen();
		var element_left = Math.ceil(screen.x/2 - width/2);
		var element_top = Math.ceil(screen.y/2 - height/2);
		return {x:element_left, y:element_top}
	},
	
	showImages:function(size){
		this.slideElementBySize(size.height, size.width);
		$('#stickr-com-modal-content #wait').hide();
		$('#modalwindow2').show();
	},
	
	Images:{
		images:Array(),
		count:0,
		border:{
			height : 20,
			width : 20
		},
		summ : {
			height:0, 
			width:0
		},
		
		getImagesSrc:function() {
			var images = $("#stickr-com-modal span.attach_thumb img");
			var imagesSrc = Array();
			for(var i = 0, size = images.length; i < size; i++) {
				imagesSrc.push(images[i].src);
			}
			return imagesSrc;
		},
		
		getSizeSumm:function(imagesSrc, callback) {
			this.count = imagesSrc.length;
			this.summ.height = 0;
			this.summ.width = 0;
			this.images=Array();
			this.countSumm(imagesSrc, callback);
		},
		
		countSumm:function(imagesSrc, callback) {
			var summ = {height:0, width:0};
			while(imagesSrc.length > 0) {
				var imageSrc = imagesSrc.pop();
				var image = new Image();
				image.src = imageSrc;
				image.onload = this.onImageLoad(image, callback);
			}
		},
		
		onImageLoad:function(image, callback){
//			this.images.push(image);
			this.summ.height += image.height + this.border.height;
			this.summ.width += image.width + this.border.width;
			if(this.images.length == this.count) {
				callback(this.summ, this.images);
			}
		}
	}
}

var SiteObjectHTML = {
	
	/**
	 * get object absolute left and top 
	 * @param {Object} object
	 */
	getAbsoluteCoord:function(object) {
		var r = {x: object.offsetLeft, y: object.offsetTop};
		if (object.offsetParent){
	    	var tmp = this.getAbsoluteCoord(object.offsetParent);
	        r.x += tmp.x;
	        r.y += tmp.y;
	    }
		return r;
	},
	
	/**
	 * get object height and width
	 * @param {Object} object
	 */
	getSize:function(object) {
		owidth =  object.clientWidth;//object.width;
		oheight = object.clientHeight;//object.height;
		if(oheight == 0) {
			oheight = object.height;
		}
		if(owidth == 0) {
			owidth = object.width;
		}
		return {h:oheight, w:owidth};
	},
	
	/**
	 * get client screen size
	 */
	getClientScreen:function() {
		var clientScreenX = 0, clientScreenY = 0;
		if (window.innerWidth) {
			clientScreenX = window.innerWidth;
		} else {
			clientScreenX = document.body.clientWidth;
		}
		if (window.innerHeight) {
			clientScreenY = window.innerHeight;
		} else {
			clientScreenY = document.body.clientHeight;
		}
		return {x:parseInt(clientScreenX), y:parseInt(clientScreenY)};
	}
};
var SiteToolTip = {
		block : null,
		tdn5 : null,
//		site : window.domain,
		outToolTipTimeOut : null,
		data : null,
		style : {
			height:100,
			width:100,
			position:'absolute',
			zIndex : 11111112
		},

		init:function() {
			if(this.block == null) {
				this.create();
			}
			return this.block;
		},

		addListner:function() {
			$('img.SiteModalWindowElement').mouseover(function(){SiteToolTip.showByObjectId(this.id);})
			$('img.SiteModalWindowElement').mouseout(function(){SiteToolTip.startHide();})
		},

		create:function() {
			this.loadCSS();
			this.block = document.createElement("div");
			this.block.setAttribute("id",'stickr_tool_tip');
			this.block.className = 'yousticker_com_hints';
			this.block.style.display = 'none';
			this.block.style.position = this.style.position;
			this.block.style.zIndex = this.style.zIndex;
			this.block.innerHTML = this.getHTML();
			document.body.appendChild(this.block);
			jsCore.addListener({"mElement":this.block,"sType":"mouseover","fnCallback":this.fnMouseOver,"oObj":this,"mScope":true,"sLabel":"Label"});
			jsCore.addListener({"mElement":this.block,"sType":"mouseout","fnCallback":this.fnMouseOut,"oObj":this,"mScope":true,"sLabel":"Label"});
			this.tdn5 = document.getElementById('Stickr_SiteToolTip_tdn5');
		},

		loadCSS:function() {
			var d = new Date();
			var m = d.getSeconds() + '-' + d.getMonth() + '-' + d.getDay() + '-' + d.getMilliseconds();
//			LabelLoader.fnLoadFile("/design/css/siteHints.css?" + m,"css");
			A=document.createElement("link");
			A.type="text/css";
			A.rel="stylesheet";
			A.href='/design/css/siteHints.css?' + m;
			A.media="screen";
			document.getElementsByTagName("head")[0].appendChild(A);
		},

		getHTML:function() {
			var resHTML =
				'<table>' +
					'<tr>' +
						'<td class="tdn-1"></td>' +
						'<td class="tdn-2"></td>' +
						'<td class="tdn-3"></td>' +
					'</tr>' +
					'<tr>' +
						'<td class="tdn-4"></td>' +
						'<td id="Stickr_SiteToolTip_tdn5" class="tdn-5">' +
						'</td>' +
						'<td class="tdn-6"></td>' +
					'</tr>' +
					'<tr>' +
						'<td class="tdn-7"></td>' +
						'<td class="tdn-8"></td>' +
						'<td class="tdn-9"></td>' +
					'</tr>' +
				'</table>' +
				'<div class="yousticker_com_hints_arrow_top"></div>';
			return resHTML;
		},

		changeContent:function(text) {
			this.tdn5.innerHTML = text;
		},

		showByCoord:function(x,y) {
			this.stopHide();
			this.block.style.left = x + 'px';
			this.block.style.top = y + 'px';
			this.block.style.display = '';
		},

		showByObject:function(object) {
			var r = SiteObjectHTML.getAbsoluteCoord(object);
			var s = SiteObjectHTML.getSize(object);
			var displacement = 0;
			if(s.w < 20) {
				displacement = -15;
			}
			this.showByCoord(r.x + displacement, r.y + s.h + 5);
			return false;
		},

		showByObjectId:function(id, text) {
			this.init();
			var obj = document.getElementById(id);

			if(obj == null) {
				return false;
			}

			if(text == undefined || text == null || text == '') {
				text = this.getDataById(id);
			}
			this.changeContent(text);
			this.showByObject(obj);
			return true;
		},

		hide:function() {
			this.block.style.display = 'none';
		},

		startHide:function() {
			this.outToolTipTimeOut = setTimeout("SiteToolTip.hide()", 1000);
		},

		stopHide:function() {
			clearTimeout(this.outToolTipTimeOut);
		},

		fnMouseOver:function() {
			clearTimeout(SiteToolTip.outToolTipTimeOut);
		},

		fnMouseOut:function() {
			this.startHide();
		},

		setData:function(data) {
			this.data = data;
		},

		getDataById:function(id) {
			var num = id.replace('SiteModalWindowElement_', '');
			return this.data[num];
		}


	};

JSCore=function() {
	this.fnInit()
};
JSCore.prototype={
	fnInit:function() {
		this.aStack=new Array();
		this.oInterval;
		this.bLoaded;
		this.aEventCache=new Array()
	},
	addListener:function(D) {
		var A;
		var E;
		typeof D.sLabel!="undefined"?null:D.sLabel="";typeof D.oObj!="undefined"?null:D.oObj=null;
		typeof D.mOverrideScope!="undefined"?null:D.mOverrideScope=null;
		if(D.mScope){
			if(D.mScope===true) {
				A=D.oObj
			} else {
				A=D.mScope
			}
		} else {
			A=D.mElement
		}
		E=function(F) {
			if(!jsCore) {
				return 0
			} else {
				D.fnCallback.call(A,jsCore._getEvent(F),D.oObj)
			}
			return false
		};
		if(typeof (D.mElement)=="string") {
			var C=document.getElementById(D.mElement);
			jsCore._addEvent({nNode:C,sType:D.sType,fnCallback:D.fnCallback,fnCallbackWrapped:E,sLabel:D.sLabel})
		} else {
			if(D.mElement) {
				if(D.mElement.nodeName||D.mElement==window) {
					jsCore._addEvent({nNode:D.mElement,sType:D.sType,fnCallback:D.fnCallback,fnCallbackWrapped:E,sLabel:D.sLabel})
				} else {
					for(var B=0;B<D.mElement.length;B++) {
						jsCore._addEvent({nNode:D.mElement[B],sType:D.sType,fnCallback:D.fnCallback,fnCallbackWrapped:E,sLabel:D.sLabel})
					}
				}
			}
		}
	},
	_addEvent:function(A) {
		this.aEventCache[this.aEventCache.length++]={"nNode":A.nNode,"sType":A.sType,"fnWrapped":A.fnCallbackWrapped,"fn":A.fnCallback,"sLabel":A.sLabel};
		if(A.nNode.addEventListener) {
			A.nNode.addEventListener(A.sType,A.fnCallbackWrapped,false)
		} else{
			if(A.nNode.attachEvent) {
				A.nNode.attachEvent("on"+A.sType,A.fnCallbackWrapped)
			}
		}
	},
	removeListener:function(B) {
		this.aiDelete=new Array();
		if(typeof B.sLabel=="string") {
			for(var A=0;
			A<this.aEventCache.length;A++) {
				if(this.aEventCache[A].sLabel==B.sLabel) {
					jsCore._removeEvent({nNode:this.aEventCache[A].nNode,sType:this.aEventCache[A].sType,fn:this.aEventCache[A].fn})
				}
			}
		} else {
			if(typeof B.mElement=="string") {
				nElement=document.getElementById(B.mElement);
				jsCore._removeEvent({nNode:nElement,sType:B.sType,fn:B.fnCallback})
			} else {
				if(!B.mElement.length) {
					jsCore._removeEvent({nNode:B.mElement,sType:B.sType,fn:B.fnCallback})
				} else {
					for(var A=0;A<B.mElement.length;A++) {
						jsCore._removeEvent({nNode:B.mElement[A],sType:B.sType,fn:B.fnCallback})
					}
				}
			}
		}
		for(var A=this.aiDelete.length-1;A>=0;A--) {
			this.aEventCache.splice(this.aiDelete[A],1)
		}
	},
	_removeEvent:function(B) {
		for(var A=0;A<this.aEventCache.length;A++) {
			if(B.nNode==this.aEventCache[A].nNode&&B.sType==this.aEventCache[A].sType&&B.fn==this.aEventCache[A].fn) {
				if(B.nNode.removeEventListener) {
					B.nNode.removeEventListener(B.sType,this.aEventCache[A].fnWrapped,false)
				} else {
					if(B.nNode.detachEvent){
						B.nNode.detachEvent("on"+B.sType,this.aEventCache[A].fnWrapped)
					}
				}break
			}
		}
		this.aiDelete[this.aiDelete.length++]=A
	},
	_getEvent:function(A) {
		return A||window.event
	},
	getElementFromEvent:function(A) {
		var B;
		if(A.target) {
			B=A.target
		} else {
			if(A.srcElement) {
				B=A.srcElement
			}
		}
		if(B.nodeType==3) {
			B=B.parentNode;
		}
		return(B);
	}
}
var jsCore=new JSCore();
 
function displaylimit(id, limit, limit_id){
	if(limit_id == undefined){
		limit_id = 'symbol_limit';
	}
	
	var ta = $("#"+id);
    var counter = $("#"+limit_id);
    if(ta.attr('default') == 'true'){
    	counter.html(limit);
	} else {
    	if(ta.val() != undefined){
    		counter.html(limit - ta.val().length);
    	} else {
    		counter.html(limit);
    	}
	}
		if ($.browser.mozilla && $.browser.version.substr(0,3)=="1.9") {
			ta.bind("input", function() {
				updateCounter();
			});
	}
	else {
	ta.bind("keyup", function() {
			updateCounter();
		});
	}
  
	function updateCounter() {
		ostatok=limit - ta.val().length;
		counter.html(ostatok);
		if (ostatok < 0) {
			message=( $('#body').attr('lang') == 'ru' ) ? 'Превышен допустимый лимит в '+limit+' символов!' : 'Limit '+limit+' symbols!';
			showMessage(message)
		}
		var split = ta.val().split("\n");
	if (split.length > 15) {
    	ta.attr("rows", split.length);
		}
	}
}

/*
 * Blacklist 
 */
function removeBlacklist(){
	$('a.blacklist').live('click',function(data){
		if(data.button != 0) return true;
		blacklist(this);
		return false;
	})
}
function addBlacklist(){
	$('a.un_blacklist').live('click',function(data){
		if(data.button != 0) return true;
		blacklist(this);
		return false;
	})
}
function blacklist(obj){
	$.get(obj.href, function (data){
			id = $(obj).attr('id');
			$('a#'+id).each(function(a){
				$(this).replaceWith(data);
			})
	})	
}


/**
 *  change rss url 
 */
function changeRssUrl (obj) {
	changeRssUrl2('.li-toprate',obj);
	changeRssUrl2('.li-publicfeed',obj); 
	changeRssUrl2('.li-commented',obj); 
}

function changeRssUrl2 (str,obj) {
	hash = $(obj).attr('href');
	hash = hash.replace(/(http:\/\/.*?\?)/, '');
	href=$(str+' .i-rss').attr('href');
        
        if(href){
            href=href.replace(/\?.*/, '');
            timezone = -1 * new Date().getTimezoneOffset()/60;
            $(str+' .i-rss').attr('href',href+'?'+hash+"&timezone="+timezone);
        }
}

$(document).ready(function(){
    $('#livejournal-show').click(function(){
        var modal = $('#modalwindow2');
	var main = $('#stickr-com-site-modal-window-main');
	var content = $('#stickr-com-modal-content');
        $('#livejournal-login', content).remove();
	modal.show();

        var data = $('#livejournal-loader').html();
        content.append(data);
        SiteModalWindow.slideElementBySize(200, 300);

        $('#modalwindow2 #lj_button').live('click',function(){
           $('.lj-response').remove();
           var link = $(this).attr('link');
           $('.loading').show();
           $.post(link,{nickname:$('#modalwindow2 #lj_nickname').val(),password:$('#modalwindow2 #lj_password').val()},
               function(data){
                        if($('#status', data).attr('result') == 'error'){
                            $('#modalwindow2 #livejournal-login').remove();
                            content.append(data);
                        }else{
                            var message = $('#lj-active', data).html();
                            // Deleted div
//                            var parent = $('#livejournal-show').parent();
//                            var box = parent.parent();
//                            parent.remove();
//                            $('div:last', box).remove();
//                            box.append(message);
                            $('#livejournal-show-block').html(message);
                            modal.hide();
                        }
                        $('.loading').hide();
               }
           );
        });
    });
});



function addgroup () {
    $('#create_group').live('click',(function() {
        $('#form_group_add').html('');
        $('#modalwindow2').show();
        $('#stickr-com-modal-content #wait').show();
        
        str = '<iframe src="/groups/add/?view=small" width="512px" height="490px" frameborder="0" scrolling="no"></iframe>';
        SiteModalWindow.slideElementBySize(510, 532);
        $('#stickr-com-modal-content').html(str);
        return false;
    }))
}

function deletegroup () {
    $('#delete_group').live('click',(function() {
       $('#modalwindow2').show();
       $('#stickr-com-modal-content').html($('#delete_group_block').html());
       SiteModalWindow.slideElementBySize(200, 550);
        return false; 
    }))
}
