    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) {
                var min = value.split('-')[0];
                var max = value.split('-')[1];

                if ( !(
                    (
                        id == 0 &&
                        (min == 0 || totalCustomerFilters >= min) &&
                        (max == 0 || totalCustomerFilters <= max)
                    ) ||
                    (
                        id > 0 &&
                        typeof customerFilters[id] != 'undefined' &&
                        (min == 0 || customerFilters[id] >= min) &&
                        (max == 0 || customerFilters[id] <= max)
                    )
                ) )
                {
                    _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 * parseInt(
                $('#' + _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;

            if ( quantity == 0 )
            {
                _this.addClass('disattivo');
                $(':radio', _this).attr('disabled', 'disabled');
            }

            $('.quantity', _this).text(quantity);
            $('.partial-total', _this).text(addCommas(
                subtotal
                    .toFixed(2)
                    .replace('.', ',')
            ));
        });
        $('.total').text(addCommas(
            total
                .toFixed(2)
                .replace('.', ',')
        ));
    }

    $(document).ready(function() {
        
        $('.calendario-invia').click(function() {
            $('#date').focus();
        });

        $.datepicker.setDefaults($.datepicker.regional['it']);
        $('#date').datepicker();

        $('.ui-tabs').tabs({fxFade: true, fxSpeed: 'fast'});

        $('.foto a').colorbox({maxWidth:'75%', maxHeight:'75%'});

        $('#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="flottante-c" id="child_age_field_' + i + '">' +
                                '<label for="child_age_' + i + '" class="generica">eta bambino ' + i + ' <span class="rosso">*</span>:</label>' +
                                '<input id="child_age_' + i + '" name="child_age_' + i + '" type="text" class="required lungo" 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();
                }
            }
        });
        
        var links    = '<ul id="location_alternative">';
        var location = $('#regione');
        var alternativeLocation = $('<input readonly="readonly" type="text" />');
        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 = alternativeLocation.parent('.flottante-destinazione2').length > 0 ?
            {
                target: 'leftTop',
                tooltip: 'rightTop'
            } :
            {
                target: 'rightTop',
                tooltip: 'leftTop'
            }

        $(alternativeLocation).qtip({
            content: {
                text: links,
                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:'#FF9000'}, title: {background:'#FF9000', color:'#fff', 'padding-left':'7px'}}
        });

        $('#send-to').dialog({
            autoOpen: false,
            buttons: {
                'Invia messaggio': 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: 'Invia a un amico'
                            });
                            
                            $this.unblock();
                        }
                    });
                }
            },
            resizable: false,
            title: 'Invia a un amico',
            width: '600px'
        });
        $('#send-to-button').click(function() {
            $('#send-to').dialog('open');

            return false;
        });
		
        updateServices();
        $('.customer').live('keyup', updateServices);
        $('.service input:radio').live('click', updateServices);


        $('a[rel=external]').click(function() {
            window.open($(this).attr('href'));
            
            return false;
        });
    });


	
$('document').ready(function(){
	$("a[rel='shadowbox']").colorbox({ innerWidth:800, innerHeight:600});
	$("a[rel='webcam']").colorbox();
	$("a[rel='video']").colorbox({iframe:true, innerWidth:425, innerHeight:344,current: ' '});
	
	jQuery.extend(jQuery.validator.messages, {
		required: "Questo campo e obbligatorio.",
		remote: "Riempire questo campo per continuare.",
		email: "Inserire un indirizzo email valido.",
		url: "Inserire un indirizzo URL valido.",
		date: "Inserire una data in formato mm-gg-aaaa.",
		dateDE: "Inserire una data in formato gg-mm-aaaa.",
		dateISO: "Inserire una data in formato aaaa-mm-gg.",
		number: "Inserire un numero.",
		digits: "Inserire (solo) un numero.",
		creditcard: "Inserire un numero di carta di credito valido.",
		equalTo: "Inserire lo stesso valore usato sopra.",
		accept: "Usare un'estensione valida.",
		maxlength: jQuery.format("Inserire al massimo {0} caratteri."),
		minlength: jQuery.format("Inserire almeno {0} caratteri."),
		rangelength: jQuery.format("Inserire da {0} a {1} caratteri."),
		range: jQuery.format("Inserire un numero compreso tra {0} e {1}."),
		max: jQuery.format("Inserire un numero minore o uguale a {0}."),
		min: jQuery.format("Inserire un numero maggiore o uguale a {0}.")
	});
							 
	$("#arrival_date").datepicker({
                        inline: true,
                        minDate: new Date(), 
                        maxDate: new Date(2101, 12, 31), 
                        hideIfNoPrevNext: true,
                        beforeShowDay: function(dt) { return [dt.getDay() == 6, ""]; }
                });
	$("#departure_date").datepicker({
                        inline: true,
                        minDate: new Date(), 
                        maxDate: new Date(2101, 12, 31), 
                        hideIfNoPrevNext: true,
                        beforeShowDay: function(dt) { return [dt.getDay() == 6, ""]; }
                });
	$(".datepicker_normal").datepicker();
	$(".datepicker").datepicker({ changeYear: true, yearRange: '1900:2010'  });




	
	$(".form-generico").each(function(){
		$(this).validate({
			 submitHandler: function(form) {
				$(form).submit();
			 }
		});
	});

	
	showmaps();
});
$(document).ready(function(){
	
	if($('#slideshow #warp').length){
		$('#slideshow #warp').cycle({
			fx:     'scrollHorz',
			cleartypeNoBg: true, 
			prev:   '#prev', 
			next:   '#next', 
			timeout: 4000,
			pause: 1,
			speed: 800
		});
	}
	if($("#slider-offerte").length){
		$("#slider-offerte").jCarouselLite({
			btnNext: "#next2",
			btnPrev: "#prev2",
			auto: 5000,
			speed: 500,
			circular: true,
			visible: 2,
			scroll: 1
		});
	}
    $('#tab-descrizione').tabs({ fx: { opacity: 'toggle', duration: 'fast' } });

});	
