$(document).ready(function() {
    var ie6 = ($.browser.msie&&$.browser.version=="6.0")?true:false;

    if (ie6) {
        DD_belatedPNG.fix('*');
    }

    //fancybox
    if ($('.lightbox').length) {
        $('.lightbox').fancybox({
            'titleShow'			: false,
            'overlayOpacity'	: 0.7,
            'overlayColor'		: '#666666',
            'autoScale'			: true
        });
    }
    //flash include
    if ($('#flash').length) {
        $('#flash').flash({
            src: '/flash/flash.swf',
            width: 400,
            height: 280,
            wmode: 'transparent'
        });
    }


    //negotiate popup
    $('.negotiate_input').click(function() {
        $('.popup_negotiate').fadeIn();
        return false;
    });
    $('.popup_negotiate .popup_close').click(function() {
        $(this).parents('.popup_negotiate').fadeOut();
    });
    
    //history preview
    $('.history_list .button').click(
        function() {
            $(this).parent().next('.history').slideToggle();
            return false;
        }
        )
    $('.history_list .history').hide();

    //taby
    $('.box_tabs').each(function() {
        var $tabs_bookmarks = $(this).find('li');
        var $tabs = $(this).next().find('.tabs_container').find('.tab')
        $tabs.hide().first().show();
        $tabs_bookmarks.click(function() {
            $tabs.hide();
            var id = $tabs_bookmarks.index($(this));
            $tabs.eq(id).show();
            $tabs_bookmarks.removeClass('active').removeClass('first_active').removeClass('last_active');
            if ($(this).hasClass('first')) {
                $(this).addClass('first_active');
            } else if ($(this).hasClass('last')) {
                $(this).addClass('last_active');
            } else {
			   $(this).addClass('active');
			}
            return false;
        })
    });
	$('.tabs_container').each(function() {
		$(this).find('.tab').hide().eq(0).show();
	});

	//news box
		$('.box_news .line').each(function() {
			var $news = $(this).find('.big_news, .small_news');
			if ($news.first().height()>$news.last().height()) {
				$news.height($news.first().height())
			} else {
				$news.height($news.last().height())
			}
		});
        

    //cart

    $('.cart_list .number').each(function() {
        var $t = $(this);
        var $minus = $t.find('.minus');
        var $plus = $t.find('.plus');
        var $input_count = $t.find('.input_price');

        $input_count.data({
            'value':$input_count.val()
            })

        $input_count.change(function(){
            var count = parseInt($input_count.val());
            var id = parseInt($t.parent().find('.product_id').val());
            if (count<1) {
                count = 1;
            }
            if (isNaN(count)) {
                count = $(this).data('value');
            }
            $input_count.data({
                'value':count
            })
            $input_count.val(count);
        });

        $minus.click(function() {
            var count = parseInt($input_count.val())-1;
            var id = parseInt($t.parent().find('.product_id').val());
            if (count<1) {
                count = 1;
            }
            $input_count.val(count)
        })

        $plus.click(function() {
            var count = parseInt($input_count.val())+1;
            var id = parseInt($t.parent().find('.product_id').val());
            $input_count.val(count);
        })
    })

    // package

    function clear_product_data(t)
    {
        t.find('.product_name').html('');
        t.find('.photo').html('');
        t.find('.price span').html('');
        t.find('.price strong.netto').html('');
        t.find('.price strong.brutto').html('');

        t.find('.net_price_value').val(0);
        t.find('.net_price_with_discount_value').val(0);
        t.find('.gross_price_value').val(0);
        t.find('.gross_price_with_discount_value').val(0);


        t.find('.more').attr("class", 'more');
        t.find('.more').attr("href", '');
        t.find('.more').html('');
        //t.find('.attribute_list').html('');

        load_package_summary();
    }

    function nomaRound(n)
    {
        return Math.round(n*100)/100
    }

    function load_package_summary()
    {
        var summary_net_value = 0;
        var summary_gross_value = 0;
        var summary_net_value_with_discount = 0;
        var summary_gross_value_with_discount = 0;
        var summary_savings = 0;

        $('.package_form_box').each(function() {
            var t = $(this);
                
            if (t.find('.net_price_value').val())
            {
                var net_price = parseFloat(t.find('.net_price_value').val());
                var gross_price = parseFloat(t.find('.gross_price_value').val());
                var net_price_with_discount = parseFloat(t.find('.net_price_with_discount_value').val());
                var gross_price_with_discount = parseFloat(t.find('.gross_price_with_discount_value').val());
                var savings = gross_price-gross_price_with_discount;

                summary_net_value += net_price;
                summary_gross_value += gross_price;
                summary_net_value_with_discount += net_price_with_discount;
                summary_gross_value_with_discount += gross_price_with_discount;
                summary_savings += savings;
            }
        });

        summary_net_value = nomaRound(summary_net_value);
        summary_gross_value = nomaRound(summary_gross_value);
        summary_net_value_with_discount = nomaRound(summary_net_value_with_discount);
        summary_gross_value_with_discount = nomaRound(summary_gross_value_with_discount);
        summary_savings = nomaRound(summary_savings);


        $('.summary_net_value').html(number_format(summary_net_value, 2, ',', ' ')+' zł');
        $('.summary_gross_value').html(number_format(summary_gross_value, 2, ',', ' ')+' zł');
        $('.summary_net_value_with_discount').html(number_format(summary_net_value_with_discount, 2, ',', ' ')+' zł');
        $('.summary_gross_value_with_discount').html(number_format(summary_gross_value_with_discount, 2, ',', ' ')+' zł');
        $('.summary_savings').html(number_format(summary_savings, 2, ',', ' ')+' zł');
    }

    function load_product_data(t, id, discount)
    {
        var product_data_url = '/product/getProductData';

        $.ajax({
            type: "POST",
            dataType: 'json',
            data: {
                id : id,
                discount: discount
            },
            url: product_data_url,
            success : function(json) {
                //alert(json['test']);
                //$('.summary_price_total strong').html(json['total_value'] + ' zł');
                t.find('.product_name').html(json['name']);
                t.find('.photo').html('<img src="'+json['thumb_url']+'">');
                t.find('.price span').html('cena:');
                
                t.find('.price strong.netto').html(number_format(json['net_price'], 2, ',', ' ') + ' zł netto');
                t.find('.price strong.brutto').html(number_format(json['gross_price'], 2, ',', ' ') + ' zł brutto');

                t.find('.net_price_value').val(json['net_price']);
                t.find('.gross_price_value').val(json['gross_price']);
                t.find('.net_price_with_discount_value').val(json['net_price_with_discount']);
                t.find('.gross_price_with_discount_value').val(json['gross_price_with_discount']);

                        
                t.find('.more').attr("class", 'more button');
                t.find('.more').attr("href", json['product_url']);
                t.find('.more').html('więcej');

                /*
                var list = '';
                for (var category in json['parameters'])
                {
                    list += '<li><span>'+category+'</span><ul>';
                    for (var parameter in json['parameters'][category])
                    {
                        list += '<li>'+parameter+' - '+json['parameters'][category][parameter]+'</li>';
                    }

                    list += '</ul></li>'
                }
                t.find('.attribute_list').html(list);
                */

                load_package_summary();

            },
            error : function() {
                clear_product_data(t);
            }
        });

    }

    function countProducts()
    {
        var products = 0;
        var id = null;
        $('.package_form_box').each(function() {            
            var t = $(this);
            var package_configurator_product = t.find('.package_configurator_product');
            id = parseInt(package_configurator_product.find('option:selected').val());
            if (!isNaN(id))
                {
                    products++;
                }
        });        
        if (products>6)
        {
            products = 6;
        }
        $('#products').val(products);
        $('#display_products').html(products);
        if (products > 0 && products < 6)
        {
            var nextDiscount = products+1;
            $('#display_discount').html($("#discount"+products).val());
            $('#display_next_discount').html($("#discount"+nextDiscount).val());
        }
        else if (products == 6)
        {
            $('#display_discount').html($("#discount"+products).val());
            $('#display_next_discount').html($("#discount"+products).val());
        }
        else
        {
            $('#display_discount').html($("#discount"+0).val());
            $('#display_next_discount').html($("#discount"+1).val());
        }
    }
    
    function getDiscount()
    {
        var products = $("#products").val();
        return $("#discount"+products).val();
    }

    function checkProductData(t, discount)
    {
        var package_configurator_product = t.find('.package_configurator_product');
        var id = parseInt(package_configurator_product.find('option:selected').val());
        if (!isNaN(id))
        {
            load_product_data(t, id, discount)
        }
        else
        {
            clear_product_data(t);
        }
    }

    $('.package_form_box').each(function() {
        countProducts();
        var t = $(this);
        //var discount = $("#discount").val();
        var discount = getDiscount();
        var package_configurator_product = t.find('.package_configurator_product');
            
        // pierwsze odpalenie on load
        var id = parseInt(package_configurator_product.find('option:selected').val());
        if (!isNaN(id))
        {
            load_product_data(t, id, discount)
                    
        }
        else
        {
            clear_product_data(t);
        }

        // inne odpalenia on change
        package_configurator_product.change(function(){
            countProducts();
            discount = getDiscount();

            $('.package_form_box').each(function() {
                var t2 = $(this);
                checkProductData(t2, discount);                
            });
            
            
                
        });

            
    });


});

// koniec package


$(window).load(function() {
    $('.baner_selector_slide').nivoSlider({
        effect:'sliceDown',
        //        # sliceDown
        //        # sliceDownLeft
        //        # sliceUp
        //        # sliceUpLeft
        //        # sliceUpDown
        //        # sliceUpDownLeft
        //        # fold
        //        # fade
        //        # random
        directionNav:false,
        pauseTime:5000,
        controlNavThumbs:false,
        afterChange: function(){
            var index = nivoControls.filter('.active').index();
            var klasa = (index==0)?'first_active':(index==nivoControls.length-1)?'last_active':'active';
            $('.baner_selector ul.links li').removeClass('active').removeClass('first_active').removeClass('last_active').eq(index).addClass(klasa);
            if (index!=0) $('.baner_selector ul.links li').first().addClass('first');
            $('.baner_selector ul.links li span.arrow').hide();
            $('.baner_selector ul.links li').eq(index).children('span.arrow').show();
        }
    });

    $('.baner_selector ul.links li').first().children('span.arrow').show();
    var nivoControls = $('.baner_selector_slide a.nivo-control');

    $('.baner_selector ul.links li').each(function(i){
        var elem = $(this);
        elem.click(function(){
            nivoControls.eq(i).click();
            return false;
        });
    });

    $('.baner_selector ul.links li').eq(0).addClass('first_active');


});

jQuery.log = function(message) {
    if(window.console) {
        console.debug(message);
    } else {
        alert(message);
    }
}

