var timerID=null;
var hajax=null;

jQuery(document).ready( function(){
    timerID = setTimeout(Clock,1000);

    /* Баннеры */
    jQuery('.banner_link').click(function(event){
        jQuery.post('/ajax/banner-hits.php', {'banner' : $(this).attr('id').replace(/^banner_/, '')});
    });


    /* Tabs */
    var current_page=jQuery.url.attr("path");
    if (current_page=='/index.html' || current_page=='/') {
        var anchor=jQuery.url.attr("anchor");
        if (anchor==null) {
            anchor='#tab_event';
        } else {
            anchor='#tab_'+anchor;
        }
    }
    
    var tab_exist=false;
    var tabs_arr=[];
    jQuery("ul.tabs a").each(function (i) {
        var id_tab=$(this).attr("href");
        tabs_arr.push(id_tab);
        if (id_tab==anchor) {
            jQuery(this).parent().addClass('active');
            tab_exist=true;
        }
        jQuery(this).attr("rel",id_tab);
        if (current_page!='/index.html' && current_page!='/') {
            jQuery(this).attr("href",'/index.html#'+id_tab.substr(5));
        } else {
            jQuery(this).attr("href","javascript:void(0)");
            jQuery(this).click(function (event) {
                var el=jQuery(event.currentTarget);
                var sel_tab=el.attr('rel');
                if (current_page!='/index.html' && current_page!='/') {
                    //location.href='/index.html#'+sel_tab.substr(5);
                    //window.location='/index.html#'+sel_tab.substr(5);
                } else {
                    //location.href='/index.html#'+sel_tab.substr(5);
                    jQuery("ul.tabs li").each(function (i) {
                        jQuery(this).removeClass('active');
                    });
                    el.parent().addClass('active');
                    jQuery.map(tabs_arr, function(value){
                        if (value!=sel_tab && !jQuery(value).hasClass('notshow'))  jQuery(value).addClass('notshow');
                        else if (value==sel_tab) jQuery(value).removeClass('notshow');
                    });
                }
            });
        }
    });
    if (current_page=='/index.html' || current_page=='/') {
        if (tab_exist) {
            jQuery.map(tabs_arr, function(value){
                if (value!=anchor && !jQuery(value).hasClass('notshow'))  jQuery(value).addClass('notshow');
                else if (value==anchor) jQuery(value).removeClass('notshow');
            });
        } else {
            jQuery("ul.tabs li:first").addClass('active');
        }
    }
    
    $(".top_menu a").tooltip({track: true, delay: 0, showBody: " - ", showURL: false});
    $(".tabs a").tooltip({track: true, delay: 0, showBody: " - ", showURL: false, extraClass: "blue"});
    
    if($("#datepicker_start").length!=0) {
        $.datepicker.regional['ru'] = {
            closeText: 'Закрыть',
            prevText: '&#x3c;Пред',
            nextText: 'След&#x3e;',
            currentText: 'Сегодня',
            monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
            'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
            monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
            'Июл','Авг','Сен','Окт','Ноя','Дек'],
            dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
            dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
            dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
            dateFormat: 'dd.mm.yy', firstDay: 1,
            isRTL: false};
        $.datepicker.setDefaults($.datepicker.regional['ru']);    
    
        var dates = $("#datepicker_start, #datepicker_end").datepicker({
            dateFormat:'dd-mm-yy',
			onSelect: function(selectedDate) {
				var option = this.id == "datepicker_start" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
			}        
        });
    }
    
    InitCalendar('.calendar');
});

function LogoHide(el)
{    
    $(el).addClass('focus');    
}
function LogoShow(el)
{    
    $(el).removeClass('focus');
}

function Clock()
{
    var now = new Date(); 
    var hours = now.getHours(); 
    var minutes = now.getMinutes();
    var timeValue = "" + ((hours >24) ? hours -24 :hours); 
    timeValue += ((minutes < 10) ? " : 0" : " : ") + minutes;
    $('#time').text(timeValue);
    
    var day = now.getDay(); 
    var weekday= now.getDate(); 
    weekday = ((weekday < 10) ? "0" : "") + weekday;
    var month = now.getMonth(); 
    var year= now.getYear();     
    if  (year<2000) year = year + 1900;  
    var arr_days=["воскресенье", "понедельник", "вторник", "среда", "четверг", "пятница", "суббота"]
    var arr_month=["января", "февраля", "марта", "апреля", "мая", "июня", "июля", "августа", "сентября", "октября", "ноября", "декабря"];
    dateValue=arr_days[day]+", "+weekday+" "+arr_month[month]+" "+year+" г."
    $('#date').text(dateValue);

    timerID = setTimeout(Clock,1000);    
}

function intval( mixed_var, base ) {
    var tmp;
    if( typeof( mixed_var ) == 'string' ){
        tmp = parseInt(mixed_var);
        if(isNaN(tmp)){
            return 0;
        } else{
            return tmp.toString(base || 10);
        }
    } else if( typeof( mixed_var ) == 'number' ){
        return Math.floor(mixed_var);
    } else{
        return 0;
    }
}

function InitCalendar(output, init_month, init_year)
{    
    if (init_month && init_year)
    {
        init_month--;
    } else {
        var caledar = new Date();
        init_month = caledar.getMonth();  //0 - 11
        init_year = caledar.getFullYear();            
    }
    
    hajax=$.ajax({
        type: "POST",
        url: '/ajax/getevents.php',
        dataType: 'json',
        data: 'y='+init_year+'&m='+(init_month+1),
        beforeSend: function() {
            var height=$('#ab_cal').innerHeight();
            $('#ab_cal').append('<div class="overlay png"></div><div class="wait"></div>');
            $('#ab_cal .overlay').height(height);
            $('#ab_cal .wait').height(height);        
        },
        success: function(data) {
            $('#ab_cal').html('<div class="calendar">'+$('#ab_cal .calendar').html()+'</div>'); //так как применяется хак для PNG в IE6 то там создается VML код который просто так не удалить поэтому делаем так :)
            PostInitCalendar(output, data.month, data.year, data.events);
        },
        complete: function() {
            $('#ab_cal .overlay').remove();
            $('#ab_cal .wait').remove();            
        }
    });    
}

function PostInitCalendar(output, init_month, init_year, events)
{
    var weekday_str=['', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
    var month_str=['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];

    if (init_month && init_year)
    {
        init_month--;
        var caledar = new Date(init_year, init_month, 1);
    } else {
        var caledar = new Date();
        init_month = caledar.getMonth();  //0 - 11
        init_year = caledar.getFullYear();            
    }
    
    var today = new Date();    
    var date_today = today.getDate();
    var month_today = today.getMonth();  //0 - 11
    var year_today = today.getFullYear();    
    var weekday_today = today.getDay(); //0 - воскресенье
    if (weekday_today==0) weekday_today=7;
    
    var weekday_start = new Date(init_year, init_month, 1).getDay();
    if (weekday_start==0) weekday_start=7;
    var dayCount = new Date(init_year, init_month + 1, 0).getDate();
    
    //var all_cell=dayCount+(weekday_start-1);
    //var col_lines=all_cell/7;
    //if ((col_lines-intval(col_lines))>0) col_lines=intval(col_lines)+1;
    var col_lines=6;
    
    var html='<table>';
    html+='<thead>';
    html+='<tr><td colspan="7"><div class="month_left png"><img src="/images/blank.gif" width="16" height="16" alt="" /></div><div class="month_right png"><img src="/images/blank.gif" width="16" height="16" alt="" /></div><div class="month_year">'+month_str[init_month]+' '+init_year+'</div></td></tr>';
    html+='<tr>';
    for(var i=1; i<=7; i++)
    {
        html+='<td>'+weekday_str[i]+'</td>';
    }
    html+='</tr></thead>';
    html+='<tbody>';
    var ffirst=true;
    var cday=1;
    var class_today='';
    var init_month_str=((init_month+1)<10?'0':'')+(init_month+1);
    for(var j=0; j<col_lines; j++)
    {
        html+='<tr>';
        for(var i=1; i<=7; i++)
        {
            if (ffirst && i<weekday_start) {
                html+='<td>&nbsp;</td>';
            } else {
                ffirst=false;
                if (cday<=dayCount) {
                    if (cday==date_today && month_today==init_month && year_today==init_year) {
                        class_today=' class="today"';
                    } else {
                        class_today='';
                    }
                    html+='<td'+class_today+'>';
                    if (jQuery.inArray(init_year+'-'+init_month_str+'-'+(cday<10?'0':'')+cday, events)!=-1)
                    {
                        html+='<a href="/event.html?date='+init_year+'-'+init_month_str+'-'+(cday<10?'0':'')+cday+'">'+cday+'</a>';
                    } else {
                        html+=cday;
                    }
                    html+='</td>';
                    cday++;
                } else {
                    html+='<td>&nbsp;</td>';
                }
            }
        }
        html+='</tr>';
    }    
    html+='</tbody>';
    html+='</table>';
    
    $(output).html(html);
    
    $(output+' .month_left').click(function (event) {
        var new_month=init_month-1;
        var new_year=init_year;
        if (new_month<0) {
            new_month=11;
            new_year--;
        }
        $(this).unbind('click');
        InitCalendar(output, new_month+1, new_year);
    });
    
    $(output+' .month_right').click(function (event) {
        var new_month=init_month+1;
        var new_year=init_year;
        if (new_month>11) {
            new_month=0;
            new_year++;
        }
        $(this).unbind('click');
        InitCalendar(output, new_month+1, new_year);
    });
}
