function getAjax(action, params, cash) {
    JsHttpRequest.query(
        '/ajax.php',
        {
            "action": action,
            "params": params
        },
        function(result, errors) {
            if (result) {
		eval(result['eval']);
            }
        },
        cash
    );
}

function changeEpisod(object, block) {
    $("#"+block).html(object);
}

function animateTopSerial() {
    if($("#top_serial_arrow_left").data('move')==1) {
	var right=$("#top_serial_line_inner").css("left");
	var re=/px/;
        right=right.replace(re, '');
	right*=1;
	
	if(right<0) {
	    $("#top_serial_line_inner").css("left", right+5);
	    setTimeout("animateTopSerial()", 10);
	}
    } else if($("#top_serial_arrow_right").data('move')==1) {
	var left=$("#top_serial_line_inner").css("left");
	var re=/px/;
        left=left.replace(re, '');
	left*=1;
	
	if(left>-2165) {
	    $("#top_serial_line_inner").css("left", left-5);
	    setTimeout("animateTopSerial()", 10);
	}
    }
}

function showLinks(list) {
    var html='';
    
    list1="";
    
    for(i=0; i<list.length; i++) {
	list1+="<li>";
	if(list[i].link) {
	    list1+="<a href='"+list[i].link+"' target='_blank'><b>";
	    if(list[i].title) {
		list1+=list[i].title;
	    } else {
		list1+=list[i].name;
	    }
	    list1+="</b></a>";
	    
	    if(list[i]['subtitle']) {
		if(list[i]['subtitle'][0]) {
		    list1+="<a href='/files/subtitle/"+list[i]['file_block']+"/"+list[i]['subtitle'][0]['subtitle']+"' class='subtitle'><b>"+list[i]['subtitle'][0]['lan']+"</b></a>";
		} else {
		    list1+="<a class='subtitle'></a>";
		}
		
		if(list[i]['subtitle'][1]) {
		    list1+="<a href='/files/subtitle/"+list[i]['file_block']+"/"+list[i]['subtitle'][1]['subtitle']+"' class='subtitle'><b>"+list[i]['subtitle'][1]['lan']+"</b></a>";
		} else {
		    list1+="<a class='subtitle'></a>";
		}
	    } else {
		list1+="<a class='subtitle'></a>";
		list1+="<a class='subtitle'></a>";
	    }
	    list1+="<br clear='all'>";
	} else {
	    list1+="<span title='Ссылка еще не готова'><b>";
	    if(list[i].title) {
		list1+=list[i].title;
	    } else {
		list1+=list[i].name;
	    }
	    list1+="</b></span>";
	}
	list1+="</li>";
    }
    
    html+='<ul><p class="title">Ссылки для закачки</p><p class="title2">Субтитры</p><br clear="all">'+list1+'</ul><br clear="all">';
    
    $("#links_list").html(html);
   
    //top.location.hash="links_list";
}

$(document).ready(function() {
    $(".tabs").show();
    
    $("a.preview").fancybox({
        'overlayShow': true
    });
    
    $("#show_country").click(function() {
        $("#country_menu_block").slideToggle();
    });
    
    $("#show_genre").click(function() {
        $("#genre_menu_block").slideToggle();
    });
    
    $("#search").focus(function() {
        if($(this).val()=='Поиск по сайту...') {
            $(this).val('');
        }
    });
    
    $("#search").blur(function() {
        if(!$(this).val()) {
            $(this).val('Поиск по сайту...');
        }
    });
    
    $(".link_list").click(function() {
        var block=$(this).parent();
        
        if($(this).data('flag')==1) {
            $(this).data('flag', 0);
            
            $(this).siblings().show();
            $(this).parent().children("textarea").hide();
        } else {
            $(this).data('flag', 1);
            
            $(this).siblings().hide();
            $(this).parent().children("textarea").show();
        }
        
        return false;
    });
    
    $("#order_name").change(function() {
        $.ajax({
            type: "POST",
            url: "/ajax.php", 
            data: { name: $("#order_name").val(), orig_name: $("#order_orig_name").val() }, 
            success: function(data) {
                if(data) {
                    $("#quick_order_table").html(data);
                    $("#quick_order").show();
                } else {
                    $("#quick_order").hide();
                }
            }
        });
    });
    $("#order_orig_name").change(function() {
        $.ajax({
            type: "POST",
            url: "/ajax.php", 
            data: { name: $("#order_name").val(), orig_name: $("#order_orig_name").val() }, 
            success: function(data) {
                if(data) {
                    $("#quick_order_table").html(data);
                    $("#quick_order").show();
                } else {
                    $("#quick_order").hide();
                }
            }
        });
    });
    
    $(".vk_link").mouseenter(function(e) {
        if(!$("#vk_file_name").text()) {
            var title=$(this).attr('title');
            $(this).attr('title', '');
            $("#vk_file_name").text(title);
            $("#vk_title").css({
                top: $(this).offset().top,
                left: $(this).offset().left+30
            });
            $("#vk_title").show();
        }
        
        return false;
    });
    $(".vk_link").mouseleave(function(e) {
        $(this).attr('title', $("#vk_file_name").text());
        $("#vk_title").hide();
        $("#vk_file_name").text('');
        
        return false;
    });
    
    $("#star_rating:not('.rated')").mouseenter(function(e) {
        if(!$.browser.msie) {
            if($("#star_rating").data('position')==undefined) {
                $("#star_rating").data('position', $(this).css('background-position'));
            }
        } else {
            if($("#star_rating").data('position-x')==undefined) {
                $("#star_rating").data('position-x', $(this).css('background-position-x'));
                $("#star_rating").data('position-y', $(this).css('background-position-y'));
            }
        }
    });
    $("#star_rating:not('.rated')").mouseleave(function() {
        if(!$.browser.msie) {
            $(this).css({
                'background-position': $("#star_rating").data('position')
            })
        } else {
            $(this).css({
                'background-position-x': $("#star_rating").data('position-x'),
                'background-position-y': $("#star_rating").data('position-y')
            })
        }
    });
    $("#star_rating:not('.rated')").live('mousemove', function(e) {
        var x=Math.ceil((Math.round(e.pageX)-Math.round($(this).offset().left))/30)*30-300;
        if(x>0) {
            x=0;
        }
        
        if(!$.browser.msie) {
            if($("#star_rating").data('position')!=undefined) {
                $(this).css({
                    'background-position': x+'px 0px'
                })
            }
        } else {
            if($("#star_rating").data('position-x')!=undefined) {
                $(this).css({
                    'background-position-x': x+'px',
                    'background-position-y': '0px'
                })
            }
        }
    });
    $("#star_rating").click(function(e) {
        if($(this).hasClass('rated')) {
            alert('Вы уже голосовали за этот сериал!');
        } else if($(this).hasClass('nologin')) {
            alert('Голосовать могут только зарегистрированные пользователи!');
        } else {
            $("#star_rating").addClass('rated');
            
            var x=Math.ceil((Math.round(e.pageX)-Math.round($(this).offset().left))/30);
            
            $.ajax({
                type: "POST",
                url: "/ajax.php", 
                data: { rating: x, serial: $("#serial_id").val() }, 
                success: function(data) {
                    if(data=='OK') {
                        var x=x*30-300;
                        
                        if(!$.browser.msie) {
                            $(this).css({
                                'background-position': x+'px 30px'
                            })
                            $("#star_rating").data('position', x+'px 30px');
                        } else {
                            $(this).css({
                                'background-position-x': x+'px',
                                'background-position-y': '30px'
                            })
                            $("#star_rating").data('position-x', x+'px');
                            $("#star_rating").data('position-y', '30px');
                        }
                        
                        alert('Спасибо, Ваш голос учтен. Рейтинг будет изменен в течении нескольких минут.');
                    } else {
                        alert('В настоящий момент голосование не доступно. Пожалуйста, попробуйте позже');
                    }
                }
            });
        }
    });
    
    $(".order_up").click(function() {
        var user=$(".sms_user_id");
        if(!$(user[0]).text()) {
            alert('Голосовать могут только зарегистрированные пользователи!');
        } else {
            var id=$(this).attr('id');
            var re=/order_/;
            id=id.replace(re, '');
            
            var serialName=$(this).text();
            var reg=/(^\s*)|(\s*$)/g;
            serialName=serialName.replace(reg, "");
            serialName='"'+serialName+'"';
            $(".sms_serial_name").text(serialName);
            
            var row=$(this).parent().parent().children();
            var serialId=$(row[0]).text();
            $(".sms_serial_id").text(serialId);
            
            $("#sms_dialog").dialog({
                modal: true,
                title: 'SMS голосование',
                width: 650,
                height: 580
            });
        }
        
        return false;
    });
    
    if($("#order_ok").html()) {
        $("#order_ok").dialog({
            modal: true,
            title: 'Заказ на сериал принят!',
            width: 450
        });
    };
    
    $("#show_sms_rules").click(function() {
        $("#sms_rules").dialog({
            modal: true,
            title: 'Правила сервиса "SMS голосование"',
            width: 650,
            height: 580
        });
    });
    
    $(".home_serial").mouseenter(function() {
        $(this).children('.home_serial_title').addClass('no_transparent');
        $(this).children('.home_serial_desc').addClass('no_transparent');
    });
    $(".home_serial").mouseleave(function() {
        $(this).children('.home_serial_title').removeClass('no_transparent');
        $(this).children('.home_serial_desc').removeClass('no_transparent');
    });
    
    $(".home_serial_short").mouseenter(function() {
        $(".home_serial_poster_inner").css('background-image', 'url(/files/serial/tmb/'+$(this).children('.poster_name').val()+')');
    });
    $(".home_serial_short_2").mouseenter(function() {
        $(".home_serial_poster_inner_2").css('background-image', 'url(/files/serial/tmb/'+$(this).children('.poster_name').val()+')');
    });
    
    $(".home_serial_short").click(function() {
        top.location.href=$(this).children('.serial_link').val();
    });
    
    $(".home_serial_short_2").click(function() {
        top.location.href=$(this).children('.serial_link').val();
    });
    
    if($("#vote_dialog").html()) {
        $("#vote_dialog").dialog({
            modal: true,
            title: 'Важное сообщение. Пожалуйста, прочитайте!',
            width: 650,
            height: 370
        });
    }
    
    //$(".vote_radio").change(function() {
    //    $("#vote").val($(this).val());
    //    
    //    $("#make_vote").attr("disabled", false);
    //});
    
    $("#make_vote").click(function() {
        var vote=$("#vote").val();
        
        $.ajax({
            type: "POST",
            url: "/ajax.php", 
            data: { vote: 1 }, 
            success: function(data) {
                //if(data=='OK') {
                //    alert('Голос учтен. Большое спасибо за Ваше мнение!');
                //} else {
                //    alert('В настоящий момент голосование не доступно. Пожалуйста, попробуйте позже');
                //}
                
                $("#vote_dialog").dialog('close');
            }
        });
    });
    
    $(".episod_info").mouseenter(function() {
        var src=$(this).children('.episod_img').attr('src');
        var re=/jpg/;
        var thisImage=this;
        
        src=src.replace(re, 'gif');
        
        $(this).children('.episod_img').attr('src', src);
        $(this).css('background-color', '#efefef');
    });
    
    $(".episod_info").mouseleave(function() {
        var src=$(this).children('.episod_img').attr('src');
        var re=/gif/;
        var thisImage=this;
        
        src=src.replace(re, 'jpg');
        
        $(this).children('.episod_img').attr('src', src);
        
        $(this).css('background-color', '#fff');
    });
    
    $(".episod_info").click(function() {
        
        $(this).parent().parent().children('.video_object').html("<p>&nbsp;</p>");
        var block_id=$(this).parent().parent().children('.video_object').attr('id');
        
        var id=$(this).attr('id');
        
        var params={
            episodId: id,
            blockId: block_id
        };
        
        getAjax('changeEpisod', params);
    });
    
    $(".online_season_title").click(function() {
        var id=$(this).attr('id');
        
        $(".online_inner").hide(1000, function() {
            $("#block_"+id).show(1000);
        });
        
        return false;
    });
    
    $(".userbar_img").change(function() {
	$(this).css('background-image', $(this).children('option:selected').css('background-image'));
    });
    
    $("#make_preview").click(function() {
	var type=$("#userbarType").val();
	
	if(type) {
	    
	    if(type==1) {
		var list=$("#serialList option:selected");
		if(!list.length) {
		    alert("Вы должны выбрать хотя бы один сериал!");
		    return false;
		}
	    }
	    
	    $("#result_userbar").attr('src', '/img/spacer.gif');
	    
	    var src="/userbar.php?";
	    
	    src+= "color1="+$("#gradient_1").val();
	    src+="&color2="+$("#gradient_2").val();
	    src+="&gradientDirection="+$("#gradient_direction").val();
	    src+="&bg="+$("#bg").val();
	    src+="&logo="+$("#logo").val();
	    src+="&tpl="+$("#tpl").val();
	    src+="&shine="+$("#shine").val();
	    src+="&bg_opacity="+$("#bgOpacitySlider").slider("value");
	    src+="&border="+$("#border").val();
	    src+="&noborder="+$("#noborder").attr('checked');
	    
	    src+="&font="+$("#font").val();
	    src+="&fontColor="+$("#fontColor").val();
	    src+="&fontSize="+$("#fontSizeSlider").slider("value");
	    src+="&strokeColor="+$("#strokeColor").val();
	    src+="&strokeSize="+$("#strokeSizeSlider").slider("value");
	    src+="&x="+$("#leftMarginSlider").slider("value");
	    src+="&y="+$("#topMarginSlider").slider("value");
	    
	    src+="&type="+type;
	    if(type==1) {
		var list=$("#serialList option:selected");
		for(i=0; i<list.length; i++) {
		    src+="&serial[]="+$(list[i]).val();
		}
	    } else if(type==2) {
		src+="&serial="+$("#serialList2").val();
		src+="&season="+$("#seasonList").val();
		src+="&episod="+$("#episodNumber").val();
	    } else {
		src+="&text="+$("#myText").val();
	    }
	    
	    src+="&rand="+Math.round(Math.random()*10000000);
	    
	    
	    $("#result_userbar").attr('src', src);
	}
    });
    
    $("#saveUserbar").click(function() {
	if(!confirm("Уверены? Изменить созданный юзербар буден нельзя!")) {
	    return false;
	}
	
	if($("#result_userbar").attr('src')!='/img/spacer.gif') {
	    var type=$("#userbarType").val();
	    
	    var params={
		color1: $("#gradient_1").val(),
		color2: $("#gradient_2").val(),
		gradientDirection: $("#gradient_direction").val(),
		bg: $("#bg").val(),
		logo: $("#logo").val(),
		tpl: $("#tpl").val(),
		shine: $("#shine").val(),
		bg_opacity: $("#bgOpacitySlider").slider("value"),
		border: $("#border").val(),
		noborder: $("#noborder").attr('checked'),
		font: $("#font").val(),
		fontColor: $("#fontColor").val(),
		fontSize: $("#fontSizeSlider").slider("value"),
		strokeColor: $("#strokeColor").val(),
		strokeSize: $("#strokeSizeSlider").slider("value"),
		x: $("#leftMarginSlider").slider("value"),
		y: $("#topMarginSlider").slider("value"),
		type: type
	    };
	    
	    if(type==1) {
		params['serial']=new Array();
		var list=$("#serialList option:selected");
		for(i=0; i<list.length; i++) {
		    params['serial'][i]=$(list[i]).val();
		}
	    } else if(type==2) {
		//src+="&serial="+$("#serialList2").val();
		//src+="&season="+$("#seasonList").val();
		//src+="&episod="+$("#episodNumber").val();
	    } else {
		params['text']=$("#myText").val();
	    }
	    
	    getAjax('saveUserbar', params, true);
	}
    });
    
    $("#result_userbar").load(function() {
	if($(this).attr('src')!='/img/spacer.gif') {
	    $("#saveUserbarBlock").show();
	}
    });
    
    $("#userbarType").change(function() {
	var type=$(this).val();
	
	$(".userbarType").hide();
	
	if(type) {
	    $("#userbarType"+type).show();
	    $("fieldset").not(".userbarType").show();
	    
	    if($("#userbarType").data('rendered')!=1) {
		$("#userbarType").data('rendered', 1);
		
		if($("#gradient_1").length) {
		    $("#gradient_1").jPicker({
			window: {
			    expandable: true
			},
			images: {
			    clientPath: '/script/jpicker/images/'
			}
		    });
		    
		    $("#gradient_2").jPicker({
			window: {
			    expandable: true
			},
			images: {
			    clientPath: '/script/jpicker/images/'
			}
		    });
		    
		    $("#border").jPicker({
			window: {
			    expandable: true
			},
			images: {
			    clientPath: '/script/jpicker/images/'
			}
		    });
		    
		    $("#fontColor").jPicker({
			window: {
			    expandable: true
			},
			images: {
			    clientPath: '/script/jpicker/images/'
			}
		    });
		    
		    $("#strokeColor").jPicker({
			window: {
			    expandable: true
			},
			images: {
			    clientPath: '/script/jpicker/images/'
			}
		    });
		    
		    $("#fontSizeSlider").slider({
			value:10,
			min: 5,
			max: 20,
			slide: function(event, ui) {
			    $("#fontSizeValue").text(ui.value+'px');
			}
		    });
		    $("#fontSizeValue").text($("#fontSizeSlider").slider("value")+'px');
		    
		    $("#strokeSizeSlider").slider({
			value:2,
			min: 0,
			max: 5,
			slide: function(event, ui) {
			    $("#strokeSizeValue").text(ui.value+'px');
			}
		    });
		    $("#strokeSizeValue").text($("#strokeSizeSlider").slider("value")+'px');
		    
		    $("#leftMarginSlider").slider({
			value:15,
			min: 0,
			max: 340,
			slide: function(event, ui) {
			    $("#leftMarginValue").text(ui.value+'px');
			}
		    });
		    $("#leftMarginValue").text($("#leftMarginSlider").slider("value")+'px');
		    
		    $("#topMarginSlider").slider({
			value:5,
			min: 0,
			max: 19,
			slide: function(event, ui) {
			    $("#topMarginValue").text(ui.value+'px');
			}
		    });
		    $("#topMarginValue").text($("#topMarginSlider").slider("value")+'px');
		    
		    $("#bgOpacitySlider").slider({
			value:85,
			min: 0,
			max: 100,
			slide: function(event, ui) {
			    $("#bgOpacityValue").text(ui.value+'%');
			}
		    });
		    $("#bgOpacityValue").text($("#bgOpacitySlider").slider("value")+'%');
		}
	    }
	} else {
	    $("fieldset").not("#selectUserbarType").hide();
	}
    });
    
    $(".delUserbar").click(function() {
	var params={
            id: $(this).attr('id')
        };
        
        getAjax('delUserbar', params);
    });
    
    $(".top_serial_block").mouseenter(function() {
	$(this).children(".hint").css("bottom", 15+$(this).children(".hint").height());
    });
    $(".top_serial_block").mouseleave(function() {
	$(this).children(".hint").css("bottom", "0");
    });
    
    $("#top_serial_arrow_left").mouseenter(function() {
	$("#top_serial_arrow_left").data('move', 1);
	animateTopSerial();
    });
    $("#top_serial_arrow_left").mouseleave(function() {
	$("#top_serial_arrow_left").data('move', 0);
    });
    
    $("#top_serial_arrow_right").mouseenter(function() {
	$("#top_serial_arrow_right").data('move', 1);
	animateTopSerial();
    });
    $("#top_serial_arrow_right").mouseleave(function() {
	$("#top_serial_arrow_right").data('move', 0);
    });
    
    $("#top_serial_arrow_left").click(function() {
	return false;
    });
    
    $("#top_serial_arrow_right").click(function() {
	return false;
    });
    
    $("#select_file_block li").mouseenter(function() {
	$(this).addClass('active');
    });
    $("#select_file_block li").mouseleave(function() {
	$(this).removeClass('active');
    });
    $("#select_file_block li").click(function() {
	var id=$(this).attr('id');
	$(this).siblings().removeClass('selected').end().addClass('selected');
	$("#select_file_block").data('selected', id);
	$("#links_list").hide();
	$("#select_fo").show();
	
	//top.location.hash="select_fo";
    });
    
    $("#select_fo li").mouseenter(function() {
	$(this).addClass('active');
    });
    $("#select_fo li").mouseleave(function() {
	$(this).removeClass('active');
    });
    $("#select_fo li").click(function() {
	var id=$(this).attr('id');
	$(this).siblings().removeClass('selected').end().addClass('selected');
	
	var params={
	    'file_block': $("#select_file_block").data('selected'),
	    'fo': id
	};
	
	$("#links_list").html('<center><img src="/img/ajax-loader.gif"></center>');
	$("#links_list").show();
	getAjax('getLinks', params);
	
    });
    
    $("#link_tizer").bind('click', function() {
	$("#select_file_block").show();
	$("#link_tizer").hide();
	alert('Спасибо! Ссылки активированы.');
    });
});

