if (typeof jQuery == "function") {
 jQuery.noConflict();
 var init ;
 (init = function($) {
 $(function(){
  var IE7 = ($.browser.msie && parseInt($.browser.version)<=7);
  var headPhotoShow;
  (headPhotoShow = function(hideBefore){
  var HPdiv = $("div.head-photo");
  if (hideBefore) HPdiv.animate({"opacity":0},100);
// if (IE7) {
//  HPdiv.css({"opacity":1,"filter":"alpha(opacity=100)"});
// } else {
  var bi = new Image();
  bi.src = HPdiv.css("background-image").replace(/^url\(\"?|\"?\)$/g,'');
  $(bi).load(function(){
   var bm = new Image();
   var masksrc;
   if (masksrc = HPdiv.css("-webkit-mask-image")) {
    bm.src = masksrc.replace(/^url\(\"?|\"?\)$/g,'');
   } else if (masksrc = $(".mask",HPdiv).css("background-image")) {
    bm.src = masksrc.replace(/^url\(\"?|\"?\)$/g,'');
   } else if (masksrc = $("img",HPdiv).attr("src")) {
    bm.src = masksrc ;
   }
   if (bm.src) $(bm).load(function(){
     HPdiv.animate({"opacity":1},1000);
   });
   else HPdiv.animate({"opacity":1},1000);
  });
 })();
// }
 /*
 4. Хотелось бы, чтобы ссылки на сторонние сайты открывались в новой вкладке.
 Оно и полезнее - читатель не забудет, откуда начал серфинг. А то, бывает, как увлечешься... )))
  Ставить в html target="_blank"
 */
 jQuery("a[href^='http://'][href!='"+location.host+"'][target='']")
 .attr("target","_blank");/*.each(function(){
 console.log(jQuery(this).attr("href"));
}).size();
 /**/
/* верхнее меню */
  var TopMenu = $("div.top-menu");
  if (!$("li.delim",TopMenu).size()) $(".top-menu ul li:not(.last)").after("<li class='delim'>|</li>");
  $(">ul>li:not(.active):has(ul)",TopMenu).unbind().hover(
  function(){
   $(">ul>li.active ul",TopMenu).hide();
   $("ul",$(this)).show();
//   Cufon.refresh();
  },function(){
   $("ul",$(this)).hide();
   $(">ul>li.active ul",TopMenu).show();
//   Cufon.refresh();
  });
// TopMenu.css("opacity",0);
 $("a",TopMenu).css({"width":"auto","min-width":"0"});
 $("a",TopMenu).css("min-width",function(){ return ($(this).text().length*0.7)+"em"});
 if ($.browser.safari||$.browser.opera) $("ul",TopMenu).addClass("s2");
/* выровнять меню по ширине * /
 */$(TopMenu) /*
 .animate({"opacity":0.1},2500,function(){
   var tw=0;
   var ta = $(".top-menu>ul>li>a");
   ta.each(function(){
//    console.log(tw+"+"+$(this).width());
    tw+=$(this).outerWidth();
   })
   var twTo = TopMenu.width();
   var twd = $(">ul>li.delim",TopMenu).size() * $(">ul>li.delim",TopMenu).width();

   var twDim = twTo - tw - twd;
//  console.log(tw+ " - "+twTo + " - " + twd);
//  console.log(twDim );
   var padAdd = Math.floor((twDim )/(2 * ta.size()));
//  console.log(padAdd);
    ta.css("padding","0 "+padAdd+"px");
//  var twche = 10;
//   $(">ul>li",TopMenu).each(function(){
//    console.log(twche+"+"+$(this).width());
//    twche+=$(this).outerWidth();
//   })

//console.log(twche+" ?? "+ twTo);
//   if (twche>twTo) ta.css("padding","0");
  })
*/  .animate({"opacity":1},3000);
/* выровнять меню по ширине */

/* /Верхнее меню */

  /* рамка вокруг изображений */
  var imgBorder = function(e){
   var o = $(this);
    if (o.closest(".column-head,.noborder,.more,.moreshort").size() || o.is(".noborder,.more,.moreshort")) return;
//   if (!o.width()) return;
   if (o.closest(".img-border").size()) {
    ib = o.closest(".img-border");
     if (o.width()) {
      ib.width(o.width()+26);
      if (IE7) {
//       ib.find(".top,.bottom").width(o.width());
//      console.log(o.width()+ " " + ib.find(".top,.bottom").width());
      }
    }  else ib.css("width","auto");
      return;
   }
   var float = o.css("float");o.css("float","none");
   if (o.parent().is("a")) o = o.parent();
   var ib = o.wrap('<div class="img-border"></div>').parent().css("float",float);
   o.before('<div class="TL"><div class="TR"><div class="T"></div></div></div>');
   o.after('<div class="BR"><div class="BL"><div class="B"></div></div></div>');
   o.wrap('<div class="R"><div class="L"></div></div>');
   if (o.width() && IE7) {
//    ib.width(o.width()+26);
    $(".TR,.BL",ib).width(o.width()+26);
   }
  };
  $(".content img:not(.noborder)").load(imgBorder).each(imgBorder);
/**/
// if ($(".paginator a").size() < 2 ) $(".paginator").hide(); // убрать пагинатор если только одна страница

/* облако тегов*/
$(".tagsContent a").each(function(){
 $(this).css("font-size",(Math.round(Math.random()*20)+5)+"px")
 });
 /* Все теги - увеличиваем высоту блока */
 var tagDiv = $(".tagsContent");
 var TminH = 228;
 if (tagDiv.height()>TminH) {
 tagDiv.data("height",tagDiv.height()).height(TminH).css("overflow","hidden").after('<div class="allLink tagSw" style="margin-top:10px"><a href="#">Все теги</a></div>');
 $(".tagSw a").click(function(e){
  e.preventDefault();
  tagDiv.animate({"height":tagDiv.height()==TminH?tagDiv.data("height"):TminH},500);
  $(this).html(tagDiv.height()==TminH?"Свернуть теги":"Все теги");
 });
}


/**/
/* Галерея */
if ($('.gallery .list img').size()) {
var onScroll = function(e){
 if ($('.gallery .list img').size()<=12) return;
   var pyTop = window.pageYOffset || document.documentElement.scrollTop ;
   var o = $('.gallery .content-block');
   if (pyTop>500 && o.not(".fixed")) {
    o.removeClass("absolute").addClass("fixed").css({"top":0,"margin-left":IE7?"5px":"325px"});
    var als = $(".tagsBlock").offset()["top"] - $('.gallery .content-block').height();
    var tals = als - ($(".header").height()+$(".column-head").height());
//console.log(window.pageYOffset + " " +als + " " + tals + " left "+o.offset()["left"]);
    if (pyTop > als) {
     o.removeClass("fixed").addClass("absolute").css({"top":tals,"margin-left":IE7?"5px":"325px"});
    }
   } else // if (o.is(".fixed"))
    o.removeClass("absolute").removeClass("fixed").css({"top":0,"margin-left":0});

  };
//  $(window).scroll(onScroll);
//  $(window).bind("scrollstart,scrollstop,scroll",onScroll);
//  $(window).bind("scrollstop",onScroll);
  $(window).bind("scroll",onScroll);
//  $(window).bind("scrollstart",onScroll);
 /**/
 $('.gallery .list a:has(img)').unbind().click(function(e){
  e.preventDefault();
  var o = $(this),ohref = $(o).attr("href"),
      vo = $('.gallery .content-block .view'),
      io;
  io = $("ul",vo);
  if (!io.size()) {
   io = $('.gallery .list ul').clone();
   $("li",io).css({"display":"block","position":"absolute"}).hide();
   $(".img-border",io).css("width","auto");
   $("img",io).attr("class","").attr("src","");
   $("a",io).lightBox();
   io.appendTo(vo);
  };
  var df = function() {
   $("li:visible",io).fadeOut(500);
   var ia = $("li:has(a[href='"+ohref+"'])",io);
   ia.fadeIn(500,function(){
    // дурацкий сафари
     vo.animate({height:ia.height()},500);
     //$(window).scroll();
     onScroll();
     if (IE7) {
       $("img",io).each(imgBorder);
//       if (io.closest(".content-block").not(".fixed"))
//        io.closest(".content-block").addClass("absolute");
      }
    });
   if (ia.height()>300) vo.animate({height:ia.height()},500);
   $(".gallery .content-block .photoinfo").html($("a",ia).attr("title"));
  };
  if (!$("li:has(a[href='"+ohref+"']) img",io).attr("src"))
   $("li:has(a[href='"+ohref+"']) img",io).attr("src",ohref).load(df);
  else df();
 });
 $('.gallery .list a:has(img):first').click();
/**/
}
/**/
$("form.filter select").change(function(){
 $(this).closest("form").submit();
});
$(".filter input[type='submit']").hide();
/**/
$(".right-sb .media .tabs a").click(function(e){
 e.preventDefault();
 if ($(this).is(".active")) return;
 $(".right-sb .media .tabs a").removeClass("active");
 $(this).addClass("active");
 var tClass = $(this).attr("class").split(" ")[0];
 $(".media-content>div, .allLink",$(".right-sb .media")).addClass("inactive");
 $(".media-content ."+tClass+", .allLink."+tClass,$(".right-sb .media")).removeClass("inactive");
});

/* Форма заказа /**/
 if ($(".orderform").size()) {
  $(".order a").click(function(e){
   e.preventDefault();
   $(".shop").slideUp(500);
   $(".orderform").slideDown(500);
  });
 }
/* Управление изображениями /**/
  if ($(".managecontainer").size()) {
   $("div[class='right-sb']").remove();
  }
/* ajax тексты на страницах с "стихами" /**/
 $(".items .text .closeIcon, .texts-cover").click(function(e){
  e.preventDefault();
  $(".items .text .text-container").fadeOut(500);
  $(".texts-cover").hide();
 });
 $(".items .text .viewIcon").click(function(e){
  e.preventDefault();
  var o = $(this).closest(".text").find(".text-container"),
      vo,
      tco = $(".texts-cover");
  if ($(this).is(".inactive") || !o.size()) return;
//  console.log(o.find(".text-content").text()+"|"+o.html()+ " ?"+(!o.text()?"0":1));
  if (!o.find(".text-content").text()) {
   o.find(".text-content").html("Загрузка...");
   o.find(".text-content").load($(this).attr("href")+" .content .content-block");
  }
  if (o.is(":visible")) vo = true;
  $(".items .text .text-container").fadeOut(500);
  if (!vo) o.fadeIn(500);
  $(".texts-cover",o).show();

 });

/* Визуализация элементов форм
(http://www.xiper.net/collect/html-and-css-tricks/verstka-form/nice-radio.html
 http://www.xiper.net/scripts/cusel/) /**/
   $("input[type='radio']").addClass("niceRadio");
   /* при загрузке страницы меняем обычные на стильные radio */
   jQuery(".niceRadio").each(function() { changeRadioStart(jQuery(this)); });
   function changeRadio(el){
   /* функция смены вида и значения radio при клике на контейнер */
    var el = el,
     input = el.find("input").eq(0);
    var nm=input.attr("name");
    jQuery(".niceRadio input").each(function(){ if(jQuery(this).attr("name")==nm) jQuery(this).parent().removeClass("radioChecked");});
    if(el.attr("class").indexOf("niceRadioDisabled")==-1) {
     el.addClass("radioChecked");
     input.attr("checked", true);
    }
    return true;
   }
   function changeVisualRadio(input) {
   /* меняем вид radio при смене значения */
    var wrapInput = input.parent();
    var nm=input.attr("name");
    jQuery(".niceRadio input").each( function() { if(jQuery(this).attr("name")==nm) jQuery(this).parent().removeClass("radioChecked");});
    if(input.attr("checked"))  wrapInput.addClass("radioChecked");
   }
   function changeRadioStart(el) {
   /* новый контрол выглядит так <span class="niceRadio"><input type="radio" name="[name radio]" id="[id radio]" [checked="checked"] /></span>
    новый контрол получает теже name, id и другие атрибуты что и были у обычного */
    try  {
    var el = el,
     radioName = el.attr("name"),
     radioId = el.attr("id"),
     radioChecked = el.attr("checked"),
     radioDisabled = el.attr("disabled"),
     radioTab = el.attr("tabindex");
     radioValue = el.attr("value");
     if(radioChecked)
      el.after("<span class='niceRadio radioChecked'>"+
       "<input type='radio'"+
       "name='"+radioName+"'"+
       "id='"+radioId+"'"+
       "checked='"+radioChecked+"'"+
       "tabindex='"+radioTab+"'"+
                "value='"+radioValue+"' /></span>");
     else
      el.after("<span class='niceRadio'>"+
       "<input type='radio'"+
       "name='"+radioName+"'"+
       "id='"+radioId+"'"+
       "tabindex='"+radioTab+"'"+
             "value='"+radioValue+"' /></span>");
     /* если контрол disabled - добавляем соответсвующий класс для нужного вида и добавляем атрибут disabled для вложенного radio */
     if(radioDisabled) {
      el.next().addClass("niceRadioDisabled");
      el.next().find("input").eq(0).attr("disabled","disabled");
     }
     /* цепляем обработчики стилизированным radio */
     el.next().bind("mousedown", function(e) { changeRadio(jQuery(this)) });
     el.next().find("input").eq(0).bind("change", function(e) { changeVisualRadio(jQuery(this)) });
     if(jQuery.browser.msie) {
      el.next().find("input").eq(0).bind("click", function(e) { changeVisualRadio(jQuery(this)) });
     }
     el.remove();
    }
    catch(e) {  /*если ошибка, ничего не делаем/**/ }
    return true;
   }

var CUSELparams = {
  changedEl: "select",
  visRows: 5,
  scrollArrows: true
 }
 cuSel(CUSELparams);

/**/

if (IE7 && $(".paginator").size()) {
 var pagW = 0;
 $(".paginator *").each(function() {
  pagW += $(this).width()
    + (!isNaN(a = parseInt($(this).css("margin-left")))?a:0)
    + (!isNaN(a = parseInt($(this).css("margin-right")))?a:0)
    + (!isNaN(a = parseInt($(this).css("padding-left")))?a:0)
    + (!isNaN(a = parseInt($(this).css("padding-right")))?a:0)

 });
 $(".paginator").width(pagW+8);
}
function playerLight() {
  var plc = ['070100','FFFFFF'];
  console.log($("body").is(".night")?"night":"day");

  if ($("body").is(".night")) plc = ['FFFFFF','070100'];
  $(".player").each(function(){ var o = $(this);o.html(o.html().replace(new RegExp(plc[0],"ig"),plc[1]));   })
}
$("body").append(
 $("<div/>").addClass("lightSwitch").text("День / Ночь").attr("title","Включить / выключить свет")
  .mouseenter(function(){$(this).stop().animate({"right":$.browser.msie?"-5px":"-35px"})})
  .mouseleave(function(){$(this).stop().animate({"right":$.browser.msie?"-20px":"-50px"})})
  .click(function(){
   $("body").animate({"opacity":0},1000,function(){
    $(this).toggleClass("day night");
    headPhotoShow(1);
    playerLight();
    $.cookie("dayLight",$("body").is(".night")?1:0);
   }).animate({"opacity":1},1000);
  })
);
 if ($.cookie("dayLight") != undefined) $(".lightSwitch").mouseleave();

 });
 })(jQuery);
}
