$(document).ready(function(){
    
    Cufon.replace('h1, h2, .menu a, a.menu');
    
    // prettyPhoto
    
    $("a[rel^='prettyPhoto']").prettyPhoto({theme: 'facebook'});
    
    // Меню вверху
    
    $('.menutop').hover(function(){
        $('.sub').hide();
        $('.sub[i='+$(this).attr('i')+']').show();
        clearTimeout($('.sub[i='+$(this).attr('i')+']').data('timeout'));
    }, function(){
        $('.sub[i='+$(this).attr('i')+']').data('timeout', setTimeout('$(".sub[i='+$(this).attr('i')+']").hide()', 500));
    });
    
    $('.sub').hover(function(){
        clearTimeout($(this).data('timeout'));
    }, function(){
        clearTimeout($(this).data('timeout'));
        $(this).data('timeout', setTimeout('$(".sub[i='+$(this).attr('i')+']").hide()', 500));
    });
    
    // Меню слева
    
    $('.menu2').hover(function(){
        $('.sub2').hide();
        $('.sub2[i='+$(this).attr('i')+']').show();
        clearTimeout($('.sub2[i='+$(this).attr('i')+']').data('timeout'));
    }, function(){
        $('.sub2[i='+$(this).attr('i')+']').data('timeout', setTimeout('$(".sub2[i='+$(this).attr('i')+']").hide()', 500));
    });
    
    $('.sub2').hover(function(){
        clearTimeout($(this).data('timeout'));
    }, function(){
        clearTimeout($(this).data('timeout'));
        $(this).data('timeout', setTimeout('$(".sub2[i='+$(this).attr('i')+']").hide()', 500));
    });
    
    // Datepicker для мероприятий
    
    if ($('#datepicker').length) {
        var years = new Array();
        $('#datepicker').datepicker({
            dateFormat:'yymmdd',
            defaultDate:$('#datepicker').attr('date') ? $('#datepicker').attr('date') : null,
            beforeShowDay:function(date){
                
                var year = date.getFullYear();
                var day = Math.ceil((date.getTime() - (new Date(year, 0, 1)))/86400000);
                var res = new Array();
                
                // Первый запуск
                if (!years.length) {
                    years[year] = $('#datepicker').attr('daysofyear');
                }
                
                // Перелистнули на другой год
                if (!years[year]) {
                    daysofyear = '';
                    $.ajax({
                        url:'/action/daysofyear/year-'+year+'/',
                        async:false,
                        success:function(data){
                            years[year] = data;
                        }
                    });
                }
                
                res[0] = parseInt(years[year].substr(day, 1)) ? true : false;
                
                return res;
                
            }, onSelect:function(dateText){
                location.href = $(this).attr('href')+'date-'+dateText+'/';
            },
            onChangeMonthYear:function(year, month){
                location.href = $(this).attr('href')+'year-'+year+'/month-'+month+'/';
            }
        });
    }
    
    // Подвал - в подвал
    
    fill();
    $('.bg').attr('height', Math.min($(window).height(), 450));
    
    // Виртуальный тур
    
    $('#virtual a[class!="img"]').live('click', function(){
        loadvirtual($(this).attr('href'));
        return false;
    });
    
    // Валидация форм
    
    $('form.validate').validate();
        
    // Для главной страницы ротация фоток
    
    if ($('#mainpage_big').length) {
        $('#mainpage_big img, #mainpage_small img').each(function(){
            $('<img>').attr('src', $(this).attr('src'));
        });
        setTimeout('cycle();', 5000);
    }
    
    // Видео
    
    $('object[data$=".flv"]').each(function(){
        var swf = new SWFObject('/i/player.swf', 'ply', '400', '300', '9', '#ffffff');
        swf.addParam('allowfullscreen', 'true');
        swf.addParam('allowscriptaccess', 'always');
        swf.addParam('wmode', 'opaque');
        swf.addVariable('file', $(this).attr('data'));
        $(this).replaceWith(swf.getSWFHTML());
    });
    
    // Быстрые диалоги
    
    $('.load').click(function(){
        $('<div></div>').load($(this).attr('href')+'ajax-1/', function(){
            $('form.validate').validate();
        }).dialog({
            title:$(this).attr('title').length ? $(this).attr('title') : $(this).html(),
            buttons:{
                'Закрыть':function(){
                    $(this).dialog('destroy');
                }
            },
            modal:true,
            width:640,
            height:480,
            resizable:false,
            draggable:false
        });
        return false;
    });
    
    $('.dialog').click(function(){
        $('<div></div>').load($(this).attr('href')+'ajax-1/', function(){
            $('form.validate').validate();
        }).dialog({
            title:$(this).attr('title').length ? $(this).attr('title') : $(this).html(),
            buttons:{
                'Отмена':function(){
                    $(this).dialog('destroy');
                },
                'Ok':function(){
                    $(this).find('form').submit();
                }
            },
            modal:true,
            width:500,
            resizable:false,
            draggable:false
        });
        return false;
    });
        
});

function fill() {
    if ($('body').outerHeight()<$(window).height()) {
        $('#filler').attr('height', $(window).height()+$('#filler').parent().height()-$('body').outerHeight());
    }
}

function loadpage(id) {
    var convert = {
        409:'/content/id-50/',
        428:'/content/view/id-1/',
        429:'/content/view/id-2/',
        411:'/content/id-53/',
        397:'/content/view/id-3/',
        393:'/content/view/id-4/',
        390:'/content/view/id-5/',
        394:'/content/view/id-6/',
        395:'/content/view/id-7/',
        396:'/content/view/id-8/',
        400:'/content/view/id-9/',
        432:'/content/view/id-10/',
        399:'/content/view/id-11/',
        398:'/content/view/id-12/',
        414:'/content/view/id-13/',
        415:'/content/view/id-14/',
        416:'/content/view/id-15/',
        417:'/content/view/id-16/',
        412:'/content/id-68/',
        391:'/content/view/id-17/',
        392:'/content/view/id-18/',
        402:'/content/view/id-19/',
        401:'/content/view/id-20/',
        418:'/content/view/id-21/',
        419:'/content/view/id-22/',
        420:'/content/view/id-23/',
        423:'/content/view/id-24/',
        421:'/content/view/id-25/',
        422:'/content/view/id-26/',
        427:'/content/view/id-27/',
        413:'/content/id-80/',
        408:'/content/view/id-25/',
        407:'/content/view/id-26/',
        406:'/content/view/id-27/',
        424:'/content/view/id-25/',
        425:'/content/view/id-26/'
    };
    loadvirtual(convert[id]);
}

function loadvirtual(link) {
    $('#virtual').html('<center><br /><br /><br /><br /><br /><br /><img src="/i/ajaxload.gif" /></center>');
    fill();
    $('#virtual').load(link+'ajax-1/', fill);
}

function cycle() {
    
    var i = ($('#mainpage_big img').length - $('#mainpage_big img:visible ~ img').length)%7;
    var p = 0;
    var interval = 1500;
    
    // Картинки
    $('#mainpage_big').css('background', 'url('+$('#mainpage_big img:eq('+i+')').attr('src')+') top right no-repeat');
    $('#mainpage_small').css('background', 'url('+$('#mainpage_small img:eq('+i+')').attr('src')+') top left no-repeat');
    $('#mainpage_big img:visible, #mainpage_small img:visible').fadeOut(interval, function(){
        if ((++p)==2) {
            $('#mainpage_big img:eq('+i+'), #mainpage_small img:eq('+i+')').show();
        }
    });
    
    // Подписи
    if ($('#cycle_title:visible').length) {
        $('#cycle_title').fadeOut(interval/2, function(){
            if ($('#mainpage_big img:eq('+i+')').attr('title')) {
                $('#cycle_title_text').html($('#mainpage_big img:eq('+i+')').attr('title'));
                $('#cycle_title').fadeIn(interval/2);
            }
        });
    }
    else {
        if ($('#mainpage_big img:eq('+i+')').attr('title')) {
            $('#cycle_title_text').html($('#mainpage_big img:eq('+i+')').attr('title'));
            setTimeout("$('#cycle_title').fadeIn(500);", interval/2);
        }
    }
    
    setTimeout('cycle();', 5000);
    
}

$.validator.addMethod('phone', function(ph, element) {
    if (this.optional(element)) {
        return true;
    }
    var stripped = ph.replace(/[\s()+-]|ext\.?/gi, '');
    // 6 is the minimum number of numbers required
    return ((/\d{6,}/i).test(stripped));
}, 'Пожалуйста, введите корректный номер телефона.');

