$().ready(function() {
    $timeout    = 500;
    $closetimer = 0;
    $ddmenuitem = 0;

    ddm_open = function() {
        ddm_canceltimer();
        ddm_close();
        $ddmenuitem = $(this).find('ul').css('visibility', 'visible');
    };

    ddm_close = function() {
        if($ddmenuitem)
            $ddmenuitem.css('visibility', 'hidden');
    };

    ddm_timer = function() {
        $closetimer = window.setTimeout(ddm_close, $timeout);
    };

    ddm_canceltimer = function() {
        if($closetimer) {
            window.clearTimeout($closetimer);
            $closetimer = null;
        }
    };

    $('#ddmenu > li').bind('mouseover', ddm_open);
    $('#ddmenu > li').bind('mouseout',  ddm_timer);

    document.onclick = ddm_close;

    getCurrentTime = function() {
        $date = new Date();
        $hours = $date.getHours();
        $setHour = ($hours < 10 ? '0' + $hours : $hours);
        $minutes = $date.getMinutes();
        $setMin = ($minutes < 10 ? '0' + $minutes : $minutes);
        $seconds = $date.getSeconds();
        $setSec = ($seconds < 10 ? '0' + $seconds : $seconds);
        setTimeout("getCurrentTime()", 1000);
        $('.date-top').html($current + ' ' + $setHour + ':' + $setMin + ':' + $setSec);
    }
    
    document.onload = getCurrentTime();
    
    var calendar = function () {
        $.post('/get-date/', function(data) {
            $currentDays = data;
            $("#calendar").datepicker(
                {autoSize:true,
                 dateFormat: 'yy-mm-dd',
                 minDate: new Date(2011, 1 - 1, 1),
                 maxDate: new Date(),
                 beforeShowDay: getDays,
                 onSelect: function(dateText, inst) {
                            document.location.href = '/news/date/' + dateText + '/';
                          }
                 }
            );
        }, "json");
    }
    
    var getDays = function(date) {          
           for (i = 0; i < $currentDays.length; i++) {
              if (date.getMonth() == $currentDays[i][0] - 1
                  && date.getDate() == $currentDays[i][1]) {
                return [true, $currentDays[i][2] + '_day'];
              }
            }
          return [false, ''];
    }
    
    document.onload = calendar();
    
    $("#gallery a").fancybox({
        'titlePosition'  : 'over',
        'titleFormat'    : function(title, currentArray, currentIndex, currentOpts) {
            return '<span id="fancybox-title-over">Image ' +  (currentIndex + 1) + ' / ' + currentArray.length + '. ' + title + '.</span>';
        }
    });
});
