Array.prototype.max = function() {
    var max = this[0],
        len = this.length;
    
    for (var i = 1; i < len; i++) {
        if (this[i] > max) {
            max = this[i];
        }
    }
    
    return max;
}

jQuery.fn.extend({
    popup: function() {
        var t = $(this);
        
        if (t.data('popup')) {
            return;
        }
        
        t.data('popup', popup = $('<div class="popup" style="display: none;"><div class="shadow"></div><div class="box">' +
                        '<span class="close">закрыть</span><div class="popup-content"></div>' +
                        '</div></div>').appendTo(document.body));
        
        $('.popup-content', popup).append(t);
        
        $('.close', popup).click(function() {
            popup.hide();
        });
        
        var box = $('.box', popup);
        
        popup.bind('popup-position', function() {
            var top = $(window).scrollTop() + ($(window).height() - box.height()) / 2;
            
            box.css({'margin-left': -(box.width() / 2), 'top': top > 30 ? top : 30});
        });
        
        popup.bind('popup-show', function() {
            popup.show().height($(document).height()).trigger('popup-position');
        }).trigger('popup-show');
        
        return this;
    }
});

$(function() {
    var headerTime = $('#header .time'),
        pad = function(n) { return n < 10 ? '0' + n : n };
    
    setInterval(function() {
        var d = new Date();
        headerTime.html(pad(d.getDate()) + '/' + pad(d.getMonth() + 1) + '/' + d.getFullYear() + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()));
    }, 1000);
    
	$('.image-titled img').load(function() {
		var img = $(this);
		img.closest('.image-titled').width(img.width()).addClass('image-titled-loaded');
	});
	
	$('#menu').bind('menuSetHeight', function() {
	    var t = $(this);
	    
	    t.height($('ul.menu:visible', t).map(function() { return $(this).outerHeight(); }).get().max());
	    
	}).trigger('menuSetHeight');
	
	if ($.fn.tsort) {
    	$('.table-sort-order:not(.js-sort-order-disabled)').delegate('th a', 'click', function(event) {
    	    event.preventDefault();
	    
    	    var t = $(this),
    	        th = t.closest('th'),
    	        table = t.closest('.table-sort-order'),
    	        order = !t.hasClass('asc') ? 'asc' : 'desc';
	    
    	    $('tr:gt(0)', table).tsort('td:eq(' + th.index() + ')', {order: order});
	    
    	    $('th a', table).removeClass();
    	    t.addClass(order);
    	}).each(function() {
    	    if ($('th a.asc, th a.desc', this).length == 0) {
    	        $('th:eq(0) a').click();
    	    }
    	});
	}
	
	$('.a-calculator').live('click', function(event) {
	    event.preventDefault();
	    
	    if (!(calculator = $('.calculator-popup')).length) {
	       $.get(this.href, function(d) {
                var popup = $(d).popup();
                $('dd input', popup).focus(function() {
                    $(this).closest('li').addClass('active').siblings('li').removeClass('active');
                }).keyup(function() {
                    var t = $(this);
                    
                    if ((oldVal = t.data('old-val')) && oldVal == t.val()) {
                    	return;
                    }
                    t.val(val = (parseFloat(t.val()) || 0)).data('old-val', val);

                    var v = val / parseFloat(t.data('coefficient'));

                    $(':not(.active) input', t.closest('ul')).each(function() {
                    	var input = $(this);

                    	input.val(Math.round(parseFloat(input.data('coefficient')) * v * 100) / 100);
                    });
                });

                $('dt input', popup).click(function() {
                    var t = $('dt input:checked', popup),
                        dt = t.closest('dt'),
                        dd = dt.siblings('dd:eq(' + dt.index() + ')').show();
                    
                    dd.siblings('dd').hide();
                    
                    $('input', dd).first().focus().keyup();
                }).first().click();
	       });
	    } else {
	        calculator.closest('.popup').trigger('popup-show');
	    }
	});

	$('.page-controls .control-print').click(function(event) {
	    event.preventDefault();
	    
	    window.print();
	});

	$('.filters-form .submit, .filters-form input[type="checkbox"], .filters-form input[type="radio"]').click(function(event) {
	    if ($(this).is('a')) {
    		event.preventDefault();
	    }
		$(this).closest('form').submit();
	});
});


