function set_count_mod(element, delta) {
    var val = parseInt($('#' + element).val());
    val += delta;
    if (val > 0) {
        $('#' + element).val(val);
    }
}

stepcarousel.setup({
    galleryid: 'carousel', //id of carousel DIV
    beltclass: 'belt', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'item', //class of panel DIVs each holding content
    panelbehavior: {
        speed:500,
        wraparound:false,
        persist:false
    },
    defaultbuttons: {
        enable:true,
        moveby: 1,
        leftnav: ['/images/arrow_left.png', -40, 12],
        rightnav: ['/images/arrow_right.png', 20, 12]
    },
    autostep: {enable:true, moveby:1, pause:3000},
    statusvars: ['statusA', 'statusB', 'statusC'], // Register 3 "status" variables
    contenttype: ['inline'] // content type <--No comma following the very last parameter, always!
})

stepcarousel.setup({
    galleryid: 'block-views-image_gallery-block_1', //id of carousel DIV
    beltclass: 'galleries', //class of inner "belt" DIV containing all the panel DIVs
    panelclass: 'clear-block', //class of panel DIVs each holding content
    panelbehavior: {
        speed:500,
        wraparound:true,
        persist:false
    },
    defaultbuttons: {
        enable:true,
        moveby: 3,
        leftnav: ['/images/arrow_left.png', -30, 118],
        rightnav: ['/images/arrow_right.png', 10, 118]
    },
    autostep: {enable:true, moveby:1, pause:3000},
    statusvars: ['statusA', 'statusB', 'statusC'], // Register 3 "status" variables
    contenttype: ['inline'] // content type <--No comma following the very last parameter, always!
})


function makeScrollable(wrapper, scrollable){
    // Get jQuery elements
    var wrapper = $(wrapper), scrollable = $(scrollable);

    // Hide images until they are not loaded
    scrollable.hide();
    var loading = $('<div class="loading">Загрузка...</div>').appendTo(wrapper);

    // Set function that will check if all images are loaded
    var interval = setInterval(function(){
        var images = scrollable.find('img');
        var completed = 0;

        // Counts number of images that are succesfully loaded
        images.each(function(){
            if (this.complete) completed++;
        });

        if (completed == images.length){
            clearInterval(interval);
            // Timeout added to fix problem with Chrome
            setTimeout(function(){

                loading.hide();
                // Remove scrollbars
                wrapper.css({
                    overflow: 'hidden'
                });

                scrollable.slideDown('slow', function(){
                    enable();
                });
            }, 1000);
        }
    }, 100);

    function enable(){
        // height of area at the top at bottom, that don't respond to mousemove
        var inactiveMargin = 99;
        // Cache for performance
        var wrapperWidth = wrapper.width();
        var wrapperHeight = wrapper.height();
        // Using outer height to include padding too
        var scrollableHeight = scrollable.outerHeight() + 2*inactiveMargin;
        // Do not cache wrapperOffset, because it can change when user resizes window
        // We could use onresize event, but it's just not worth doing that
        // var wrapperOffset = wrapper.offset();

        // Create a invisible tooltip
        var tooltip = $('<div class="sc_menu_tooltip"></div>')
        .css('opacity', 0)
        .appendTo(wrapper);

        // Save menu titles
        scrollable.find('a').each(function(){
            $(this).data('tooltipText', this.title);
        });

        // Remove default tooltip
        scrollable.find('a').removeAttr('title');
        // Remove default tooltip in IE
        scrollable.find('img').removeAttr('alt');

        var lastTarget;
        //When user move mouse over menu
        wrapper.mousemove(function(e){
            // Save target
            lastTarget = e.target;

            var wrapperOffset = wrapper.offset();

            var tooltipLeft = e.pageX - wrapperOffset.left;
            // Do not let tooltip to move out of menu.
            // Because overflow is set to hidden, we will not be able too see it
            tooltipLeft = Math.min(tooltipLeft, wrapperWidth - 75); //tooltip.outerWidth());

            var tooltipTop = e.pageY - wrapperOffset.top + wrapper.scrollTop() - 40;
            // Move tooltip under the mouse when we are in the higher part of the menu
            if (e.pageY - wrapperOffset.top < wrapperHeight/2){
                tooltipTop += 80;
            }
            tooltip.css({
                top: tooltipTop,
                left: tooltipLeft
            });

            // Scroll menu
            var top = (e.pageY -  wrapperOffset.top) * (scrollableHeight - wrapperHeight) / wrapperHeight - inactiveMargin;
            if (top < 0){
                top = 0;
            }
            wrapper.scrollTop(top);
        });

        // Setting interval helps solving perfomance problems in IE
        var interval = setInterval(function(){
            if (!lastTarget) return;

            var currentText = tooltip.text();

            if (lastTarget.nodeName == 'IMG'){
                // We've attached data to a link, not image
                var newText = $(lastTarget).parent().data('tooltipText');

                // Show tooltip with the new text
                if (currentText != newText) {
                    tooltip
                    .stop(true)
                    .css('opacity', 0)
                    .text(newText)
                    .animate({
                        opacity: 1
                    }, 1000);
                }
            }
        }, 200);

        // Hide tooltip when leaving menu
        wrapper.mouseleave(function(){
            lastTarget = false;
            tooltip.stop(true).css('opacity', 0).text('');
        });


        //Usage of hover event resulted in performance problems
        scrollable.find('a').hover(function(){
            tooltip
            .stop()
            .css('opacity', 0)
            .text($(this).data('tooltipText'))
            .animate({
                opacity: 1
            }, 1000);

        }, function(){
            tooltip
            .stop()
            .animate({
                opacity: 0
            }, 300);
        });

    }
}


/* jquery.timers plugin */
jQuery.fn.extend({
    everyTime:function(interval,label,fn,times,belay){
        return this.each(function(){
            jQuery.timer.add(this,interval,label,fn,times,belay);
        });
    },
    oneTime:function(interval,label,fn){
        return this.each(function(){
            jQuery.timer.add(this,interval,label,fn,1);
        });
    },
    stopTime:function(label,fn){
        return this.each(function(){
            jQuery.timer.remove(this,label,fn);
        });
    }
});
jQuery.extend({
    timer:{
        guid:1,
        global:{},
        regex:/^([0-9]+)\s*(.*s)?$/,
        powers:{
            'ms':1,
            'cs':10,
            'ds':100,
            's':1000,
            'das':10000,
            'hs':100000,
            'ks':1000000
        },
        timeParse:function(value){
            if(value==undefined||value==null)
                return null;
            var result=this.regex.exec(jQuery.trim(value.toString()));
            if(result[2]){
                var num=parseInt(result[1],10);
                var mult=this.powers[result[2]]||1;
                return num*mult;
            }else{
                return value;
            }
        },
        add:function(element,interval,label,fn,times,belay){
            var counter=0;
            if(jQuery.isFunction(label)){
                if(!times)
                    times=fn;
                fn=label;
                label=interval;
            }
            interval=jQuery.timer.timeParse(interval);
            if(typeof interval!='number'||isNaN(interval)||interval<=0)
                return;
            if(times&&times.constructor!=Number){
                belay=!!times;
                times=0;
            }
            times=times||0;
            belay=belay||false;
            if(!element.$timers)
                element.$timers={};

            if(!element.$timers[label])
                element.$timers[label]={};

            fn.$timerID=fn.$timerID||this.guid++;
            var handler=function(){
                if(belay&&this.inProgress)
                    return;
                this.inProgress=true;
                if((++counter>times&&times!==0)||fn.call(element,counter)===false)
                    jQuery.timer.remove(element,label,fn);
                this.inProgress=false;
            };

            handler.$timerID=fn.$timerID;
            if(!element.$timers[label][fn.$timerID])
                element.$timers[label][fn.$timerID]=window.setInterval(handler,interval);
            if(!this.global[label])
                this.global[label]=[];
            this.global[label].push(element);
        },
        remove:function(element,label,fn){
            var timers=element.$timers,ret;
            if(timers){
                if(!label){
                    for(label in timers)
                        this.remove(element,label,fn);
                }else if(timers[label]){
                    if(fn){
                        if(fn.$timerID){
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    }else{
                        for(var fn in timers[label]){
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }
                    for(ret in timers[label])break;if(!ret){
                        ret=null;
                        delete timers[label];
                    }
                }
                for(ret in timers)break;if(!ret)
                    element.$timers=null;
            }
        }
    }
});

if(jQuery.browser.msie)
    jQuery(window).one("unload",function(){
        var global=jQuery.timer.global;
        for(var label in global){
            var els=global[label],i=els.length;
            while(--i)
                jQuery.timer.remove(els[i],label);
        }
    });



jQuery(document).ready(function() {
    //makeScrollable("div.sc_menu_wrapper", "div.sc_menu");
    $('.tablesorter').tablesorter({
        widgets: ['zebra'],
        headers: {
            5:{
                sorter: false
            },
            6: {
                sorter: false
            }, 
            4: {
                sorter: false
            }

        }
    });

    

    recalcPrice();
    $('.tablesorter :checkbox').click(function() {
        recalcPrice();
    });
    
    $("body").everyTime(5000, function(i) {

        var active = $('#active_pict');
        var currentNum = active.attr('imgnum');
        currentNum++;
        if (currentNum>3) {
            currentNum = 1;
        }

        active.fadeOut(2000);
        active.attr('id', '');
        $('#slideshow img[imgnum='+ currentNum +']').fadeIn(1000).attr('id', 'active_pict');
    });

    $('#pause').click(function() {
        uppodSend('audioplayer1302','pause');
        $('#pause').hide();
        $('#play').show();
    })

    $('#play').click(function() {
        uppodSend('audioplayer1302','play');
        $('#pause').show();
        $('#play').hide();
    });

    $('.ammountTD input').change(function() {
        recalcPrice();
    });

    function recalcPrice() {
        var sum = 0;
        $.each($('.tablesorter :checked'), function(index, item) {
            var text = $(this).parents('tr').find('.priceTD').html();
            var pack = $(this).parents('tr').find('.packTD').html();
            var ammount = pack.match(/[0-9]+/g)[0];
            var packCount = $(this).parents('tr').find('.ammountTD input').val();
            sum += parseFloat(text) * ammount * packCount;
        });
        sum = sum.toFixed(2);
        $('#sum_val').val(sum);
        $('#sum span').text(sum);
        var newSum = false;
        for (var i = 5; i >= 1; i--) {
            var val = checkDiscount(i, sum);
            if (val) {
                newSum = true;
                sum = val.toFixed(2);
                break;
            }
        }
        

        if (newSum) {
            $('#sumdiscount').show().find('#skidkasum').text(sum);
            $('#sum span').addClass('no');
            $('#sum_discounted_val').val(sum);
        } else {
            $('#sum_discounted_val').val(0);
            $('#sumdiscount').hide();
            $('#sum span').removeClass('no');
        }
    }

    function checkDiscount(num, sum) {
        var dis_sum = parseFloat($('#sum' + num).val());
        //alert(dis_sum);
        var discountVal = parseFloat($('#discount' + num).val());
        if (sum > dis_sum) {
            sum = sum - (sum * discountVal / 100);
            $('#skidka').text(discountVal + "%");
            return sum;
        }
        return false;
    }
});
