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() {
$.datepicker.setDefaults($.datepicker.regional['it']);
        $('#datadipartenza').datepicker({
            "buttonImage"     : $base + "/images/bg_calend.jpg",
            "buttonImageOnly" : true,
            "numberOfMonths"  : 2,
            "showButtonPanel" : true,
            "showOn"          : "both",
            "showOtherMonths" : true,
            "stepMonths"      : 2
        });						   
			
	 $("#loadopen").colorbox({open:true, iframe:true, innerWidth:930, innerHeight:530,onClosed: function(){scroll(0,0);}});		
			
	$('#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();
                }
            }
        });
	
	
        selectToTooltip($('#lmr'), true, 'località: ');
        selectToTooltip($('#city'), true, 'città: ');
		selectToTooltip($('#rgn'), true, 'regione: ');
	
	
	$('#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;
	});
});
function selectToTooltip(select, firstOptionIsDefault, textPrefix)
    {
        var $select    = $(select),
            $input     = $("<input />", {"readonly": "readonly"}),
            textPrefix = typeof textPrefix == 'undefined' ? '' : textPrefix;

        $input.data("select", $select);
        $select.data("input", $input);
        $select.before($input);
        $select.hide();

        if ( firstOptionIsDefault === true )
        {
            $input.val($select.find('option:first').text());
        }

        $input.focus(function() {
            var $input         = $(this),
                $select        = $input.data("select"),
                $options       = $('<ul />'),
                $selectOptions = $select.find('option');

            if ( firstOptionIsDefault === true )
            {
                $selectOptions = $selectOptions.not(':eq(0)');
            }

            $selectOptions.each(function() {
                var $this   = $(this);
                var $option = $('<li />', {
                    "text" : $this.text(),
                    "click": function() {
                        $select
                            .val($this.val())
                            .change();

                        $input.val(textPrefix + $this.text());
                        $input.qtip('destroy');
                    }
                });

                $options.append($option);
            });

            $input.qtip({
                content: {
                    text: $options,
                    title: $select.find('option:first').text()
                },
                hide: {
                    fixed: true,
                    event: "unfocus"
                },
                position: {
                    viewport: $(window)
                },
                show: {
                    event: "focus"
                },
                style: {
                    tip: true,
                    classes: "ui-tooltip-italiahotels"
                },
                events: {
                    hide: function(event, api) {
                        api.destroy();
                    }
                }
            });

            $input.qtip("show");
        });
	
	/*
			
		$('#rgn')
            .change(function() {
				$("select#lmr").empty();
                $("select#lmr").data('input').val('località');		
				$value = $(this).val();
				if($value > 0){
				$.getJSON($base+'/loadCerca.php',{'type':'provincia','idregione':$value}, function(j) {
				var options = '';
					options += '<option value="0">seleziona zona</option>';
				
				for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].id_localita + '">' + ucfirst(j[i].localita.toLowerCase()) + '</option>';
				}
				$("select#lmr").html(options);
				$("select#lmr").attr("disabled",false);
				$("select#lmr").val(0);
				});
				}
				return false;
            })
			
	
		$('#comune')
            .change(function() {
				$("select#city").empty();
                $("select#city").data('input').val('località');		
				$value = $(this).val();
				if($value > 0){
				$.getJSON($base+'/loadCerca.php',{'type':'localita','idcomune':$value}, function(j) {
				var options = '';
					options += '<option value="0">seleziona localit&agrave;</option>';
				
				for (var i = 0; i < j.length; i++) {
				options += '<option value="' + j[i].id_localita + '">' + ucfirst(j[i].localita.toLowerCase()) + '</option>';
				}
				$("select#city").html(options);
				$("select#city").attr("disabled",false);
				$("select#city").val(0);
				});
				}
				return false;
            })
			*/
			
			
    }
