var c_cache        = new Array();

function RunAjaxJS(insertelement, data){
	var milisec = new Date;
    var jsfound = false;
    milisec = milisec.getTime();

    var js_reg = /<script.*?>(.|[\r\n])*?<\/script>/ig;

    var js_str = js_reg.exec(data);
    if (js_str != null) {

		var js_arr = new Array(js_str.shift());
        var jsfound = true;

        while(js_str) {
           js_str = js_reg.exec(data);
           if (js_str != null) js_arr.push(js_str.shift());
        }

        for(var i=0; i<js_arr.length;i++) {
           data = data.replace(js_arr[i],'<span id="'+milisec+i+'" style="display:none;"></span>');
        }
	}

	$("#" + insertelement).html(data);

    if (jsfound) {

       var js_content_reg = /<script.*?>((.|[\r\n])*?)<\/script>/ig;

       for (i = 0; i < js_arr.length; i++) {
           var mark_node = document.getElementById(milisec+''+i);
           var mark_parent_node = mark_node.parentNode;
           mark_parent_node.removeChild(mark_node);

           js_content_reg.lastIndex = 0;
           var js_content = js_content_reg.exec(js_arr[i]);
           var script_node = mark_parent_node.appendChild(document.createElement('script'));
		   script_node.text = js_content[1];

           var script_params_str = js_arr[i].substring(js_arr[i].indexOf(' ',0),js_arr[i].indexOf('>',0));
           var params_arr = script_params_str.split(' ');

           if (params_arr.length > 1) {
              for (var j=0;j< params_arr.length; j++ ) {

                  if(params_arr[j].length > 0){
                       var param_arr = params_arr[j].split('=');
                       param_arr[1] = param_arr[1].substr(1,(param_arr[1].length-2));
                       script_node.setAttribute(param_arr[0],param_arr[1]);
                  }

               }
           }

       }
    }
};

//Меню
function dropdownmenu(obj, e, menucontents, menuwidth){
	if (window.event) event.cancelBubble=true;
	else if (e.stopPropagation) e.stopPropagation();
	var menudiv = $('#dropmenudiv');
	if (menudiv.is(':visible')) { clearhidemenu(); menudiv.fadeOut('fast'); return false; }
	menudiv.remove();
	$('body').append('<div id="dropmenudiv" style="display:none;position:absolute;z-index:100;width:165px;"></div>');
	menudiv = $('#dropmenudiv');
	menudiv.html(menucontents.join(""));
	if (menuwidth) menudiv.width(menuwidth);
	var windowx = $(document).width() - 30;
	var offset = $(obj).offset();
	if (windowx-offset.left < menudiv.width())
			offset.left = offset.left - (menudiv.width()-$(obj).width());
	menudiv.css( {
		left : offset.left + "px",
		top : offset.top+$(obj).height()+"px"
	});
	menudiv.fadeTo('fast', 0.9);
    menudiv.mouseenter(function(){
	      clearhidemenu();
	    }).mouseleave(function(){
	      delayhidemenu();
	});
	$(document).one("click", function() {
		hidemenu();
	});
	return false;
};
function hidemenu(e){
	$("#dropmenudiv").fadeOut("fast");
};
function delayhidemenu(){
	delayhide=setTimeout("hidemenu()",1000);
};
function clearhidemenu(){
	if (typeof delayhide!="undefined")
		clearTimeout(delayhide);
};
//!Меню

//Сообщения загрузки
function ShowLoading( message ){
	if ( message )
	{
		$("#loading-layer-text").html(message);
	}
	var setX = ( $(window).width()  - $("#loading-layer").width()  ) / 2;
	var setY = ( $(window).height() - $("#loading-layer").height() ) / 2;
	$("#loading-layer").css( {
		left : setX + "px",
		top : setY + "px",
		position : 'fixed',
		zIndex : '99'
	});
	$("#loading-layer").fadeTo('slow', 0.6);
};
function HideLoading( message ){
	$("#loading-layer").fadeOut('slow');
};
//!Сообщения загрузки

//Комменты
function ajax_comm_edit( c_id, area ){
	if ( ! c_cache[ c_id ] || c_cache[ c_id ] == '' )
	{c_cache[ c_id ] = $('#comm-id-'+c_id).html();}
	ShowLoading('');
	$.get(dle_root + "system/ajax/editcomments.php", { id: c_id, area: area, action: "edit" }, function(data){
		HideLoading('');
		RunAjaxJS('comm-id-'+c_id, data);
		setTimeout(function() {
           $("html:not(:animated)"+( ! $.browser.opera ? ",body:not(:animated)" : "")).animate({scrollTop: $("#comm-id-" + c_id).offset().top - 70}, 700);
        }, 100);
	});
	return false;
};
function ajax_cancel_comm_edit( c_id ){
    if ( c_cache[ c_id ] != "" )
	{$("#comm-id-"+c_id).html(c_cache[ c_id ]);}
	return false;
};
function ajax_save_comm_edit( c_id, area ){
	var comm_txt = '';
	comm_txt = $('#dleeditcomments'+c_id).val();
	ShowLoading('');
	$.post(dle_root + "system/ajax/editcomments.php", { id: c_id, comm_txt: comm_txt, area: area, action: "save" }, function(data){
		HideLoading('');
		c_cache[ c_id ] = '';
		$("#comm-id-"+c_id).html(data);
	});
	return false;
};
function doAddComments(){
	var form = document.getElementById('dle-comments-form');
    if (form.comments.value == '' || form.name.value == ''){alert ( dle_req_field );return false;}
	if ( form.allow_subscribe ) {
		if ( form.allow_subscribe.checked == true ) {var allow_subscribe= "1";} else {var allow_subscribe= "0";}
    } else { var allow_subscribe= "0"; }
	ShowLoading('');
	$.post(dle_root + "system/ajax/addcomments.php", { post_id: form.post_id.value, comments: form.comments.value, name: form.name.value, mail: form.mail.value, skin: dle_skin, allow_subscribe: allow_subscribe }, function(data){
		HideLoading('');
		RunAjaxJS('dle-ajax-comments', data);
		if (data != 'error' && document.getElementById('blind-animation')) {
			$("html"+( ! $.browser.opera ? ",body" : "")).animate({scrollTop: $("#dle-ajax-comments").offset().top - 70}, 1100);
			setTimeout(function() { $('#blind-animation').show('blind',{},0)}, 0);
		}
	});
};
function commentdelete(c_id, u_hash){
    var agree=confirm( "Удалить комментарий?" );
    if (agree){
    ShowLoading('');
    $.get(dle_root + "system/ajax/commentdelete.php", { commid: c_id, uhash: u_hash }, function(data){
    HideLoading('');
        $("#comment-id-" + c_id).html(data);
    });
}}
//!Комменты

function log_out(){
    var agree=confirm(" Вы действительно хотите выйти?" );
    if (agree){
        $.get(dle_root+"system/modules/sitelogin.php", {action: logout}, function(){
            location.href="";
            location.reload();
        });
}}

function Rate( rate, id, type ) {
	ShowLoading('');
	$.get(dle_root + "system/ajax/rating.php", { go_rate: rate, id: id, type: type, skin: dle_skin}, function(data){
		HideLoading('');
        if(type==1){$("#ratig-layer-" + id).html(data);}else{$("#cratig-layer-" + id).html(data);}
	});
};

function doFilesList( id ){
	ShowLoading('');
	$.post(dle_root + "system/ajax/torrent.php", { id: id }, function(data){
		HideLoading('');
		$("#listing_torrent-" + id).html(data);
	});
};

function doFavorites( fav_id, event ){
	ShowLoading('');
	$.get(dle_root + "system/ajax/favorites.php", { fav_id: fav_id, action: event, skin: dle_skin }, function(data){
		HideLoading('');
		$("#fav-id-" + fav_id).html(data);
	});
	return false;
};
function comm_Subscribe( news_id, event ){
    ShowLoading('');
    $.get(dle_root + "system/ajax/subscribe.php", { news_id: news_id, skin: dle_skin}, function(data){
        HideLoading('');
        $("#subscribe-id-" + news_id).html(data);
    });
    return false;
};
function CheckLogin(){
	var name = document.getElementById('name').value;
	ShowLoading('');
	$.post(dle_root + "system/ajax/registration.php", { name: name }, function(data){
		HideLoading('');
    	$("#result-registration").html(data);
	});
	return false;
};
function find_relates ( ){
	var title = document.getElementById('title').value;
	ShowLoading('');
	$.post(dle_root + 'system/ajax/find_relates.php', { title: title }, function(data){
		HideLoading('');
		$('#related_news').html(data);

	});
	return false;
};
function newslist( news_id, type ){
	ShowLoading('');
    $.get(dle_root + "system/ajax/newslist.php", { news_id: news_id, action: type}, function(data){
        HideLoading('');
        $("#news-id-" +news_id).html(data);
    });
};
function voted_list(id){
    $("#voted-list").remove();
	ShowLoading('');
	$.get(dle_root + "system/ajax/voted.php", {id: id}, function(data){
		HideLoading('');
		$("body").append( data );
		$('#voted-list').dialog({
				autoOpen: true,
				width: 400,
				height: 300,
                buttons: {
                    "Закрыть": function() {
                    $(this).dialog("close");
                    $("#voted-list").remove();
        }}});
	 });

	return false;
};

function ShowAlert(message, title){
	$("#dlepopup").remove();
	$("body").append("<div id='dlepopup' title='" + title + "' style='display:none'><br />"+ message +"</div>");
	$('#dlepopup').dialog({
		autoOpen: true,
		width: 470,
		dialogClass: "modalfixed",
		buttons: {
			"Ok": function() {
				$(this).dialog("close");
				$("#dlepopup").remove();
			}
		}
	});

	$('.modalfixed.ui-dialog').css({position:"fixed"});
	$('#dlepopup').dialog( "option", "position", ['0','0'] );
};
function upload_form(open_url){
	ShowLoading('');
    $("#upload_form").remove();
	$.post(dle_root + "system/ajax/upload.form.php", {}, function(data){
		HideLoading('');
		$("body").append( data );

		$('#upload_form').dialog({
				autoOpen: true,
				width: 400,
				height: 300,
                buttons: {
                    "Закрыть": function() {
                    $(this).dialog("close");
                    $("#upload_form").remove();
        }}});
	 });

	return false;
};
function Reputation(action, user_id){
	var cause = prompt("Введите причину", "");

	if (cause){
        ShowLoading('');
        $.post(dle_root + "system/ajax/reputation.php", { action: action, user_id: user_id, cause: cause, skin: dle_skin }, function(data){
        HideLoading('');
            $("#repa-" + user_id).html(data);
        });
        return false;
	}
};

function dle_copy_quote(qname){
    dle_txt= '';
	if (window.getSelection) {dle_txt=window.getSelection();}
	else if (document.selection){dle_txt=document.selection.createRange().text;}
	if (dle_txt != ""){dle_txt='[quote='+qname+']'+dle_txt+'[/quote]\n';}
};
function confirmDelete(url){
    var agree=confirm( dle_del_agree );
    if (agree)
    document.location=url;
};
function ShowBild(sPicURL) {
window.open(dle_root + 'system/modules/imagepreview.php?image='+sPicURL, '', 'resizable=1,HEIGHT=200,WIDTH=200, top=0, left=0, scrollbars=yes');
};
function dle_ins(name){
	if ( !document.getElementById('dle-comments-form') ) return false;
	var input=document.getElementById('dle-comments-form').comments;
	if (dle_txt!= "") {input.value += dle_txt;}
	else {input.value += "[b]"+name+"[/b],"+"\n";}

    var target_offset = $('#comments').offset();
   	var target_top = target_offset.top;
   	$('html, body').animate({scrollTop: target_top},300);
};
function ShowOrHide( id ) {
	  var item = document.getElementById(id);
	  if ( document.getElementById('image-'+ id) ) {var image = document.getElementById('image-'+ id);
	  } else {var image = null;}
	  if (!item) {return;
	  }  else {
        if (item.style) {
			if (item.style.display == "none") {item.style.display = "";
				if (image) { image.src = dle_root + 'templates/'+ dle_skin + '/images/spoiler-minus.gif';}
			} else {item.style.display = "none";
				if (image) { image.src = dle_root + 'templates/'+ dle_skin + '/images/spoiler-plus.gif';}
			}} else{ item.visibility = "show"; }
	  }};
function ckeck_uncheck_all() {
    var frm = document.pmlist;
    for (var i=0;i<frm.elements.length;i++) {
        var elmnt = frm.elements[i];
        if (elmnt.type=='checkbox') {if(frm.master_box.checked == true){ elmnt.checked=false; }else{ elmnt.checked=true; }}
    }if(frm.master_box.checked == true){ frm.master_box.checked = false; }else{ frm.master_box.checked = true; }
};
function setNewField(which, formname){
    if (which != selField){fombj    = formname; selField = which;}};

function news_change_sort(sort, direction){
  var frm = document.getElementById('news_set_sort');
  frm.dlenewssortby.value=sort;
  frm.dledirection.value=direction;
  frm.submit();
  return false;
};
function comm_change_sort(sort){
	var frm = document.getElementById('comm_set_sort');
	frm.dle_comm_sort.value=sort;
	frm.submit();
	return false;
};

$(document).ready(function(){
    $(".slide0").attr('style', 'display:block;');
    $("#s0").attr('style', 'background-color:gray;');

    $("a.slink").click(function(){
        $("a.slink").attr('style', '');
        $(this).attr('style', 'background-color:gray;');
        var id = $(this).attr("id");
        var tp = $($(this).closest('.newsslider').get(0)).attr('id');
        $('#'+tp+' li.slide').hide();
        $('#'+tp+' li.slide0').hide();
        $("#slide_"+id).fadeIn('200');
        return false;
    });

    $(window).scroll(function(){
        if ($(this).scrollTop() > 100) {
            $('.scrollup').fadeIn();
        } else {
            $('.scrollup').fadeOut();
        }
    });

    $('.scrollup').click(function(){
        $("html, body").animate({ scrollTop: 0 }, 600);
        return false;
    });
});