if (Podfm == undefined) var Podfm = {};

function SetCookie(sName, sValue) {
  //setCookie('name', '23', '','/', 'mysite.com','')
  document.cookie = sName + "=" + escape(sValue) + "; expires=Tue, 14 Dec 2020 23:59:59 GMT; path=/; domain=podfm.ru";
}


function GetCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}


var messages = {};
messages.login = {
    "login":"логин",
    "password":"пароль",
    "rememberMe":"запомнить меня",
    "submit":"войти",
    "forgotPassword":"забыли пароль",
    "formLegend":"Введите свой логин и пароль"
};
messages.loginErrors = {
    "illegal_login_password":"Неправильный логин или пароль",
    "illegal_email":"Неправильный email"
};
messages.regErrors = {
    "illegal_login":"Логин не соотвествует требованиям",
    "illegal_password":"Введите пароль",
    "illegal_password_repeat":"Пароль не совпадает с его повтором",
    "illegal_email":"Введите корректный email"
};

Podfm.SliderController = function() {
    this.init = function() {

	 if($("div.scrollable")) {
        $("div.scrollable").scrollable({
            vertical:true,
            keyboard:false,
            size: 10,
            speed:400,
            easing: "linear"
        }).circular().mousewheel();

        $("div.scrollable-small").scrollable({
            vertical:true,
            keyboard:false,
            size: 3,
            speed:400,
            easing: "linear"
        }).circular().mousewheel();
    }
	}
}

function hideSpecialPlayer() {
    $('#topPlayer').remove();
    $('#searchtd').remove();
    $('#searchtd_content div.roundsrch').addClass('full');
    html = $('#searchtd_content').html();
    $('#searchtd_content').remove();
    $('#logosearchtd').attr('colspan', 5);
    $("div.logo").after(html);
    SetCookie('noShowPlayerTop', 1);
}

var _callbackAddFriend = function(response) {
    if(response.success) {
        $('a.friend').text('Удалить из друзей');
        $('a.friend').attr('mode', 'delete');
    }
}

var _callbackDelFriend = function(response) {
    if(response.success) {
        $('a.friend').text('Добавить в друзья');
        $('a.friend').attr('mode', 'add');
    }
}


var controlFriend = function(event) {
    var link = $(event.target);
    if(link.attr('mode')=='add') {
        var qString = 'a_todo=add_friend&user_id=' + link.attr('userid');
        $.get("/ajax.php?", qString, _callbackAddFriend, "json");
    }
    else {
            if(confirm("Удалить пользователя из друзей?")){			
            var qString = 'a_todo=del_friend&user_id=' + link.attr('userid');
            $.get("/ajax.php?", qString, _callbackDelFriend, "json");
        }
    }
    return false;
}

var _callbackUnsubscribeLent = function(response) {
    if(response.success) {
        $('#slent_' + response.id).remove();
    }
}

var controlUnsubscribeLent = function(event) {
    if(confirm('Вы уверены, что хотите отписаться от этой ленты?')) {
        var link = $(event.target);
        link.unbind('click');
        var qString = 'a_todo=del_sub&type=edit&lent_id='+ link.attr('lid');
        $.get("/ajax.php?", qString, _callbackUnsubscribeLent, "json");
        return false;
    }
}

var _selectAllLetters = function(event) {
    var ch = $(event.target);
    if(ch.attr('checked')) {
        $('td.selmess input').attr('checked',true);
        $('#letters').css('backgroundColor', '#f7f7f7');
    } else {
        $('td.selmess input').attr('checked', false);
        $('#letters').css('backgroundColor', '#ffffff');
    }
}

var _selectLetter = function(event) {
    if($(event.target).attr('href')) return true;
    

    var tr = $(event.target).parents('tr:first');
    
    if($(event.target).attr('type')=='checkbox') {
        c = $(event.target);
        if(c.attr('checked')) {
            c.attr('checked',true);
            tr.css('backgroundColor', '#f7f7f7');

        } else {
            c.attr('checked',false);
            tr.css('backgroundColor', '#ffffff');
        }
    }
    else {
        var c = tr.find('input:first');
        c = $('#' + c.attr('id'));
        if(c.attr('checked')) {
            c.attr('checked',false);
            tr.css('backgroundColor', '#ffffff');
        } else {
            c.attr('checked',true);
            tr.css('backgroundColor', '#f7f7f7');
        }
    }
}

var _callbackSubscribe = function(response) {
    $('#subemail').val('');
    if(response.success) {
        $('#submessage').html('<br>Вы успешно подписаны на рассылку!');
    }
    else {
        $('#submessage').html('<br>Вы уже подписаны на рассылку!');
    }
    $('#subsbut').val('Да');
}

function subscribe() {
    if (!emailIsValid($('#subemail').val())) {
        $('#submessage').html('<br>Некорректный email');
    } else {
        $('#subsbut').val('...');
        var qString = 'a_todo=subscribe&email=' + $('#subemail').val();
        $.get("/ajax.php?", qString, _callbackSubscribe, "json");
    }
}





var _callbackSubscribeLent = function(response) {
    $('#subemail2').val('');
    if(response.success) {
        $('#submessage2').html('<br>Внимание! На Ваш email выслана просьба подтвердить подписку. Только после подтверждения Вы начнете получать уведомления.');
    }
    else {
        $('#submessage2').html('<br>Вы уже подписаны на эту ленту!');
    }
    $('#subsbut2').val('Да');
}

function subscribeLent() {
    
    if (!emailIsValid($('#subemail2').val())) {
        $('#submessage2').html('<br>Некорректный email');
    } else {
        $('#subsbut2').val('...');
        var qString = 'a_todo=subscribe&email=' + $('#subemail2').val() + '&lent=' + $('#lentid').val();
        $.get("/ajax.php?", qString, _callbackSubscribeLent, "json");
    }
}

var _callbackShow =  function(response) {
    if(response.success) {
        
        $('#listpods').html(response.text);
    }
    else {
        return;
    }
}

var _showpods = function(event) {
    var td = $(event.target);
    var type;
    if(td.attr('class')=='left_tab') {td.attr('class', 'left_tab_sel');
        $('td.right_tab_sel').attr('class', 'right_tab');
        type='cat';}
    if(td.attr('class')=='right_tab') {td.attr('class', 'right_tab_sel'); type='all';
        $('td.left_tab_sel').attr('class', 'left_tab');
    }
    $('#listpods').html('<center><br><table><tr><td><img src=/images/load.gif align=top width=24 height=24></td><td valign=middle style="padding-top:5px;">&nbsp; <i>Идет загрузка...</i></td></tr></table></center>');
    $.get("/ajax.php?", 'type=' + type, _callbackShow, "json");
}

$(document).ready(function() {
    var psc = new Podfm.SliderController();
    psc.init();
    
    if($('a.friend'))	
    $('a.friend').live('click', controlFriend);
	if($('a.unsubscribe_lent'))
    $('a.unsubscribe_lent').live('click', controlUnsubscribeLent);
    if($('#ch'))
    $('#ch').bind('click', _selectAllLetters); 

    if($('tr.mess'))	
    $('tr.mess').bind('click', _selectLetter);

    $('.left_tab').live('click', _showpods);
    $('.right_tab').live('click', _showpods);

  if(0)
  $("form").keypress(function (e) {
         if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
             var f = $(this);
             var sub = f.find(":submit");
             if(sub && sub.attr('type') == 'submit') {
                    f.submit();
             }
             else {
                 var sub = f.find(".button");
                 if(sub) {
                    sub.focus().click();
                }
             }
             return false;
         } else {
             return true;
         }
     });

});

function SetColor() {
    var  str =  document.getElementById("srch").value;
    if( str.length>2){
        $('#srch').css('border','2px solid #33cc33');
    }
    else {
        //$('#srch').css('border','2px solid #d2293f');
        $('#srch').css('border','1px solid #455260');
    }
}

function emailIsValid(email) {
    re2 = new RegExp("^([a-zA-Z0-9_!\"\#\$\%\&\'\*\.\+\/\=\?\{\|\}\~\`-]+?)@([a-zA-Z0-9_-]+\.){1,3}([a-zA-Z]){2,4}$");
    return re2.test(email);
}

_callbackAddVote = function(response) {
    if(response.success){
        eval(response.evalcode.toString());
    } else {
        ShowBaloon($('#' + response.key), response.error);
    }
}

function add_vote(pod_id,user_id,vote){
    qString = 'a_todo=add_vote&pod_id='+pod_id+'&pod_user_id='+user_id+'&vote='+vote;
    $.post("/ajax.php?", qString, _callbackAddVote, "json");
    return false;
}


function check_link() {
	$('#link_progress').hide();
    link = $('#file_link').toLowerCase();
	if(link.blank()){
		ShowBaloon(link, 'Укажите ссылку на файл');
		return false;
	}
	$('#link_progress').show();
	return true;
}

function deleteField(a) {
var contDiv = a.parentNode;
contDiv.parentNode.removeChild(contDiv);
countOfFields--;
return false;
}

function addField() {
if (countOfFields >= maxFieldLimit) {return false;}
countOfFields++;
curFieldNameId++;
var disabled = (curFieldNameId==1)?" disabled":"";
var space = (curFieldNameId<10)?"&nbsp;&nbsp;":"";
var div = document.createElement("div");
div.innerHTML = "<div class=form_line><div style='width: 15px; text-align: right; float: left;'><b>"+curFieldNameId+"</b></div>&nbsp;<input type=file name=image_"+curFieldNameId+" id=image_"+curFieldNameId+" class=file_input size=40>&nbsp;&nbsp;<input "+disabled+" type=button value='&#150;' title='Удалить поле' onclick='deleteField(this);' class=buttons> <input type=button value='+' title='Добавить еще одно поле' onclick='addField();' class=buttons></div>";
document.getElementById("files_div").appendChild(div);
return false;
}

function popup(url, width, height)
{
  wx = (screen.availWidth - width)/2;
  wy = (screen.availHeight - height)/2;

  return window.open(url, "popup", "width="+width+",height="+height+",status=no,resizable=0,scrollbars=1,toolbar=no,menubar=no,left="+wx+",top="+wy);
}

function expand(Item) {
	dom = (document.getElementById);
	ie4 = (document.all);
	if (dom || ie4) {
	  var currElement = (dom) ? document.getElementById(Item) : document.all[Item];
	  currElement.style.display = (currElement.style.display == 'none')? 'block' : 'none';
	  return false;
	}
	else return true;
}


function imgOpen(imgURL,Title,w,h)
{
	w = 0 + Number(w);
	h = 0 + Number(h);

	hiddenImg= new Image();
	hiddenImg.src= imgURL;
	if(w>0 && h>0)
	{
		imgWidth = w;
		imgHeight = h;
	}
	else
	{
		imgWidth = hiddenImg.width;
		imgHeight = hiddenImg.height;
	}


	var imgWndw=window.open('','_blank','width='+imgWidth+',height='+imgHeight+',toolbar=no,menubar=no,location=no,status=no,'+'resizable=yes,scrollbars=no, top=300,left=400');
	var imgTitle=(Title)?Title:imgURL+": "+imgWidth+'x'+imgHeight;
	with (imgWndw.document)
	{
	  open();
	  write('<ht'+'ml><he'+'ad><ti'+'tle>'+ imgTitle +'</ti'+'tle>'+'</he'+'ad><bo'+'dy leftmargin="0" topmargin="0" '+'rightmargin="0" bottommargin="0" marginwidth="0" '+'marginheight="0"><a href="javascript:history.go(0);" onclick="window.close();"><img src="'+imgURL+'" width="'+imgWidth+'" height="'+imgHeight+'" border="0" alt="'+imgTitle+'"></a></bo'+'dy></ht'+'ml>');
  	close();
	}
	return false;
}

function reloadCaptchaReg() {
var randomnumber=Math.floor(Math.random()*11);
$('#captcha_img').attr('src', '/cap/index.php?' + randomnumber);
}
 

$(document).ready(function() {

        $('.rss_link').hover(function(event) {
            var _e = $('#qr_code');

            var a = $(this);
	     $("#qr_code a:first").attr('href', a.attr('href'));
		 $(".qimg img").attr('src', '/images/load.gif');

	     $(".qimg img").attr('src', 'http://chart.apis.google.com/chart?cht=qr&chs=150x150&choe=UTF-8&chld=H&chl=' + a.attr('href'));

 	     var position = a.position();
            _e.css('top', position.top-9);
            _e.css('left', position.left-12);
            _e.show();

        }, function(event){
         $('#qr_code').hide();
    });

        $('#qr_code').hover(function(){
            $(this).show()
        }, function() {$(this).hide()});


    });