jQuery.fn.extend({'money_slider': function(options) {
        if (typeof(options) == 'undefined') {
            options = {};
        }

        var fields = {
            count:    'count',
            price:    'price',
            max:      'max'
        };

        var result = this.find('.result');

        for (var field in fields) {
            if (!jQuery.isFunction(fields[field])) {
            
                if (typeof(options[field + '_field']) != 'undefined') {
                    fields[field] = options[field + '_field'];
                }

                fields[field] = this.find('[name=' + fields[field] + ']');
            }
        }

        function calc() {
            var price   = fields.price.val().replace(',', '.');
            var prod    = price * fields.count.val();
            result.html(money(prod));
        }

        var slider = this.find('.slider').slider({
            orientation: 'horizontal',
            range: 'min',
            min: 0,
            max: fields.max.val(),
            slide: function(event, ui) {
                fields.count.val(ui.value);
                calc();
            }

        });

        var max_value = fields.max.val();

        fields.count.change(function() {
            var value = $(this).val() * 1;
            if (value > max_value) {
                fields.count.val(fields.max.val());
            }
            slider.slider('option', 'value', value);
            calc();
        });

        fields.price.change(calc);
        fields.count.trigger('change');
    }
});



jQuery(document).ready(function($) {
    $('a[rel*=facebox]').facebox({
        loading_image : '/facebox/loading.gif',
        close_image   : '/facebox/closelabel.gif'
    });

    $('.tabs').tabs();

    $('form.buy_market_share').money_slider({count_field: 'amount', max_field: 'max_amount'});
    $('form.buy_from_proposal').money_slider({ count_field: 'amount', max_field: 'max_amount' });
    $('form.create_sell_proposal').money_slider({ count_field: 'amount', max_field: 'max_amount', price_field: 'price' });

    $('form.confirm').bind('submit', function() {
        var $form = $(this);
        var title = $form.attr('title');
        var question = $form.find('input[type=submit]').attr('title');
        $('<div class="confirm-submit">' + question + '</div>').dialog({
            modal: true,
            resizable: false,
            draggable: false,
            closeOnEscape: false,
            title: title,
            buttons: {
                'Ja': function() {
                    var $dialog = $(this);
                    $form.unbind('submit'); 
                    $form.submit();
                    $(this).dialog('close').remove();
                },      
                'Nee': function() {
                    $(this).dialog('close');
                    return false;
                }
            } 
        });
        return false;
    });


    $('form div.dialog').each(function() {

        var $form = $(this).parents('form:first');

        var dialog = $(this).dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                'Ok': function() {
                    // re-append the dialog inside the form
                    $form.append(dialog);
                    // unbind the submit
                    $form.unbind('submit');
                    // and repeat the submit
                    $form.submit();
                    $('body').hide();
                },
                'Annuleren': function() {
                    dialog.dialog("close");
                }
            }
        });

        $form.submit(function() {
            dialog.dialog("open");
            return false;
        });
    });

    $('input.date').each(function(i, el) {
        el = $(el);
        var options = { 
        };
        var dp;

        if (el.hasClass('option')) {
            options.maxDate = '+3m';
            options.minDate = '+1d';
			options.beforeShowDay = $.datepicker.noWeekends;
        }
        
        if (el.attr('type') == 'hidden') {

            // insert empty div
            el.after('<div></div>');
            options.inline = true;
            options.altField = el;
            options.altFormat = 'mm/dd/yy';

            dp = el.next().datepicker(options);
        } else {
            dp = el.datepicker(options);
        }

    });
    
    /** 
     * Recalculate option info in write-out form
     */
    $('form.write-option').each(function() {

        var $count   = $(this).find('input[name=count]');
        var $price   = $(this).find('input[name=price]');
        var $target  = $(this).find('span.product');

        var update = function() {
            var value = 0;
            // get count as a number
            var count = $count.val(); //isNaN($count.val()) ? 0 : $count.val();
            // get price as a number, if it's not a number, try if replacing comma's by dots works
            var price = isNaN($price.val()) ? (
                isNaN($price.val().replace(/,/, '.')) ? 0 : $price.val().replace(/,/, '.')
            ) : $price.val();

            $target.html(money(count * price));
        };

        $count.change(update);
        $price.change(update);

        update();
    });
});

function money (n, c, d, t){ //v1.0
    var precision = 4;
	var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
	/(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
	return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
	"$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
};
