/*
 * Initial function
 * 
 */

$(document).ready(function(){        
	var config = "FilterConfig" in window ? FilterConfig : [];
	window.Filter = Workspace(config);

	var hm = document.getElementsByTagName('html');
	if( hm[0].getAttribute('class') == 'popup' )
	{
		var today = new Date();
		today.setTime( today.getTime() );
		expires = 14 * 60 * 60 * 24;
		var expires_date = new Date( today.getTime() + (expires) );
            
		window.onblur = function()
		{
			Set_Cookie ('widget-counter',0,expires_date,'/');
		}
		window.onfocus = function()
		{
			Set_Cookie ('widget-counter',1,expires_date,'/');
		}
	}

	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();
        addUrls();
      //more_comments();
      //getCommentForm();
      //commentBind2();
	messageDeleteBind();
	messageSendBind();
	//groupInviteSendBind();
	//bindMenuLinks();
	paginationModalWindow();
	bindCheckLogin();
	bindInfoLine();
//	bindRange();
	bindTabs2();
	bindStatus();
	bindGroupsApprove();
	bindBanSticker();
	bindSearchButton(); 
	avatarDDinit();
	changePostStatus();
	removeBlacklist (); 
	addBlacklist ();
	bbcodeModal();
	shareModal();
	commentModal();
        stickerModal();
        bindRelatedClick();
        addgroup ();
        deletegroup();
        bindRelatedSticker();
        bindFullScreen();
        bindShortSticker();
        //bindViewTypeSelector();
        reportComment(); 
        bindDisplayLimit();        

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

/**
 * Url - url parser/modifier
 * 
 * @example: Url("https://example.com/foobar/index.html?foo=bar").path("/foobar/404.html").compose();
 * 
 */

var Url = function (url) {
	var m = url.match(/(http|https):\/\/(.*?)\/(.*?)(\?|#|$)/);

	var proto = m[1], domain = m[2], path = m[3], params = getUrlParams(url);

	var compose = function () {
		return setUrlParams([proto, "://", domain, "/", path].join(""), params);
	};

	var accessor = function (key) {
		var get = function () {
			return eval(key);
		};

		var set = function (value) {
			return (eval(key + "=value;"), this);
		};

		return function () {
			return (arguments.length == 0 ? get : set).apply(this, arguments);
		};
	};

	return {
		proto: accessor("proto"),
		domain: accessor("domain"),
		path: accessor("path"),
		compose: compose
	};
};

var getUrlParams = function (url) {
	var params = {};
	var pairs = url.substr(url.indexOf("?") + 1 || url.length).split("&");

	$(pairs).each(function () {
		var t = this.split("=");
		params[t[0]] = t[1];
	});

	return params;
};

var setUrlParams = function (url, params) {
	var p = [], k;
	for(k in params) {
		p.push(k + "=" + params[k]);// encodeURIComponent(params[k]));
	}

	return (url.substr(0, url.indexOf("?") + 1) || url + "?") + p.join("&");
};

function Workspace(config) {
    return false;
        var aditional_params = ['tags[]', 'group'];
	var links_vector = [];
	
        var parceHashByParam = function(param) {
            var params = window.location.hash.split('&');
            var tmp = '';
            for(var key in params) {
                if(0 == params[key].indexOf(param + '=')) {
                    tmp += params[key] + '&';
                }
            }
            tmp = tmp.replace(param + '=', '');
            tmp = tmp.substr(0, tmp.length - 1);
            return tmp;
        }

	var clearCurrent = function (element) {
            if(undefined == $(element).parent("li")[0] || null == $(element).parent("li")[0]) {
                $(element).removeClass("sel");
            } else {
                $(element).parent("li").removeClass("sel");
            }
	};

	var setCurrent = function (element) {
            if(undefined == $(element).parent("li")[0] || null == $(element).parent("li")[0]) {
                $(element).addClass("sel");
            } else {
                $(element).parent("li").addClass("sel");
            }
	};

	var handleClick = function (event) {
		if(event.button == 0) {		// left-click
			this.blur();

			var actor = this, param_name;

			$(links_vector).each(function (index) {
				(this[0] == actor) && (param_name = this[1]);
			});

			var params = getUrlParams($(actor).attr("href"));
			var update = function (element) {
                                var p = getUrlParams($(element).attr("href"));
                                p[param_name] = params[param_name];
				$(element).attr("href", setUrlParams($(element).attr("href"), p));
			};

			$(links_vector).each(function (index) {
				if(this[1] != param_name) {
					update(this[0]);
				} else {
					clearCurrent(this[0]);
				}
			});

			$(".tabs a.ajax").each(function (index) {
				update(this);
			});
			$(".tabs a.rssIcon").each(function (index) {
				update(this);
			});
			setCurrent(this);
			applyFilter(actor);
			changeRssUrl(actor);
                        updateFilter();
		}
		event.stopPropagation();
		return false;
	};

	var updatePath = function (new_path) {
		$(links_vector).each(function (index) {
                    var url = Url(this[0].href), path = url.path().split("/");
                    path[0] = new_path;
                    this[0].href = url.path(path.join("/")).compose();
		});
	};

        var updateFilter = function() {
            $(links_vector).each(function (index) {
                var params = getUrlParams(this[0].href);
                for(var i = 0, count = aditional_params.length; i < count; i++) {
                    var name = aditional_params[i];
                    var value = parceHashByParam(name);
                    if(value == '') {
                        params = removeParam(name, params);
                    } else {
                        params[name] = value;
                    }
                }
                this[0].href = setUrlParams(this[0].href, params);
            });
        }

        var removeParam = function(name, params) {
            var tmp = [];
            for(var key in params) {
                if(key != name) {
                    tmp[key] = params[key];
                }
            }
            return tmp;
        }

	var filters = [
//		{selector: "example-css", param: "ex", values: [100, 200, 300], current_value: 100, ref_element: undefined}
	];
	
	$(config).each(function (index) {           
		var values = [], links = [];

		var param_name = this.param;
		
		$("." + this.selector + " a").each(function () {
			values.push($(this).attr("val"));
			links.push(this);	// deprecated ???
			links_vector.push([this, param_name]);
		});

		$("." + this.selector + " a").live("click", handleClick);

		filters.push({
			selector: this.selector,
			param: this.param,
			values: values,
			current_value: $("." + this.selector + " .sel a").eq(0).attr("val"),
			ref_element: $("." + this.selector),
			links: links
		});
	});

	return {
		updatePath: updatePath,
                updateFilter: updateFilter
	};
}

/*
 * make urls
 */
function addUrls() {
    var obj;
    $('.b-add-comment-link').each(function(a){
        obj = $(this);
        obj.html('<a href="'+obj.attr('url')+'"><b>+</b><i>'+obj.attr('titleLink')+'</i></a>')
    })

    $('.shareLink').each(function(a){
        obj = $(this);
        obj.html('<a onclick="return false;" title="'+obj.attr('urlTitle')+'" class="modal_share icon i-share" href="'+obj.attr('url')+'" object="true" width="420" height="600" link="'+obj.attr('link')+'"></a>')
    })
}

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().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(){
    return false; 
//    $('.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;
}


// deprecated ???
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 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 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;
                lang=$('#body').attr('lang');
		message = ( lang == 'ru' ) ? 'Уверены, что хотите заблокировать этот стикер?' : 'Are you sure you want to ban this sticker?';
		if(confirm(message)){
			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 bindTabs2(){
	$('#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');
//		applyFilter(this);
//		return false;
//	})
//}

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

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

/*
 * Activate tab
 */
function activateInfoLine(obj){
	hash = obj.href;
	hash = hash.replace(/http:\/\/.*?\//, '');

//	alert(hash.split("?")[0]);
	
	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');
	$(obj).parent().parent().parent().addClass("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').show();
	} 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);
        //scrol_ajax_content ()

        return false;
}

function scrol_ajax_content () {

    if (!$('#ajax-content').length){
        return;
    }

    var destination = $('#ajax-content').offset().top - 80;
	var tags = (navigator.appName == 'Opera') ? 'html' : 'body,html';

        $(tags).animate({scrollTop: destination}, 500, function() {
		window.animate_scroll = true;
		setDefaultHeight();
	});
}

function setDefaultHeight () {    
    if (window.animate_scroll && window.animate_load) {
        
        $('#ajax-content').css( 'height', 'auto' );
        $('#ajax-content').css( 'min-height', '0' );
        window.animate_scroll=false;
        window.animate_load=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){		
                if (data.error==false){
                    $('#nickname').removeClass('errorInput').removeClass('errorInput'); // fix bug bouble class="errorInput errorInput" in html
                    $('#nickname').next('.errorMessage').empty();
                }else{
                    if (!$('#nickname').hasClass('errorInput')) {
                        $('#nickname').addClass('errorInput');
                    }
                }
                showMessage(data.msg);
	});
}

var parseJSON = function (string) {
	try {
		return ("JSON" in window ? JSON.parse(string) : eval("(" + string + ")"));
	} catch (_) {
		return undefined;
	}
};

/*
 * Load content from history
 */
function loadContent(hash, f_continue) {
	var checkAnchor = function () {
		return (
			window.location.href.indexOf(window.location.host+'/help') > 0
			|| window.location.href.indexOf('blog_id') > 0
		);
	};
	
	if (window.noLoadUrlAfterHash == true) {
		window.noLoadUrlAfterHash = false;
		return;
	}
        
	if (checkAnchor()) {
		return;
	}

	var h = $("#ajax-content").height();        
	$("#ajax-content").css('min-height', h + 'px');
	
	var PREFIX = "";

	if (hash) {
		scrol_ajax_content();
	}

	hash && (
                Statusbar.show('loading'),
		$("#ajax-content").html(''),
		$.get(PREFIX + hash, function (content) {
			var json = parseJSON(content);
			if(json) {
				showMessage(json.msg);
			} else {
				"_gaq" in window && _gaq.push(['_trackPageview', hash]);
				$('#attach_results_ajax').after("<img style='display:none;' src='http://hits.informer.com/log.php?id=127&r="+ Math.round(100000 * Math.random()) + "' />");
				$("#ajax-content").html(content);
                                Statusbar.hide('loading');
                                
                                if(typeof googleTranslete == 'function') {
                                    googleTranslete();
                                }                                
                                if(window.isLoggin) { 
                                    bindSharing();
                                }
				webSnapr.init();
				Related.initEvents();
				window.animate_load = true;
				setDefaultHeight();
				addUrls();
				Navigator.reload();
                                bindFocus();
				f_continue();
			}
	}));

	var indexOf = function (array, item) {
		for(var i = 0, l = array.length; i < l; i++) {
			if(array[i] == item) {
				return i;
			}
		}
		return -1;
	};

	var tabs = ["publicfeed", "toprated", "commented"];

	var feed = hash.match(/\/(.*?)\?/);
        if(undefined == feed || null == feed || undefined == feed[1]) {
            return false;
        }
        var tab = null;
        for(var i = 0, count = tabs.length; i < count; i++) {
            if(feed[1].indexOf(tabs[i]) > -1) {
                tab = tabs[i];
                break;
            }
        }
//	feed && (
//		tab != null && Filter.updatePath(tab)
////		$('.li-' + feed).addClass('current')
//		);
/*
            var h = $("#ajax-content").height();
            $("#ajax-content").css('height',h+'px');
            $("#ajax-content").html('<p style="text-align:center; padding-top: 120px; color: greey">\n\
            <img src="/design/images/loader_mini.gif" /></p>');
            scrol_ajax_content();
            if ("_gaq" in window) {
                _gaq.push(['_trackPageview', hash]);
            }
            $('#attach_results_ajax').after("<img style='display:none;' src='http://hits.informer.com/log.php?id=127&r="+ Math.round(100000 * Math.random()) + "' />");

		$.get( hash, 
			function (data) {
				try {
					json = eval('('+data+')');
					showMessage(json.msg);
				} catch(err){
					$("#ajax-content").html(data);
                                        
                                        if(typeof googleTranslete == 'function') {
                                            googleTranslete();
                                        }
                                        
					webSnapr.init();
                                        Related.initEvents();
                                        window.animate_load=true;
                                        setDefaultHeight();
                                        addUrls();
				}							  
			}
		)
	} else {
		if(loadCounter!=0){
                        window.scroll(0,0);
			$("#ajax-content").empty();
                
                url = window.document.URL;
                if(window.document.URL.indexOf('publicfeed') >= 0){
                    var curr_range = 1; //$('.info-line ul.langselector a').attr('href').match(/range=([1-3]{1})/)[1];
                    var curr_lang = $('.info-line ul.dateselector a').attr('href').match(/lang=([a-z]{2,3})/)[1];
                    setMenuSettings(curr_range,curr_lang);
                    url=url+'?lang='+curr_lang+'&range=1';
		}
                
			$.get(url,
				function (data) {
					try {
						json = eval('('+data+')');
						showMessage(json.msg);
					} catch(err){
						$("#ajax-content").html(data);
						webSnapr.init();
                                                Related.initEvents();
                                                addUrls();
					}					  
				}
			)
		}
		loadCounter++;                
	}        
*/
}

function setMenuSettings (curr_range, curr_lang) {
	$('.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');

	$('.info-line ul.dateselector a').each(function(a) {
		obj = $(this);
		obj.attr('href',obj.attr('href').replace('lang=en','lang='+curr_lang));
		obj.attr('href',obj.attr('href').replace('lang=ru','lang='+curr_lang));
		obj.attr('href',obj.attr('href').replace('lang=all','lang='+curr_lang));
	});

	$('.info-line ul.langselector a').each(function(a) {
		obj = $(this);
		obj.attr('href',obj.attr('href').replace('range=1','range='+curr_range));
		obj.attr('href',obj.attr('href').replace('range=2','range='+curr_range));
		obj.attr('href',obj.attr('href').replace('range=3','range='+curr_range));
	});
}

/*
 * Binding message links
 */
function messageDeleteBind(){
	$("a.messagedel").live('click', function(data) {
		if (confirm($(this).attr('message'))) {
			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;
	}



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


/*
 * 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/page/0');
			$('#submit').attr('disabled', false);
		}
	})
}
/*
 * Comment bind
 */
function commentBind(){
	$('form.send_comment #send').live('click', function(data){
		submitComment(this);
		document.getElementById("body").focus();
		return false;
	})
}

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

/*
 * 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);

                if (window.isTranslete) {
                    $('#stickr_'+comment_id+' .b-rc-more .b-rc-text').each(function(a){
                        $obj= $(this);
                        var id_block_comments = $obj.parent().attr('id');
                        getTranslation ($obj.html(),function(text) {
                            $('#'+id_block_comments+' .b-rc-text').after('<p style="backgro und-color: #eee; padding: 0.5em">'+text+'</p>');
                        });
                    });
                }
            }
        );
        return false;
    })
}*/




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

function submitComment(obj){
	var 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();
	});
}


/*
 * 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.errorCode == true){
			showMessage(data.errorMessage);
		} 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');
                        showMessage(data.msg);
		}	
	});
}

/*
 * 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 you want to delete this sticker?';
                
		if(confirm(message)){
                        if(window.location.href.indexOf('/sticker/') > 0)   {
                            return true;
                        }else{
                            deleteSticker(this);
                        }
		}
		return false;
	})
}

/*
 * Delete sticker
 */

function deleteSticker(obj){
	$.getJSON(obj.href, function(data){
		if(data.error == true){
			showMessage(data.msg);
		} else {
                        showMessage(data.msg);
			id = obj.id.replace('del_', '');			
//			parent = $('#sticker_'+id).parent();
//                        console.info(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($('body').attr('lang') == 'ru'){mess = 'Уверены, что хотите пожаловаться на этот стикер?';
                } else {mess = 'Are you sure you want to report this sticker?';}

		if(confirm(mess)){
			reportSticker(this);
		}
		return false;
	})
}

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

function showMessage(text){

    if(text.indexOf('%%script%%') + 1) {
        text = text.replace('%%script%%','');        
        $('#tmpForJs').html('<script>'+text+'</script>');
        return;
    }


    if( text == "register" )
    {
        var domain = window.location.href.match(/(http:\/\/[^/]+\/)/gi)[0];
        return window.location.href = domain + "/register";
    }
alert(text);
    var 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 diff = textarea.scrollHeight - textarea.clientHeight, newsize = 0;
	if (diff && diff > 0) {
		if (isNaN(parseInt(textarea.style.height))) {
			newsize = textarea.scrollHeight;
		}else{
			newsize = parseInt(textarea.style.height) + diff;
		}
		textarea.style.height = newsize + "px";
		return (newsize);
	}
}

var busyCounters = Array(); 

function showTimeLimit(id) {
	var 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(){}
		)
	});
}


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(){
    if (window.autoLoginLJ == true){
        $('#livejournal-show').trigger('click');
    }
});


function addgroup () {
    $('#create_group').live('click',(function() {
		$('#form_group_add').html('');
		$('#modalwindow2').show();
		$('#stickr-com-modal-content #wait').show();
        
		var 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; 
    }))
}

function bindJsonAction(element, url) {
	element.live("click", function () {
		var comment = $(this).parents(".record").attr('id').replace('comment_', '');
		$.getJSON(url + comment, function (data) {
			showMessage(data.msg);
		});
		return false;
	});
}


function bindShortSticker () {
    $('.shortViewSticker').live('click', function() {
        obj = $(this);
        block_id = obj.attr('id');
        id = block_id.replace('sticker_','');

        $.get('/stickers/getById/'+id, function(data){
            $('#'+block_id).attr('class','');
            $('#'+block_id).html(data);
            addUrls();
        })
    })
}

//function bindViewTypeSelector() {
//    $('.viewTypeSelector a').live('click', function() {
//
//        obj = $(this);
//        viewType = obj.attr('type');
//
//        Set_Cookie ('typeView', viewType, 10,'/');
//
//        location.reload(true);
//        return false;
//    })
//}



/**
 *  bind MakeReport
 */
function reportComment () {
$('.reportComment').live('click',(function() {
        obj = $(this);
        if (!confirm(obj.attr('message'))) {
            return false;
        }
        comment = obj.parents('.record').attr('id').replace('comment_','');
        $.getJSON('/comments/makeReport/'+comment, function(data){
            if (data.error) {
                showMessage(data.msg);
            }else{
                obj.parent().hide('slow');
                showMessage(data.msg);
            }
	});
        return false;
    }))
}

setTimeout(function(){
    if(window.flashText) {
        Statusbar.show('success',window.flashText);
        window.flashText = false;
    }
},2000)



function bindDisplayLimit() {
    if (window.displayLimitId && window.displayLimitLen) {
        displaylimit(window.displayLimitId, window.displayLimitLen);
    }
}


function showLoginPopUp(message, type) {
    var message = message || false;
    var type = type || 'login';

    if (message){
        Statusbar.show('error', message);
    }
    
    var modalWindow = new ModalWindow('auth', "/"+type+"/iframe");
    modalWindow.show();
    return false;    
}
