// ie ашч для лєйблов
if(window.iamIE)  {
    window.onload = function(){  
        var a = document.getElementsByTagName("label");
        for(var i=0,j=a.length;i<j;i++){
          if(a[i].hasChildNodes && a[i].childNodes.item(0).tagName == "IMG")          {
            a[i].childNodes.item(0).forid = a[i].htmlFor;
            a[i].childNodes.item(0).onclick = function(){
              var e = document.getElementById(this.forid);
              switch(e.type){
                case "radio": e.checked|=1;break;
                case "checkbox": e.checked=!e.checked;break;
                case "text": case "password": case "textarea": e.focus(); break;
              }
            }
          }
        }
  }
}

function handleFlashClick(banId) {
    //alert('You clicked on flash-banner with id=' + banId);
       
    var urlTo = $('.banner #' + banId + ' param[name="outerUrl"]').val();
    if ( urlTo && (urlTo != '' || urlTo != 'http://') )
        window.document.location = urlTo;
    
    return true;    
}

function open_popupVK (url){
    open_popup( url, 40 ,10, 920, 760, 1);
}

function open_popup(url, posx, posy, size_w, size_h, scroll) {
    if (window.iamIE) {
        msg=window.open(url,'jmd','scrollbars=1,status=0,toolbar=0,directories=0,menubar=0,location=1,resizable=0,width='+size_w+',height='+size_h+', left='+posx+', top='+posy+'');
    } else {
        msg=window.open(url,'jmd','scrollbars='+scroll+',status=0,toolbar=yes,chrome=yes,directories=0,menubar=1,location=0,resizable=0,width='+size_w+',height='+size_h+', left='+posx+', top='+posy+'');
    }
}
    
var headerBG = {};   // Глобальный объект для хранения ссылок на фоновые изображения в шапке

$(function(){

// Для IE6 фиксим фон у input в комбобоксе
if (window.DD_belatedPNG) {
    DD_belatedPNG.fix('div.sexy input');
}

if (headerBG.src){
    $('#header .bg').css('backgroundImage', 'url(' + headerBG.src[0] + ')');
    headerBG.current = 1;


// МЕНЯЕМ ФОН В ШАПКЕ
headerBG.interval = setInterval(function(){
    //alert('length ' + headerBG.src.length + ' headerBG.current ' + headerBG.current);
    if (headerBG.src.length == 0 || headerBG.src.length == 1 && headerBG.current == 1) return;
    if (!headerBG.current || headerBG.current >= headerBG.src.length) headerBG.current = 0;
    $('#header .bg').fadeOut('slow',function(){
        $(this).css('backgroundImage', 'url(' + headerBG.src[headerBG.current] + ')').fadeIn('slow');
        headerBG.current++;
    });
}, headerBG.freq);
}

// МЕНЮ
var nav = $('#nav');
var activeHeight = $('.active .subnav', nav).height();
if ($('.active .subnav', nav).size() > 0) {
    nav.height(42 + activeHeight);
}
   
// Фикс для IE6, потому что он не понимает селекторов такого вида ".first.active"
if (window.iamIE6) {
    $('#nav td.active:first-child').addClass('firstActive');
    $('#nav td.active:last-child').addClass('last-child');    
}

if (window.iamIE7){
    $('#nav td:last-child').addClass('last-child');
}

// ВЕШАЮ КАРУСЕЛИ
/*
$('#carousel ul').jcarousel({
    vertical: true,
    scroll: 1,
    animation : 1000
});
*/

$('.jcarousel-skin-bubu').jcarousel({
    scroll: 1,
    animation : 5,
    wrap : 'both'
    //auto : 4
});

$('.jcarousel-prev, .jcarousel-next').live('mouseover', function() {
    $(this).addClass('hovered');
}).live('mouseout', function() {
    $(this).removeClass('hovered');
});

if (window.iamIE){
    //$('.jcarousel-skin-tango .jcarousel-container-vertical').css('height', '280px').children('.jcarousel-clip-vertical').css('height', '278px');
}
var hAdd = (window.iamIE) ? 40 : 45; 

if (window.DD_belatedPNG) {
    DD_belatedPNG.fix('.jcarousel-skin-bubu .jcarousel-prev, .jcarousel-skin-bubu .jcarousel-next');
} 

// АККОРДИОН
var accordion = $('#accordion');
$('.active', accordion).css('height', 'auto');

$('li a', accordion).hover(function(){
    if ($(this).parent()[0].className != 'active') {
        var imageHeight = $(this).find('img').height();
        var heightIn;
        if (window.iamIE6) { heightIn = '32px' }    // Для IE6
        else heightIn = '33px';                     // Для всех остальных
        $('.active', accordion).removeClass('active').stop().animate({ height : heightIn });
        $(this).parent().addClass('active').stop().animate({ height : imageHeight + 2 });
    }
});

// Делаем аккордион фиксированной высоты
$(window).bind('load', function(){
    if (window.iamIE)
        accordion.height(accordion.height() - 7);
    else 
        accordion.height(accordion.height());
});

// Обработчик для поля поиска
var searchFeild = $('#search input');
var searchFeildVal = searchFeild.val();
searchFeild.focus(function(){
    if($(this).val() === searchFeildVal) { $(this).val('') };
}).blur(function(){
    if($(this).val() === '') { $(this).val(searchFeildVal) };
});

// Раскрывалка блоков в левой колонке
var expBlocks = $('.expandeble');

var hAdd = (window.iamIE) ? 40 : 45;
$('.expandeble .h').hover(function(){
    var content = $(this).children('.c');//.show();
    var contentHeight = content.height();
    if ( contentHeight ){        
        $(this).stop().animate({'height': contentHeight + hAdd }, 'slow'); 
        $(this).next().next().stop().animate({'opacity': 0.0}, 300);              
        
        content.fadeIn();//.animate({'background-position': '0 0'}, 300);//.fadeIn(); 
    }
    return false;
}, function(){
    var content = $(this).children('.c');
    var contentHeight = content.height();
    if ( contentHeight ){        
        $(this).next().next().stop().animate({'opacity': 1.0}, 300);
        $(this).stop().animate({height: $(this).height() - contentHeight - 10 }, 'slow'); 
        
        content.fadeOut();//.animate({'background-position': '10 0'}, 300);//.fadeOut();
    }
});
        
    // РАСКРЫВАЛКА СТАТЕЙ
    var page = $('#page');    
    var expanderTitle = '';
    $('.expander', page).click( function() {
        var rel = $(this).attr('rel');
        $('.expander.expanderE', page).each(function(){
            if ($(this).attr('rel') == rel)
                return;

            $(this).removeClass('expanderE').find('span').show();
            var par = $(this).parent().parent();            
            par.find('.contBody, h2 .expander').hide();
        });       
        
        if ( !$(this).hasClass('expanderE') ){
            $('.expander[rel=' + rel + ']').addClass('expanderE').find('span').hide();
            $(this).parent().parent().find('.contBody').show();
            $('h2 .expander[rel=' + rel + ']').show();            
        } else {
            $('.expander[rel=' + rel + ']').removeClass('expanderE').find('span').show();
            $(this).parent().parent().find('.contBody').hide();            
            $('h2 .expander[rel=' + rel + ']').hide();                       
        }
        
        $('#page .contentItemContainer, #page .contentItems')
            .scrollTo( 'a[name="'+rel+'"]'
                , 1500
                , { easing: 'swing', queue:true , offset:{top: (window.iamIE)? -15 : -5 } } 
            );
    }) 
    
    
    // переход при клике на баннер, внутренние страницы, низ, бока
    $('div.bn:not(#vk)').live('click', function(){
        window.document.location = $(this).find('.banner a').attr('href');
    });
    
    // $('div.bn#vk').unbind('click');
    // переход при клике на баннер, внутренние страницы, низ, бока
    $('div.bn#vk').live('click', function(event){
        open_popupVK($(this).find('.banner a').attr('href'));
        
        return false;
    });    
    $('div.bn#vk a').live('click', function(event){
        open_popupVK($(this).attr('href'));
        
        return false;
    });        
})
