    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() {
	$('#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">età 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();
                }
            }
        });
	$('#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'
	});
	
	var $paginationBlocks = $('.slider-menu ul > *'); 
	
	$("#slider-pagination-items ul").cycle({
		fx: 'fade',
		timeout: 4000,
		speed: 1500,
		pager: '#slider-menu ul',
		before: function(currSlideElement, nextSlideElement, options, forwardFlag) {
			$paginationBlocks.eq($(currSlideElement).index()).removeClass('activeSlide');
			$paginationBlocks.eq($(nextSlideElement).index()).addClass('activeSlide');
		}, 
		pagerAnchorBuilder: function(index, slide) { 
			return $paginationBlocks.eq(index); 
		}
	});
	
	
	$('#send-to-button').click(function() {
		$('#send-to').dialog('open');

		return false;
	});
						   
	$("a[rel='gallery']").colorbox();
	$("a[rel='video']").colorbox({iframe:true, innerWidth:425, innerHeight:344,current: ' '});
	
	$('a[rel=external]').click(function() {
		window.open($(this).attr('href'));
		return false;
	});
	
	//When page loads...
	$(".tab_content").hide(); //Hide all content
	$("ul.tabs li:first").addClass("active").show(); //Activate first tab
	$(".tab_content:first").show(); //Show first tab content

	//On Click Event
	$("ul.tabs li").click(function() {

		$("ul.tabs li").removeClass("active"); //Remove any "active" class
		$(this).addClass("active"); //Add "active" class to selected tab
		$(".tab_content").hide(); //Hide all tab content

		var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
		$(activeTab).fadeIn(); //Fade in the active ID content
		return false;
	});

	$("#slider-servizi").jCarouselLite({
		btnNext: "#next2",
		btnPrev: "#prev2",
		auto: 5000,
		speed: 500,
		circular: true,
		visible: 2,
		scroll: 1
	});

	$(".datepicker").datepicker();
	$("#focus-dataarrivo").css({'cursor':'pointer'});
	$("#focus-dataarrivo").click(function(){
		$("#datadiarrivo").focus();
	});
	
	
	$("#focus-datapartenza").css({'cursor':'pointer'});
	$("#focus-datapartenza").click(function(){
		$("#datadipartenza").focus();
	});
	
	$(".form-generico").each(function(){
		$(this).validate();
	});

	$('.ui-tabs').tabs({fx: {opacity: 'toggle'}});

	if($("#map").length > 0){
		showmaps();	
	}
					  
});
	

