/*Login/logout*/
function loginSubmit() {
	$("#loginform").ajaxSubmit({success: function (responseText, statusText)  {$("#header .loginbox").before(responseText).remove();}});
	return false;
}

/*
function logout() {
    $("#login").load('/login.php?action=logout', { }, function () {
        Com.manageRem(); if($("#imp").html() != null) location.href="/";	
    });
}*/
/*Rating*/
/*function rateSubmit() {
	$("#vote-echo").html(" ");
    if (!$("input.star:checked").length) alert('Вы не поставили оценку! Пожалуйста, поставте оценку и попробуйте снова.');
    else $("#rateForm").ajaxSubmit({success: function (responseText, statusText) { $("#vote-echo").html(responseText); if ($("#voteResAv").html() != null) $("#voteAv").html($("#voteResAv").html()); if ($("#voteResNum").html() != null) $("#voteNum").html($("#voteResNum").html()); }});
}
*/

function htmlspecialchars(text)
{
   var chars = Array("&", "<", ">", '"', "'");
   var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "'");
   for (var i=0; i<chars.length; i++)
   {
       var re = new RegExp(chars[i], "gi");
       if(re.test(text))
       {
           text = text.replace(re, replacements[i]);
       }
   }
   return text;
}

function redirect(page, data)
{
    $('html').append('<div id="errorsBox">' +
            '<h1>'+(data.error?'Ошибка!':'')+ '<span style="float:right">&nbsp;</span></h1>'+(data.error?data.error:data.notice)+
    '<br /><br /><a href="javascript:javascript:history.go(-1)"><b>назад</b></a></div><div id="overlay"></div>');
    $("#overlay").show().fadeTo("slow",0.5).click(function(){ hideThat(); });
    $("#errorsBox").show().fadeTo("slow",0.8);
    function hideThat() {
        $("#overlay").fadeOut("slow",function(){$(this).hide();});
        $("#errorsBox").fadeOut("slow",function(){$(this).hide();});

    }
    var k=3;
    $("#errorsBox > h1 > span").html(Number(k--));
    setTimeout(function(){hideThat();window.location = page;},k*1000);
    setInterval(function(){if (k) $("#errorsBox > h1 > span").html(Number(k--));},1000);
}


function parseData (data) {

    if (data['error']) warn(data['error'],'error');
    if (data['notice']) warn(data['notice'],'notice');
}

/*function warn (warn) {
    if (!$('#warn').html()) {
        $('<div id="warn">'+warn+'</div>').appendTo('body').slideDown('normal');   
    } else $('#warn').html(warn).slideDown('normal');
    setTimeout(function () {$('#warn').slideUp("normal")},10000);
*/
function warn(warn,type)
{
    $('#slayer').fadeIn(1000);
    $('<div id="warn" style="display:none;" class="window '+type+'"><div class="ins_text"><div class="color"><div class="top"></div><div class="center"><div class="ntext">'+warn+'</div></div><div class="bot"></div></div></div><a class="ok_bttn" href="javascript:closeWarn();"></a></div>').appendTo('body').fadeIn(1000);
    window.scrollTo(0,0);
    $('#slayer').click(closeWarn);
    $(document).keypress(closeWarn);
}

function closeWarn()
{
    $('#warn').fadeOut(300).remove();
    $('#slayer').fadeOut(300);
}
function slide (s, id) {
	var tmp=$(s).attr('rel','title');
	$(s).attr('rel',$(s).html());
	$(s).html(tmp);
	$(id).slideToggle('slow');
}

function suggestions(id,func,li,extra) {
	var extr = extra || new Object();
	extr['func'] = func;
	$(id).autocomplete("/suggestions.php", {
		delay:10,
	    matchContains:1,
	  	formatItem:li,
	    maxItemsToShow:10,
	    extraParams:/*{func:func}*/extr
	}); 
}

function updateExtra(id,func,li,extra)
{
	$(id).flushCache();
	var extr = extra || new Object();
	extr['func'] = func;
	$(id).setOptions({extraParams:extr});
}



function searchSugg() {
	$('#search').autocomplete("/suggestions.php", {
		delay:10,
	    matchContains:1,
	  	formatItem:li2c,
	    maxItemsToShow:10,
	    extraParams:{func:'getSugg'}
	}); 
}

function licR (row, i, num) {
  return (parseInt(row[1])>0)?'<span style="width:100%;border-bottom:1px #fff dotted">'+row[0]+'</span>':row[0];
}

function lic (row, i, num) {
  return row[0];
}

function li2c (row, i, num) {
  return row[0] + " <span class='qnt'>("+row[1]+")</span>";
}

function li3c (row, i, num) {
  return row[0] + "<br /> <span class='qnt'>"+row[1]+" "+row[2]+"</span>";
}

$(document).ready(function(){
    $('a.actor').mouseover(function(){
        var offset=$(this).offset();
        var src=baseURL+'images/actors/small_'+$(this).attr('rel');
        if (typeof $('#actor-frame')[0] == 'undefined') $('<div id="actor-frame"></div>').appendTo('body'); 
        $('#actor-frame').css({'top':offset.top+$(this).height(), 'left':offset.left+Math.round($(this).width()/4)}).html('<img src="'+src+'" />').show();
    }). mouseout(function(){
        $('#actor-frame').hide();
    });
    $('a.serial').mouseover(function(){
        var offset=$(this).offset();
        var src=baseURL+'images/posters/small_'+$(this).attr('rel');
        if (typeof $('#serial-frame')[0] == 'undefined') $('<div id="serial-frame"></div>').appendTo('body'); 
        $('#serial-frame').css({'top':offset.top+$(this).height(), 'left':offset.left+Math.round($(this).width()/4)}).html('<img src="'+src+'" />').show();
    }). mouseout(function(){
        $('#serial-frame').hide();
    });
});

function getBrowserInfo() {
 var t,v = undefined;
 if (window.opera) t = 'Opera';
 else if (document.all) {
  t = 'IE';
  var nv = navigator.appVersion;
  var s = nv.indexOf('MSIE')+5;
  v = nv.substring(s,s+1);
 }
 else if (navigator.appName) t = 'Netscape';
 return {type:t,version:v};
}

function bookmark(a){
 var url = window.document.location;
 var title = window.document.title;
 var b = getBrowserInfo();
 if (b.type == 'IE' && 7 > b.version && b.version >= 4) window.external.AddFavorite(url,title);
 else if (b.type == 'Opera') {
  a.href = url;
  a.rel = "sidebar";
  a.title = url+','+title;
  return true;
 }
 else if (b.type == "Netscape") window.sidebar.addPanel(title,url,"");
 else alert("Нажмите CTRL-D, чтобы добавить страницу в закладки.");
 return false;
}

/**
 * для индексной страницы
 */


/**
  *      Новости
 */

var scrollContent, scrollbar;
$(function() {

//compare the height of the scroll content to the scroll pane to see if we need a scrollbar
var difference = $('#scroll-content').height()-$('#scroll-pane').height();//eg it's 200px longer
scrollContent = $('#scroll-content');

    
if(difference>0)//if the scrollbar is needed, set it up...
{
   var handleHeight = 75; //Math.round((1-proportion)*$('#scroll-pane').height());//set the proportional height - round it to make sure everything adds up correctly later on

   //set up the slider
   scrollbar = $('#slider-vertical').slider({
      orientation: 'vertical',
      min: 0,
      max: 100,
      value: 100,
      slide: function(event, ui) {//used so the content scrolls when the slider is dragged
		 var topValue = -((100-ui.value)*difference/100);
         $('#scroll-content').css({marginTop:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
      },
      change: function(event, ui) {//used so the content scrolls when the slider is changed by a click outside the handle or by the mousewheel
         var topValue = -((100-ui.value)*difference/100);
         $('#scroll-content').css({marginTop:topValue});//move the top up (negative value) by the percentage the slider has been moved times the difference in height
      }
   });

    $('#slider-vertical').removeClass('ui-widget-content').find('a').addClass('scroller');
   //set the handle height and bottom margin so the middle of the handle is in line with the slider
   $(".ui-slider-handle").css({height:handleHeight,'margin-bottom':-0.5*handleHeight});

   var origSliderHeight = $("#slider-vertical").height();//read the original slider height
   var sliderHeight = origSliderHeight - handleHeight ;//the height through which the handle can move needs to be the original height minus the handle height
   var sliderMargin =  (origSliderHeight - sliderHeight)*0.5;//so the slider needs to have both top and bottom margins equal to half the difference
   $(".ui-slider").css({height:sliderHeight,'margin-top':sliderMargin});//set the slider height and margins

}//end if

$(".ui-slider").click(function(event){//stop any clicks on the slider propagating through to the code below
   	event.stopPropagation();
   });


$("#slider-wrap").click(function(event){//clicks on the wrap outside the slider range
	  var offsetTop = $(this).offset().top;//read the offset of the scroll pane
	  var clickValue = (event.pageY-offsetTop)*100/$(this).height();//find the click point, subtract the offset, and calculate percentage of the slider clicked
	  $("#slider-vertical").slider("value", 100-clickValue);//set the new value of the slider
});

//additional code for mousewheel
$("#scroll-pane,#slider-wrap").mousewheel(function(event, delta){
	var speed = 5;
	var sliderVal = $("#slider-vertical").slider("value");//read current value of the slider

	sliderVal += (delta*speed);//increment the current value

	$("#slider-vertical").slider("value", sliderVal);//and set the new value of the slider

	event.preventDefault();//stop any default behaviour
});

});



var bNBlock = false;

function newsUp()
{
    if(!bNBlock)
    {
        bNBlock = true;
        if(parseInt(scrollContent.css('marginTop')) >= -128)
        {
            scrollContent.animate({'marginTop':0},{duration:200,complete:function(){bNBlock=false;}});
            scrollbar.slider('value',100);
        }
        else
        {
            scrollContent.animate({'marginTop':"+=128px"},{duration:500,complete:function(){bNBlock=false;}});
            scrollbar.slider('value',scrollbar.slider('value')+16.667);
        }
    }
}

function newsDown()
{
    if(!bNBlock)
    {
        bNBlock = true;
        if(-parseInt(scrollContent.css('marginTop')) >= parseInt(scrollContent.height())-4*128)
        {
            scrollContent.animate({'marginTop':(-parseInt(scrollContent.height())+3*128).toString()+'px'},{duration:200,complete:function(){bNBlock=false;}});
            scrollbar.slider('value',0);
        }
        else
        {
            scrollContent.animate({'marginTop':"-=128px"},{duration:500,complete:function(){bNBlock=false;}});
            scrollbar.slider('value',scrollbar.slider('value')-16.667);
        }
    }
}

function trunc(str, max_length)
{
    if(str.length<=max_length)
    {
        return str;
    }
    else
    {
        return str.substr(0,max_length)+'...';
    }
}






function showTopSerial(sid, tab)
{
    var active = $(tab).parent().parent().find('.active:eq(0)');

    if (active == $(tab))
        return false;
    ajaxStart($('.tops .l .timg'))
    $.post('/ajax/get_serial.php',{id:sid},function(serial){
        $('.tops .timg').html('<a href="/'+serial.eng_title+'.html"><img src="images/posters/478x381/'+serial.foto+'" alt="'+serial.title+'"/></a>'+
            '<div class="tr_block">'+
                '<a href="/'+serial.eng_title+'.html" class="tlink">'+trunc(serial.title,25)+'</a>'+
                '<a href="/'+serial.eng_title+'.html" class="details">Подробнее</a>'+
            '</div>'+
            '<div class="tr round"></div>');

        active.removeClass('active');
        $(tab).addClass('active');
        ajaxStop();
    },'json');
}

function showTopActor(aid, tab)
{
    if($(tab).attr('class')!='number')
    {
        tab = $(tab).parent().find('.number').get(0);
    }
    var active = $(tab).parent().parent().parent().find('.active:eq(0)');

    if (active == $(tab))
        return false;

    ajaxStart($('.tactors .selected'));
    $.post('/ajax/get_actor.php',{id:aid},function(actor){
        $('.tactors .selected').html('<a href="/actor/'+actor.eng_title+'.html"><img src="images/actors/295x381/'+actor.foto+'" alt="'+actor.title+'"/></a>'+
                '<div class="tr_block"><a href="/actor/'+actor.eng_title+'.html">'+trunc(actor.title,20)+'</a></div>');

        $('.tactors .navblock').html('<a class="details" href="/actor/'+actor.eng_title+'.html">Подробнее</a>');

       

        active.removeClass('active');
        $(tab).addClass('active');
        ajaxStop();
    },'json');
}
/**
 * /для индексной страницы
 */


function ajaxStart(container)
{
    var ajaxLoader = '<div id="ajaxLoader" class="ajaxLoader" style="display:none;"></div>';
    container = container ? container : $('body');
    container.prepend(ajaxLoader);
    $('#ajaxLoader').fadeIn(100);
}

function ajaxStop(){
    $('#ajaxLoader').fadeOut(200);
    $('#ajaxLoader').remove();
};

var sid = undefined, aid = undefined, uid = undefined;

$(document).ready(function() {
    cuSel({changedEl: "select", visRows: 5, scrollArrows: true});
});
function min(a,b)
{
    return (a<b?a:b);
}

$(document).ready(function(){   // добавление поста
    $('.markItUp-small').markItUp(myBbcodeSettings);
    $('.markItUp-small').wrap('<div class="tarea small" />').before('<div class="ltop"><div class="rblock"></div></div>').after('<div class="lbot"></div>');

    $('.markItUp-large-rounded').markItUp(myBbcodeSettings);
    $('.markItUp-large-rounded').wrap('<div class="tarea" />').before('<div class="ltop"></div>').after('<div class="lbot"></div>');

    $('.markItUp-large').markItUp(myBbcodeSettings);

    $('.markItUp-large, .markItUp-small, .markItUp-large-rounded').autoResize();
    $('.markItUpResizeHandle').remove();

    $('[name=act1],[name=act2]').change(function(){
        $('#mess_list').attr('action','/profile/action/'+$(this).val()+'/').submit();
    });

    if(info)
        parseData(info);
});

$(document).ready(function(){
    $('.iblock .left .slids .mult-fancy, .iblock .left .slids .tr_block').parent().mouseenter(function(){
        $('.tr_block',$(this)).delay(200).animate({
            opacity: 1,
            height: '30px'
        },100);
    });
    $('.iblock .left .slids .mult-fancy, .iblock .left .slids .tr_block').parent().mouseleave(function(){
        $('.tr_block',$(this)).delay(200).animate({
            opacity: 0,
            height: '0'
        },100);
    });
	
	$('.iblock').wrap("<div></div>");
	
});

window.onscroll = function () {
    if(window.scrollY>300) document.getElementById("up_bttn").style.display = '';
    else document.getElementById("up_bttn").style.display = 'none';
}
