	function addBookmark(url, title) 
	{ 
		if (!url) 
			url = location.href; 
		if (!title) 
			title = document.title;
		//Gecko 
		if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) 
			window.sidebar.addPanel (title, url, ""); 
		//IE4+ 
		else if (typeof window.external == "object") 
			window.external.AddFavorite(url, title); 
		//Opera7+ 
		else if (window.opera && document.createElement) 
		{ 
			var a = document.createElement('A'); 
			if (!a) 
				return false; //IF Opera 6 
			a.setAttribute('rel','sidebar'); 
			a.setAttribute('href', url); 
			a.setAttribute('title',title ); 
			a.click();
		} 
		else 
			return false; 
		return true; 
	} 



function confirmUrl(url, msg) {
	ret = window.confirm(msg);
	if(ret == true) {
		window.document.location.href=url;
	}
}
function goUrl(url) {
		window.document.location.href=url;
}

function openWin(url,winName,winParams)	{	
	var theWindow = window.open(url,winName,winParams);
	if (theWindow)	{theWindow.focus();}
}
function open_photo(url){
	openWin(url,'single_gallery_object','left=100,top=100,width=750,height=600,toolbar=1,scrollbars=1');
}


function cnt_symbol(ta_id, counter_id, max_len, reverse) {
	var elem = document.getElementById(counter_id);
		if(elem) {
			var el2 = document.getElementById(ta_id);
			if(el2) {
				if(reverse) {
					elem.value = max_len - el2.value.length;
				}
				else {
				elem.value = el2.value.length;
				}
				if(el2.value.length ) {
				if(el2.value.length > max_len) {
					el2.value =  el2.value.substr(0,max_len-1);
				}
			}
		}
}
}
function trimSpaces(str) {
    while (str.substring(0,1) == ' ') str = str.substring(1);
    while (str.substring(str.length-1,str.length) == ' ') str = str.substring(0,str.length-1);
    return str;
}
function isEmail(str) {
	var supported = 0;
	if (window.RegExp) 
	{	var tempStr = "a";
		var tempReg = new RegExp(tempStr);
		if (tempReg.test(tempStr)) supported = 1;
	}
	if (!supported) 
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
	var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
	return (!r1.test(str) && r2.test(str));
}

function slider_show_image(url) {
	$('#img-large').hide();
        $('#img-large').attr('src', url);
    }
function slider_init() { 
		$('.b-photo-slider li a:first').children().addClass('sel');
		$('.b-photo-slider li a').click (function() {$('.b-photo-slider a img').removeClass('sel'); $(this).children().addClass('sel');});
		var slider_wrap = $('.b-photo-slider-i');
		var slider_wrapWidth = slider_wrap.width();
		var slider_ul = $('.b-photo-slider ul');
		var slider_li = slider_ul.children();
		var slider_liWidth = $( slider_li[0] ).width();
		var slider_liLength = slider_li.length;
		var slider_width = 0;
		for ( var i=0; i < slider_liLength ; i++) {
			slider_width += $( slider_li[i] ).width() + 6;
		}
		slider_ul.css( 'width', slider_width );

		var animating = false;
		var scroll_speed = 250;
		
		var slider_back = $( '.b-photo-slider .slider-btn_back');
		var slider_next = $( '.b-photo-slider .slider-btn_next');
		var slider_ulLeft = slider_ul.css('left').replace(/px/, "");
		
		slider_next.click(function() {
			if ( !animating ) {
			animating = true;
			offsetLeft = parseInt( slider_ul.css( "left" ) ) - ( slider_liWidth + 2 );
			slider_wrapWidth = slider_wrap.width();
			if ( offsetLeft + slider_ul.width() >= slider_wrapWidth - 30 ) {
				slider_back.addClass('slider-btn_back-act');
				slider_ul.animate({
					left: offsetLeft
				}, scroll_speed, function() {
					if ( parseInt( slider_ul.css( "left" ) ) + slider_ul.width() <= slider_wrapWidth  ) {
						slider_next.removeClass('slider-btn_next-act');
					}
					animating = false;
				});
			} else {
				animating = false;
			}
		}
		return false;
		});
		
		slider_back.click(function() {
			if ( !animating ) {
				animating = true;
				offsetRight = parseInt( slider_ul.css( "left" ) ) + ( slider_liWidth + 2 );
				if ( offsetRight + slider_ul.width() <= slider_ul.width() ) {
					slider_next.addClass('slider-btn_next-act');
					slider_ul.animate({
						left: offsetRight
					}, scroll_speed, function() {
						if ( parseInt( slider_ul.css( "left" ) ) == 0 ) {
							slider_back.removeClass('slider-btn_back-act');
						}
						animating = false;
					});
				} else {
					animating = false;
				}
			}
			return false;
		});
		
	}
function slider_init_mainphoto() {
		var mainPhoto = $('.main-photo');
		var mainPhotoImg = mainPhoto.children('img');
		mainPhoto.height(mainPhotoImg.height());
		mainPhotoImg.css('marginLeft', '-' + mainPhotoImg.width()/2 + 'px');
		mainPhotoImg.load(function() {mainPhotoImg.show();mainPhoto.height(mainPhotoImg.height());mainPhotoImg.css('marginLeft', '-' + mainPhotoImg.width()/2 + 'px');});
	}
	
function urlencode( str ) {  
     // URL-encodes string    
     var histogram = {}, tmp_arr = [];  
       var ret = str.toString();  
         
       var replacer = function(search, replace, str) {  
           var tmp_arr = [];  
           tmp_arr = str.split(search);  
           return tmp_arr.join(replace);  
       };  
         
       // The histogram is identical to the one in urldecode.  
       histogram["'"]   = '%27';  
       histogram['(']   = '%28';  
       histogram[')']   = '%29';  
       histogram['*']   = '%2A';  
       histogram['~']   = '%7E';  
       histogram['!']   = '%21';  
       histogram['%20'] = '+';  
         
       // Begin with encodeURIComponent, which most resembles PHP's encoding functions  
       //ret = encodeURIComponent(ret);  
       ret = ret   
       for (search in histogram) {  
           replace = histogram[search];  
           ret = replacer(search, replace, ret) // Custom replace. No regexing  
       }  
         
       // Uppercase for full PHP compatibility  
       return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {  
           return "%"+m2.toUpperCase();  
       });  
         
       return ret;  
}  

/*
moved to js.js
function open_photo(url){
		window.open(url,'mywin','left=100,top=100,width=750,height=600,toolbar=1,scrollbars=1');

	}

*/
function put_random_photo_stars(){
	var rs = $('.random_photo_stars');
	rs.each(function(num){
		rs.eq(num).html(photo_stars(parseInt(rs.eq(num).html())))
	})
}

function helper_attach_to__WTF(images,helper){ 
	images.each(function(num){
		images.eq(num).mouseenter(function(ev){
			var t = $(ev.target)
			var pos = t.position()
			helper.show()
			helper.width(t.width())
			helper.children('.text_helper').html(t.attr('title')+'<br>')
			helper.height(helper.children('.text_helper').height()+5)
			helper.css({'top':pos.top + t.height()-helper.height(),'left':pos.left})
		}).mouseleave(function(ev){
			helper.hide()
		})
	})
}	

function helper_attach_to(images,helper){
	images.each(function(num){
		images.eq(num).mouseenter(function(ev){
			var t = $(ev.target)
			var pos = t.position()
			var title_text = t.attr('title')
			if(title_text && title_text!=''){
				helper.show()
				helper.width(t.width())
				helper.children('.text_helper').html(t.attr('title'))
				var helper_height = t.height()/3 
				helper.height(t.height()/3)
				helper.children('.back_frame').height(helper_height)
				//helper = $('#helper')
				//alert(helper.children('.back_frame').eq(0).height())
				helper.css({'top':pos.top + t.height()*2/3+2,'left':pos.left+2})
				$('.gallery_active_list_photo').removeClass('gallery_active_list_photo')
				t.addClass('gallery_active_list_photo')
			}else{
				helper.hide()
			}
		})
	})
}


function vote(path, value) {
    if (value == 1) {
        $.post(path+'upvote/' , {} , onVoteSuccess, "json");
    }
    else if(value == 0) {
        $.post(path+'clearvote/' , {} , onVoteSuccess, "json");
    }
    else if(value == -1) {
        $.post(path+'downvote/' , {} , onVoteSuccess, "json");
    }
}
function onVoteSuccess(response) {
        if (response.success) {
            if ($("#object-score-"+response.id).text() == response.score.score)
            {
              //  voting_msg("Спасибо, Ваше мнение уже учтено.")
            } else {
                if ($("#voting-num-votes-"+response.id).text() == response.score.num_votes) {
                    $("#object-score-"+response.id).text(response.score.score);
                //    voting_msg("Спасибо, Ваш голос обновлен.")
                } else {
                    $("#object-score-"+response.id).text(response.score.score);
                    $("#voting-num-votes-"+response.id).text(response.score.num_votes);
                //    voting_msg("Спасибо! Ваше мнение учтено.")
                }
            }
            $("#user-vote-"+response.id).text("Ваш голос учтен.");
        }
}
function voting_msg(text) {
        $("#voting-msg").text(text);
        $("#voting-msg").animate({"opacity": "toggle"}, 1000).animate({"opacity": "toggle"}, 1000);
}

function showVote(){
	$('#window-vote').load();
}

function showVote2(){
	$('#window-vote2').load();
}

var user_tooltips = [];
function create_tooltip_text(content)
{
	return '<div class="b-user-popup"><div class="top"></div><div class="cont">'+content+'</div><div class="btm"></div></div>';

}

function user_link_over(e)
{
	$(e).attr('onmouseover', '').unbind();
	$(e).hover(function()
	{
		var that = $(this);
		x = that.position().left;
		var user_id = that.attr('rel');
		$('div.b-user-popup').remove();
		if (user_tooltips[user_id]) {
			var tt = $(user_tooltips[user_id]);
			tt.css('left',x+'px');
			that.append( tt );
		}
		else
		{
			var empty_tt = $(create_tooltip_text('<p class="load">Идет загрузка данных о пользователе</p>'));
			empty_tt.css('left',x+'px');
			that.append(empty_tt);
			
			jQuery.post(USER_TOOLTIP_URL, {user_id: user_id},
					function(data, status)
					{
						user_tooltips[user_id] = create_tooltip_text(data);
						var div = that.find('div.b-user-popup');
						if (div.length==0) return;
						div.remove();
						var tt = $(user_tooltips[user_id]);
						tt.css('left',x+'px');
						that.append(tt);
					}, 'html');
		}
	},
	function()
	{
		$('div.b-user-popup').remove();
	}).mouseenter();
}

// Popup
function show_popup($popup, $close_btn, timeout, $count_down)
{
	//Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();

	var mask = $('<div/>');
	mask.css(
	{
		'position': 'absolute',
		'z-index': 9000,
		'background-color': '#000', 
		'display': 'none',
		'top': 0,
		'left': 0,
		'width': maskWidth,
		'height': maskHeight
	});

	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();
	
	$popup.css(
	{
		'position': 'absolute',
		'display': 'none',
		'z-index': 9999
	});
	$popup.appendTo('body');
	//Set the popup window to center
	$popup.css('top',  $(window).scrollTop() + winH/2-$popup.height()/2);
	$popup.css('left', winW/2-$popup.width()/2);

	mask.appendTo('body');
	//transition effect		
	mask.fadeIn(400);	
	mask.fadeTo("slow", 0.8);	

	//transition effect
	$popup.fadeIn(800);

	var is_closed = false;
	
	//if close button is clicked
	$close_btn.click(function(e)
	{
		//Cancel the link behavior
		e.preventDefault();
		mask.hide();
		$popup.hide();
		mask.remove();
		$popup.remove();
		is_closed = true;
		return false;
	});		
	
	//if mask is clicked
	mask.click(function()
	{
		mask.hide();
		$popup.hide();
		mask.remove();
		$popup.remove();
		is_closed = true;
	});
	
	if (timeout)
	{
		var open_time = new Date().getTime();
		function count_down()
		{
			if (is_closed) return;
			var cur_time = new Date().getTime();
			var delta = timeout - Math.floor((cur_time - open_time) / 1000);
			if (delta <= 0)
			{
				mask.hide();
				$popup.hide();
				mask.remove();
				$popup.remove();
				is_closed = true;
			}
			else
			{
				$count_down.html(delta);
				setTimeout(count_down, 1000);
			}
		}
		count_down();
	}
}

// Notify user about new private message
$(function()
{
	$.getJSON(CHECK_NEW_MESSAGES_URL, function(data, textStatus, request)
	{
		if (!data) return;

		var popup = $('<div>У вас есть непрочитанные сообщения.<br/></div>');
		popup.css({'font-size': '16pt'})
		var read = $('<a target="_blank">Прочитать</a>');
		read.attr('href', data['read_url']);
		var close_btn = $('<a href="#">Пропустить</a>');
		popup.css(
		{
			'background': 'white',
			'padding': '70px 50px',
			'border': '3px solid black',
			'text-align': 'center'
		});
		read.css({'padding-right': 10});
		popup.append(read);
		popup.append(close_btn);
		var ps = $('<small>Это окно закроется через несколько секунд - </small>')
		var count_down = $('<span/>');
		ps.append(count_down);
		ps.css({'font-size': '11pt', 'color': 'gray'});
		popup.append($('<br/><br/>'));
		popup.append(ps);
		popup.append($('<br/>'));
		popup.append($('<a href="/accounts/profile/edit/" style="color: gray; font-size: 11pt;">Отключить это сообщение можно в настройках профиля.</a>'));
		show_popup(popup, close_btn, 20, count_down);
		$.getJSON(SET_DATE_OF_NOTIFYED_MESSAGE, {date: data['date']});
	});
});

