(function($){
  '$:nomunge';
  
  var cache = {},
    doTimeout = 'doTimeout',
    aps = Array.prototype.slice;

  $[doTimeout] = function() {
    return p_doTimeout.apply( window, [ 0 ].concat( aps.call( arguments ) ) );
  };
  
  
  $.fn[doTimeout] = function() {
    var args = aps.call( arguments ),
      result = p_doTimeout.apply( this, [ doTimeout + args[0] ].concat( args ) );
    
    return typeof args[0] === 'number' || typeof args[1] === 'number'
      ? this
      : result;
  };
  
  function p_doTimeout( jquery_data_key ) {
    var that = this,
      elem,
      data = {},
      
      args = arguments,
      slice_args = 4,
      
      id        = args[1],
      delay     = args[2],
      callback  = args[3];
    
    if ( typeof id !== 'string' ) {
      slice_args--;
      
      id        = jquery_data_key = 0;
      delay     = args[1];
      callback  = args[2];
    }
    
    if ( jquery_data_key ) {
      
      elem = that.eq(0);
      elem.data( jquery_data_key, data = elem.data( jquery_data_key ) || {} );
      
    } else if ( id ) {
      data = cache[ id ] || ( cache[ id ] = {} );
    }
    
    data.id && clearTimeout( data.id );
    delete data.id;
    
    function cleanup() {
      if ( jquery_data_key ) {
        elem.removeData( jquery_data_key );
      } else if ( id ) {
        delete cache[ id ];
      }
    };
    
    function actually_setTimeout() {
      data.id = setTimeout( function(){ data.fn(); }, delay );
    };
    
    if ( callback ) {
      data.fn = function( no_polling_loop ) {
        callback.apply( that, aps.call( args, slice_args ) ) && !no_polling_loop
          ? actually_setTimeout()
          : cleanup();
      };
      
      actually_setTimeout();
      
    } else if ( data.fn ) {

      delay === undefined ? cleanup() : data.fn( delay === false );
      return true;
      
    } else {
      cleanup();
    }
    
  };
  
})(jQuery);



$(function(){
    
    isroot = ($("#m2")[0]==undefined);
    
    
    $("#port_links a:first").click(function(){
        $("#b11").data("rp",0);
        render_port0();
        return false;
    });
    
  
    $("#b11").data("rp",0);
    $("#b11").data("dn",[]);
    
    $("h1").each(function(){
        $(this).append(" <span class='h1_span1'><span class='h1_span2'>"+$(this).text()+"</span></span>");
    });
    
   
    // расставляем дополнительные H классы для выравнивания текста
    $("#c1 h1:first, #c2 h1:first").each(function(){
        if ($(this).next()[0]!== undefined && $(this).next()[0].tagName == 'H2') { // далее идет h2
            $(this).addClass("h1_with_h2");
            $(this).next().addClass("h2_with_h1");
        } else {
            $(this).addClass("h1_without_h2");
        }
    });

    $(".h1_without_h2").find(".h1_span1").addClass("h1_without_h2_span1");
    $(".h1_without_h2").find(".h1_span2").addClass("h1_without_h2_span2");    
    
    
    if (!isroot) { // только для внутренних
    
    $("#m2").mouseleave(function(){ // таймер для убирания неродного мабменю при отведении от него курсора
        if (unnative_sub) {
            $.doTimeout('hide_unnative_sub',5000,function(){
                //alert('hide_unnative_sub');
                $(".menulevel2").fadeOut(500,function(){
                    $(".menulevel2").remove(); $("#h2").removeClass("header2_small");
                    mark_menu(true);
                });
                unnative_sub = false;
            });
        }
    });
    
    $("#m2").mouseenter(function(){ // отмера таймера при обратном наведении нам еню
        if (unnative_sub) {
            $.doTimeout('hide_unnative_sub');
        }
    });   
    
    mark_menu(false); // отметить пункт в меню и подменю
    
    $(".menulevel1 a").click(function(){ // логика при нажатии на меню
        // если есть подменю и в ссылке больше одного параметра (вложенность) то показывается сабменю
        // если нет то присходит переход, но если есть класс то не переходим, а показываем сабмен (ну если оно есть)
        
        sub2 = ($(this).parent().next().hasClass("disno"))?true:false; // да если есть подменю
        
        tmp = $(this).attr("href"); tmp2 = tmp.split('/');
        case2 = (tmp2.length < 4)?false:true; // да есть в ссылке два параметра а не один
        
        if ((sub2 && case2) || (sub2 && $(this).hasClass("m1sel"))) {
            
            if ($(".m2sel:first").parent().parent().parent().prev().find("a")[0] == this) { unnative_sub = false; } else { unnative_sub = true; }
            $(".menulevel2").remove();
            $("#h2").addClass("header2_small");
            $(".menulevel1").after($(this).parent().next().find("ul").clone().addClass("menulevel2").fadeIn(500));
            
            return false;
        }
        
//        if (sub2 && $(this).hasClass("m1sel")) {
  //      }
        
        return true;
        
        
        
    });
    
    } // if isroot
    
    
    

    // реакция на наведение на внутреннее портфолио   
    $("#inner_port_cont a").hover(function(){
        
        $(this).parent().find("*").stop();
        $(this).parent().find(".inner_port_h").remove();
        
        $("<div class='inner_port_h'></div>").insertBefore(this);
        $(this).parent().find(".inner_port_h").css({opacity:0.8}).animate({height:"225px",top:"0"},800);
        $(this).doTimeout(200,function(){
            if ($(this).prev().hasClass("inner_port_h2")) { return; }
            $(this).animate({opacity:"1"},500);
            $("<div class='inner_port_h'></div>").insertBefore(this);
            $(this).parent().find(".inner_port_h:last").css({opacity:0.8}).animate({height:"80px",top:"72px"},2000);
        });
    },function(){
        $(this).parent().find("*").stop();
        $(this).animate({opacity:"0"},500);
        $(this).parent().find(".inner_port_h:eq(0)").addClass("inner_port_h2").animate({opacity:0,height:"2px",top:"112px"},200,function(){$(this).remove();});
        $(this).parent().find(".inner_port_h:eq(1)").addClass("inner_port_h2").animate({opacity:0,height:"225px",top:"0px"},200,function(){$(this).remove();});
    
    });
    
    
    
    
    // если не портфолио и не блог, запрашиваем боковушку (и не главная и не акция золотая сороковка)
    if ($(".id_blog")[0]==undefined && $(".id_port")[0]==undefined && !isroot && $(".nosidebar").length<1) {
    //if ($(".menulevel1 a:first").attr("rel")!='_22' && $(".menulevel1 a:first").attr("rel")!='_16' && !isroot) {
        call_for_sidebar();
    }
    
    
    // прячем side baк в порт
    if ($(".id_port")[0]) {
        $("#sb").remove();
        $("#c2").css("width","90%");
        $(".inner_port_a").css("opacity",0);
        
    }

    
    //прячем side бар в блоге
    if ($(".id_blog")[0]) {
        //if ($(".menulevel1 a:first").attr("rel")=='_22') {
        $("#sb").remove();
        $("#c2").css("width","60%");
    }
    
    // рекация на кнопки под трекером блога (другие публикации)
    var blog_ipp = 10; var blog_next_from = 10;
    $("#port_inner_links a:first").click(function(){
        $("#port_inner_links").after("<div class='txt_loading'>...загрузка</div>");
        
        $.post('/system/plugins/blog.php',{a:'getinnerblogs',from:blog_next_from, count:blog_ipp},function(data){
            $(".txt_loading").remove();
            if ($(data).find("count").text()=='0') {return false;}
            text = $(data).find("html").text();
            $(text).insertBefore("#port_inner_links");
            blog_next_from = blog_next_from + blog_ipp;
            if ($(data).find("more").text()=='no') {$("#port_inner_links").hide();}
        },'xml');
        return false;
    });
    
    
    
    
    // нажатие на ссылку оставить коментарий, отправка и отмена
    $(".leave_a_comment_link").click(function(){
        
        
        
        if ($("#leave_a_comment form")[0] == undefined) {
            //$("#leave_a_comment").append("<form><h2 class='blog_comments'>Оставить коментарий:</h2><div class='leave_a_comment_row'><span>Имя</span><input name='name' class='leave_a_comment_margin'></div><div class='leave_a_comment_row'><span>E-mail</span><input name='email' class='leave_a_comment_margin'></div><div class='leave_a_comment_row'><span>Текст</span><textarea name='text' class='leave_a_comment_margin'></textarea></div><div class='leave_a_comment_row'><input class='leave_a_comment_margin' type='submit' value='Отправить'> <input type='button' value='Отмена'></div></form>");
            $("#leave_a_comment").append("<form>"+$(".comment_form_fields").html()+"</form>");
        }
        $("#leave_a_comment").show();

        $(this).hide();
        return false;
    });
    
    $("#leave_a_comment input:button").live('click',function(){
        $("#leave_a_comment").hide();
        $(".leave_a_comment_link").show();
    });
    
    $("#leave_a_comment input:submit").live('click',function(){
        if ($("#leave_a_comment input[name=name]")[0]!=undefined) {
            n = $("#leave_a_comment input[name=name]").val();
            e = $("#leave_a_comment input[name=email]").val();
            if ($.trim(n)=='') {alert("«Имя» — обязательное поле."); return false;}
            if ($.trim(e)!='') { if (!emailok(e,true)) {alert('Ошибка в е-mail!'+"\n"+'E-mail НЕ обязательное поле.'); return false; }}
        } else {
            n='';e='';
        }
        t = $("#leave_a_comment textarea").val();
        d = $(".leave_a_comment_").attr("id");
        if ($.trim(t)=='') {alert("«Текст» — обязательное поле."); return false;}
        
        $.post('/system/plugins/blog.php',{a:'send_a_comment',d:d,n:n,e:e,t:t},function(data){
            if ($(data).find("error")[0]!=undefined){alert($(data).find("error").text()); return false;}
            
            
            $(".blog_comment_cont, .blog_comment_hr").remove();
            nc = $(data).find("html").text();
            $(nc).insertAfter($("h2.blog_comments:first"));
            
                        
            $("#leave_a_comment").hide();
            $(".leave_a_comment_link").show();
            $("#leave_a_comment input[name=name]").val("");
            $("#leave_a_comment input[name=email]").val("");
            $("#leave_a_comment textarea").val("");
            
            alert('Ваше сообщение принято. Спасибо за коментарий.');
            
        },'xml');
        
        return false;
    });
    
    
    $(".p_image_desc").each(function(){
      $(this).html("<span>" + $(this).html() + "</span>");
    });
    
    
        
});



function call_for_sidebar() {
    itisnews = ($(".id_news")[0]!=undefined);
    $.post("/system/plugins/side.php",{a:'sb',cp:itisnews},function(data){
        sba = $(data).find("html").text();
        $("#sb").empty().append(sba).css("display","none").fadeIn(500);
        $.doTimeout(30000,call_for_sidebar);
    },'xml');
}

function emailok (e, s) {
    if (!s) e=email.replace(/^\s+|\s+$/g, '');
    return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(e);
}



function mark_menu(slow) {

    tmp = $(".menulevel1 a:first").attr("rel");
    tmp2 = tmp.split('_');
    sub = ($(".menulevel1 a:eq("+tmp2[1]+")").parent().parent().parent()[0].tagName == 'LI')?true:false;

    if (sub) {
        $(".menulevel1 a:eq("+tmp2[1]+")").addClass("m2sel");
        $(".menulevel1 a:eq("+tmp2[1]+")").parent().parent().parent().prev().find("a").addClass("m1sel");
        
        $(".menulevel2").remove();
        
        $("#h2").addClass("header2_small");
        
        if (slow) {
            $(".menulevel1").after($(".menulevel1 a:eq("+tmp2[1]+")").parent().parent().clone().addClass("menulevel2").fadeIn(500));
        } else {
            $(".menulevel1").after($(".menulevel1 a:eq("+tmp2[1]+")").parent().parent().clone().addClass("menulevel2"));
        }
        
    } else {
        $(".menulevel1 a:eq("+tmp2[1]+")").addClass("m1sel");
        // если есть подменю то показать его
        if ($(".menulevel1 a:eq("+tmp2[1]+")").parent().next().hasClass('disno')) {
            $(".menulevel1").after($(".menulevel1 a:eq("+tmp2[1]+")").parent().next().find("ul").clone().addClass("menulevel2"));
        }
    }
    
}




var defco = [
    {x:0,y:30},
    {x:250,y:30},
    {x:500,y:30},
    {x:750,y:30},
    {x:1000,y:30},
    {x:125,y:170},
    {x:375,y:170},
    {x:625,y:170},
    {x:875,y:170}
];



var defcol = defco.length;
var ind = [0,0,0,0,0,0,0,0,0];
var sub = false;
var unnative_sub = false;
var isroot = true;


$(window).load(function(){
    if (isroot) {
        $("#p2").empty();
        $("#p").animate({height:"595px"},1500);
        //$("#p2").css({height:"595px"});
        render_port0();
    }
});






$(".hoverimg").live('click',function(){
    //prfr
    tmp = $(this).attr("src");  tmp2 = tmp.split('/');  tmp3 = tmp2[(tmp2.length)-1];  tmp4 = tmp3.substring(0,(tmp3.length)-5);
    
    document.location.href = '/Портфолио/' + $(prfr).find("project[picsurl="+tmp4+"]").attr("pageurl") + '/';
    //alert($(prfr).find("project[picsurl="+tmp4+"]").attr("pageurl"));
    //alert(tmp3);
}); 



$(".pp_item img").live('mouseover',function(){
    id = $(this).parent().attr('id');
    if ($("#"+id+"hover")[0]==undefined) {
        hvr = $(this).clone();
        pos = $(this).parent().position();
        
        zi = 100; if ($("."+id)[0]) { zi=30; }
        
        $(hvr).attr("id",id+"hover").addClass("hoverimg").css({zIndex:zi,position: "absolute", top:(pos.top-3)+"px", left:(pos.left-3)+"px", border:"3px solid #ccc"});
        $("#p2").append(hvr);
    } else {
        $("#"+id+"hover").css({display:"block",opacity:1});
    }
});

$(".hoverimg").live('mouseout',function(){
    $(this).fadeOut(500);
}); 



var prfr = 0;
function render_port0() {
    $.post('/system/plugins/portfolio.php',{a:'prfr'},function(data){
        prfr = data;
        $("#p2").empty();
        ind = [0,0,0,0,0,0,0,0,0];
        render_port();
    },'xml');
}


function render_port() {
    alr = $("#b11").data("rp"); alr++;
    $("#b11").data("rp",alr);
    tmp = document.createElement("img");
    $(tmp).load(function(){
        itid = kogo();
        $("#p2").append("<div class='pp_item' id='pp_"+itid+"' style='position: absolute; top:"+ampl(defco[itid].y,100)+"px; left:"+(ampl(defco[itid].x,50))+"px'><img src='"+$(this).attr('src')+"' /></div>");
        
        // var hh = $("#pp_"+itid).find("img").height(); var ww = $("#pp_"+itid).find("img").width();
        var hh = $(this)[0].height; var ww = $(this)[0].width;
       
        if (navigator.userAgent.indexOf("MSIE 7.0") >= 0) {

            $("#pp_"+itid).css({display:"block", height:(hh+16)+'px',width:(ww+16)+'px'});
            apnd = "<div class='port_shadow_b' style='width:"+ww+"px'></div>"+"<div class='port_shadow_r' style='height:"+hh+"px;'></div>"+"<div class='port_shadow_rb'></div>";
            $("#pp_"+itid).append(apnd);
            //$("#pp_"+itid).fadeTo(1000,0.9);
            $("#pp_"+itid).css({display:'block'});


        } else {
            $("#pp_"+itid).css({opacity:0, height:(hh+16)+'px',width:(ww+16)+'px'});
            $("#pp_"+itid).fadeTo(1000,0.9);
            apnd = "<div class='port_shadow_b' style='width:"+ww+"px'></div>"+"<div class='port_shadow_r' style='height:"+hh+"px;'></div>"+"<div class='port_shadow_rb'></div>";
            $("#pp_"+itid).append(apnd);
        }
        
        alr = $("#b11").data("rp");
        if (alr<9) { $.doTimeout(200,render_port);} else {
            $.doTimeout(200,function(){
                ps = $(".pp_item:last").position();
                $("#p2").append("<img class='pp_"+itid+"' src='/design/new.png' style='position: absolute; top:"+(ps.top-20)+"px; left:"+(ps.left+170)+"px; z-index: 50 ' />");
                $(document).pngFix();
            });
        }
    });
    
    $(document).pngFix(); 
    tmp.src = '/files/'+$(prfr).find("project:eq("+(alr-1)+")").attr('picsurl') + 'a.jpg';
}



function ampl(x,r) {
    var m=0;
    var n=r;
    a = Math.floor( Math.random() * (n - m + 1) ) + m;
    return (x+a);

}





function kogo() {

    m=0; var n=(defcol-1); i=0; itsok = true;

    while (itsok) {
        vari = Math.floor( Math.random() * (n - m + 1) ) + m; 
        itsok=false;
        if (ind[vari]==1) {itsok=true;}
        i++; if (i> 100) {itsok=false;}
    }
    ind[vari] = 1;
    return vari;
    
    
}



/**************  по промо странице Золотая сороковкка *************/


$(function(){

if ($(".zolovka").length) {
	
	$("#c2 h1:first").remove();
	$(".h1_span1").remove();
	$("#c2").width("67%");
	$("#c2").css("font-size","16px");
	
	$("#c2 ul").addClass("zolovka_uls");
	
	ob='';
	
	$("#c2").find("h2").each(function(){
		ob = ob + "<li><a href=''>" + $(this).text() + "</a></li>";
		$(this).addClass("zolovka_h2").hide();
	});
	
	$("#c2 h1:first").after("<ul id='zolovka_ul'>"+ob+"</ul>");



	// прячем всех прямых детей начиная от UL
	showing_start = $("#zolovka_ul");
	while ($(showing_start).next().length) {
		$(showing_start).next().hide();
		showing_start = $(showing_start).next();
	}


	
	$("#zolovka_ul a").click(function(){
		
		$(".zolovka_msel").removeClass("zolovka_msel");
		$(this).addClass("zolovka_msel");
		
		aid = $("#zolovka_ul a").index(this);

		showing_start = $("#c2 h2:eq("+aid+")");
		
		//$(".showed_question, .showed_question2").hide();
		
		$(".zolovka_showed").hide();
		
		// показываем все элементы начиная от showing_start и заканчивая следующим a_lev_h2
		while ($(showing_start).next().length) {
			no = $(showing_start).next();
			if (!$(no).hasClass("zolovka_h2")) {
				$(no).addClass("zolovka_showed").fadeIn(300);
				
				$("#f").hide().show();
				
				showing_start = no;
			} else {
				break;
			}
		}

		
		return false;
	});
	
	$("#zolovka_ul a:first").click();
	
	
}



});




