    function addCommas(nStr)
    {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + '.' + '$2');
        }
        return x1 + x2;
    }

    function updateServices(e)
    {
        if ( e )
        {
            var _this = $(this);

            if ( isNaN(String.fromCharCode(e.which)) )
            {
                _this.val((_this.val().match(/(\d+)/g) || []).join(''));
            }
        }

        var customerFilters = [];
        var totalCustomerFilters = 0;
        var total = 0;

        $('.customer').each(function() {
            var _this = $(this);
            var categoryId = _this.attr('id').replace('customer_', '');

            customerFilters[categoryId] = parseInt(_this.val(), 10);

            if ( isNaN(customerFilters[categoryId]) )
            {
                customerFilters[categoryId] = 0;
            }

            totalCustomerFilters += customerFilters[categoryId];
        });
        $('.service').each(function() {
            var _this = $(this);
            var check = true;
            var quantity = 0;
            var subtotal = 0;
            $.each(_this.metadata().filters, function(id, value) {
                if ( !(
                    (id == 0 && totalCustomerFilters >= value)
                    || (typeof customerFilters[id] != 'undefined' && customerFilters[id] >= value)
                ))
                {
                    _this.addClass('disattivo');
                    $(':radio', _this).attr('disabled', 'disabled');
                    check = false;

                    return false;
                }
            });

            if ( check )
            {
                _this.removeClass('disattivo');
                $(':radio', _this).removeAttr('disabled');

                if ( _this.is('.ad_personam') )
                {
                    var category = _this.metadata().category;

                    if ( category == 0 )
                    {
                        $('.customer').each(function() {
                            var subquantity = parseInt($(this).val(), 10);

                            if ( isNaN(subquantity) )
                            {
                                subquantity = 0;
                            }

                            quantity += subquantity;
                        });
                    }
                    else
                    {
                        quantity = parseInt($('#customer_' + category).val(), 10);

                        if ( isNaN(quantity) )
                        {
                            quantity = 0;
                        }
                    }
                }
                else
                {
                    quantity = 1;
                }
            }

            subtotal = quantity * parseFloat(
                $('#' + _this.attr('id') + ' input[name=services\\[' + (_this.attr('id').replace('service_', '')) + '\\]]:checked').parent().find('.price').text()
                    .replace('.', '')
                    .replace(',', '.')
                , 10
            );

            if ( isNaN(subtotal) )
            {
                quantity = 0;
            }

            total += subtotal;

            $('.quantity', _this).text(quantity);
            $('.partial-total', _this).text(addCommas(
                subtotal
                    .toFixed(2)
                    .replace('.', ',')
            ));
        });
        $('.total').text(addCommas(
            total
                .toFixed(2)
                .replace('.', ',')
        ));
    }

    $(function() {
        
        $('.calendario-invia').click(function() {
            $('#date').focus();
        });
        $.datepicker.setDefaults($.datepicker.regional['it']);
        $('#date,.calendar').datepicker();
    
        updateServices();
        $('.customer').live('keyup', updateServices);
        $('.service input:radio').live('click', updateServices);

        $('a[href$=.pdf]').addClass('pdf');

        $('#slider-img').cycle({
            fx: 'fade', // choose your transition type, ex: fade, scrollUp, shuffle, etc...
            random: 1
        });
        
        $('a[rel=gallery]').colorbox({maxWidth:'75%', maxHeight:'75%'});

        $('a[rel=external]').click(function() {
            window.open($(this).attr('href'));

            return false;
        });

        $('#nation').change(function() {
            if ( $(this).val() == 82 )
            {
                $('#city-field').show();
            }
            else
            {
                $('#city-field').hide();
            }
        });
        $('#nation').change();

        $('#children').keyup(function() {
            var childrenField = $('#children_field');
            var children      = parseInt($(this).val(), 10);
            var maxChildren   = 20;

            if( isNaN(children) )
            {
                for ( var i = 1; i <= maxChildren; i++ )
                {
                    $('#child_age_field_' + i).remove();
                }
            }
            else
            {
                children = Math.min(Math.max(children, 0), maxChildren);

                for ( var i = 1; i <= children; i ++ )
                {
                    if ( !$('#child_age_field_' + i).length )
                    {
                        var childAgeField = $(
                            '<p class="text" id="child_age_field_' + i + '">' +
                                '<label for="child_age_' + i + '" class="text-title">età bambino ' + i + '*:</label>' +
                                '<input id="child_age_' + i + '" name="child_age_' + i + '" type="text" class="testo" value="0" size="" />' +
                            '</p>'
                        );

                        if ( i == 1 )
                        {
                            childAgeField.insertAfter(childrenField);
                        }
                        else
                        {
                            childAgeField.insertAfter($('#child_age_field_' + (i - 1)));
                        }
                    }
                }

                for ( var i = children + 1; i <= maxChildren; i++ )
                {
                    $('#child_age_field_' + i).remove();
                }
            }
        });
        $('#send-to').dialog({
            autoOpen: false,
            buttons: {
                'Richiedi password': function() {
                    $this = $(this).parents('.ui-dialog');

                    $('#send-to form').ajaxSubmit({
                        beforeSubmit: function() {
                            $('#send-to .errore').text('');
                            $this.block({message: null});
                        },
                        success: function(response) {
                            response = eval('(' + response + ')');

                            switch ( response.status )
                            {
                                case 'fail':
                                    $.each(response.errors, function(name, message) {
                                        $('#st_' + name + '_label').text(message);
                                    });
                                break;
                                case 'success':
                                    $('#send-to .errore').text('');
                                    $('#send-to').dialog('close');
                                break;
                            }

                            var dialog = $('<div />');
                            dialog.text(response.message);
                            dialog.dialog({
                                buttons: {
                                     'Ok': function() {$(this).dialog('close');}
                                },
                                modal: true,
                                resizable: false,
                                title: 'Recupera password'
                            });

                            $this.unblock();
                        }
                    });
                }
            },
            resizable: false,
            title: 'Recupera password',
            width: '400px'
        });
        $('#send-to-button').click(function() {
            $('#send-to').dialog('open');

            return false;
        });
         $("#slide-offerte").jCarouselLite({
            btnNext: "#next",
            btnPrev: "#prev",
            auto: 5000,
            speed: 500,
            circular: true,
            visible: 2,
            scroll: 1
            });
            
        var links    = '<ul id="location_alternative">';
        var location = $('#regione');
        var alternativeLocation = $('<input readonly="readonly" type="text" class="text-cerca" />');
        alternativeLocation.val($('option:selected', location).text());

        $('option', location).each(function(index) {
            if ( index == 0 )
            {
                return;
            }

            var $this = $(this);

            links += '<li><a href="' + escape($this.val()) + '" class="location_option">' + $this.html() + '</a></li>';
        });

        links += '</ul>';

        $('.location_option').live('click', function() {
            var $this = $(this);
            var locationId = $this.attr('href');

            if ( !$.support.hrefNormalized )
            {
                var regExp = new RegExp('http://' + document.location.host + document.location.pathname);
                locationId = locationId.replace(regExp, '');
            }

            location.val(locationId);
            alternativeLocation.val($this.text());

            $(alternativeLocation).qtip('hide');

            return false;
        });

        location.hide();
        alternativeLocation.insertAfter(location);

        var corner = {
            target: 'leftTop',
            tooltip: 'rightTop'
        }

        $(alternativeLocation).qtip({
            content: {
                text: links,
                title: 'Seleziona il luogo dell\'escursione'
            },
            hide: {fixed: true, when: 'unfocus'},
            position: {
                corner: corner
            },
            show: 'focus',
            style: { /*height: 400,*/name: 'light', tip: true, width: 630, border: {width: 3, radius: 5, color:'#038789'}, title: {background:'#038789', color:'#fff', 'padding-left':'7px'}}
        });
        
        
        
        
        
        var links2    = '<ul id="location_alternative2">';
        var location2 = $('#regione2');
        var alternativeLocation2 = $('<input readonly="readonly" type="text" class="text-cerca" />');
        alternativeLocation2.val($('option:selected', location2).text());

        $('option', location2).each(function(index) {
            if ( index == 0 )
            {
                return;
            }

            var $this = $(this);

            links2 += '<li><a href="' + escape($this.val()) + '" class="location_option2">' + $this.html() + '</a></li>';
        });

        links2 += '</ul>';

        $('.location_option2').live('click', function() {
            var $this = $(this);
            var locationId = $this.attr('href');

            if ( !$.support.hrefNormalized )
            {
                var regExp = new RegExp('http://' + document.location.host + document.location.pathname);
                locationId = locationId.replace(regExp, '');
            }

            location2.val(locationId);
            alternativeLocation2.val($this.text());

            $(alternativeLocation2).qtip('hide');

            return false;
        });

        location2.hide();
        alternativeLocation2.insertAfter(location2);

        var corner = {
            target: 'rightTop',
            tooltip: 'leftTop'
        }

        $(alternativeLocation2).qtip({
            content: {
                text: links2,
                title: 'Scegli la tua destinazione'
            },
            hide: {fixed: true, when: 'unfocus'},
            position: {
                corner: corner
            },
            show: 'focus',
            style: { /*height: 400,*/name: 'light', tip: true, width: 630, border: {width: 3, radius: 5, color:'#038789'}, title: {background:'#038789', color:'#fff', 'padding-left':'7px'}}
        });


        $.getScript('http://browser-update.org/update.js');

        $('.button-contatti')
            .click(function() {$('#form').toggle();})
            .click();

        $('#payment-form').submit();

        $('a[href*=#flights]').bind('click', function() {
            $(this).colorbox({href: 'http://online.touramatravel.it/customizations/searchFlights.php?cstz=dagtur', iframe: true, height: '95%', width: '760px', open: true});

            return false;
        });
    });
