_render_formatted_value = function(label, value) {
    return '<b style="float: right;">' + value + '</b>' + label + ':<br/>';
}

/**
 * function cm2ftin(float len)
 *
 * Convert centimeters (metric) to feet and inches (imperial)
 *
 * len:     The amount of centimeters to convert
 *
 * Returns: The length as a string in feet and inches in the format
 *              XX'YY"
 *
 */
function cm2ftin(len) {
    ft_conv = 30.48;
    in_conv = 2.54;
    feet = Math.floor(len / ft_conv);
    inches = Math.floor((len % ft_conv) / in_conv);
    return feet + "\"" + inches + "\'";
}

/**
 * function format_height(float height)
 *
 * Format the height (in centimeters) to a string with both
 * imperial and metric units.
 *
 * height:  The height to format
 *
 * Returns: A string in the format
 *              XX cm / YY'ZZ"
 *
 */
function format_height(height) {
    text = _render_formatted_value('Metric (SI)', height + ' cm');
    text += _render_formatted_value('Imperial', cm2ftin(height));
    return text;
//return height + ' cm / ' + cm2ftin(height);

}

function format_local_height(height) {
    /**
     * TODO Make local formatting for more than SI
     */
    return height + ' cm';
}

/**
 * function format_weight(float weight)
 *
 * Format the (metric) weight of a person to a string with
 * both imperial and metric units.
 *
 * weight:  The weight (in kilograms) to be formatted
 *
 * Returns: A string in the format
 *              XX kg / YY lbs
 *
 */
function format_weight(weight) {
    lbs_conv = 2.2046;
    w = parseFloat(weight);
    text = _render_formatted_value('Metric (SI)', w.toFixed(1) + ' kg');
    pounds = Math.round(w * lbs_conv);
    text += _render_formatted_value('Imperial', pounds + ' lbs');
    text += _render_formatted_value('UK/IE', Math.floor(pounds/14) + ' st ' + pounds % 14 + ' lbs');
    return text;
//return w.toFixed(1) + ' kg / ' + Math.round(w * lbs_conv) + ' lbs';
}

function format_local_weight(weight) {
    /**
     * TODO Make local formatting for more than SI
     */
    w = parseFloat(weight);
    return w.toFixed(1) + ' kg';
}

function format_bust_size(size) {
    eu_jap = size;
    us_uk = size * 2/5 + 4;
    b_e_f = parseInt(size) + 15;
    aus_nz = size * 2/5 - 18;
    text = _render_formatted_value('US/UK', us_uk);
    text += _render_formatted_value('EU/JAP', eu_jap);
    text += _render_formatted_value('B/E/F', b_e_f);
    text += _render_formatted_value('AUS/NZ', aus_nz);
    return text;
}

function format_cup_size(size) {
    eu_jap = ['','A','B','C','D','E','F','G','H','I','J','K'];
    us = ['','AA','A','B','C','D','DD','DDD/E','F','G','H','I'];
    uk = ['','A','B','C','D','DD','E','F','G','H','I','J'];
    aus_nz = ['','AA','A','B','C','D','DD','E','F','G','H','I'];
    text = _render_formatted_value('US', us[size]);
    text += _render_formatted_value('UK', uk[size]);
    text += _render_formatted_value('EU/JAP', eu_jap[size]);
    text += _render_formatted_value('AUS/NZ', aus_nz[size]);
    return text;
}

function format_bra_size(size, cup) {
    cup_eu_jap = ['','A','B','C','D','E','F','G','H','I','J','K'];
    cup_us = ['','AA','A','B','C','D','DD','DDD/E','F','G','H','I'];
    cup_uk = ['','A','B','C','D','DD','E','F','G','H','I','J'];
    cup_b_e_f = cup_eu_jap;
    cup_aus_nz = ['','AA','A','B','C','D','DD','E','F','G','H','I'];
    bust_eu_jap = size;
    bust_us = size * 2/5 + 4;
    bust_uk = bust_us;
    bust_b_e_f = parseInt(size) + 15;
    bust_aus_nz = size * 2/5 - 18;
    text = _render_formatted_value('US', bust_us + cup_us[cup]);
    text += _render_formatted_value('UK', bust_uk + cup_uk[cup]);
    text += _render_formatted_value('EU/JAP', bust_eu_jap + cup_eu_jap[cup]);
    text += _render_formatted_value('B/E/F', bust_b_e_f + cup_b_e_f[cup]);
    text += _render_formatted_value('AUS/NZ', bust_aus_nz + cup_aus_nz[cup]);
    return text;
}

function format_local_bra_size(size, cup) {
    /**
     * TODO Make local formatting for more than EU/JAP
     */
    cup_eu_jap = ['','A','B','C','D','E','F','G','H','I','J','K'];
    bust_eu_jap = size;
    if(size=='' || cup=='')
        return '';
        
    return bust_eu_jap + cup_eu_jap[cup];
}

function format_jeans_size_width_male(size) {
    in_conv = 2.54;
    imp = size;
    si = Math.round(size * in_conv);
    text = _render_formatted_value('Inches', imp);
    text += _render_formatted_value('Centimeters', si);
    return text;
}

function format_jeans_size_width_female(size) {
    return format_jeans_size_width_male(size);
}

function format_jeans_size_height_male(size) {

    if(size=='') return '';

    in_conv = 2.54;
    imp = size;
    si = Math.round(size * in_conv);
    text = _render_formatted_value('Inches', imp);
    text += _render_formatted_value('Centimeters', si);
    return text;
}

function format_jeans_size_height_female(size) {
    return format_jeans_size_height_male(size);
}

function format_jeans_size(width, height) {
    in_conv = 2.54;
    width = (width || 0);
    height = (height || 0);
    si_width = Math.round(width * in_conv);
    si_height = Math.round(height * in_conv);
    text = _render_formatted_value('Inches', width + '/' + height);
    text += _render_formatted_value('Centimeters', si_width + '/' + si_height);
    return text;
}

function format_local_jeans_size(width, height) {
    /**
     * TODO Make local formatting for more than EU
     */
    return (width || 0) + '/' + (height || 0);
}

function format_dress_size(size) {
    us_ca = size - 28;
    uk_aus_nz = size - 26;
    a_ch_d_nl_s = size;
    b_e_f_p = size + 2;
    i = size + 6;
    ru = size + 8;
    jap = size - 25;

    eu_sml = {
        30: 'XS',
        32: 'XS',
        34: 'XS',
        36: 'S',
        38: 'S',
        40: 'M',
        42: 'M',
        44: 'L',
        46: 'L',
        48: 'XL',
        50: 'XL',
        52: '2XL',
        54: '2XL'
    }
    us_sml = {
        30: 'XS',
        32: 'XS',
        34: 'S',
        36: 'S',
        38: 'M',
        40: 'M',
        42: 'L',
        44: 'L',
        46: 'XL',
        48: '1X',
        50: '2X',
        52: '&gt;2X',
        54: '&gt;2X'
    }

    text = _render_formatted_value('US/CA', us_ca + ' (' + us_sml[a_ch_d_nl_s] + ')');
    text += _render_formatted_value('UK/AUS/NZ', uk_aus_nz);
    text += _render_formatted_value('A/CH/D/NL/S', a_ch_d_nl_s + ' (' + eu_sml[a_ch_d_nl_s] + ')');
    text += _render_formatted_value('B/E/F/P', b_e_f_p);
    text += _render_formatted_value('I', i);
    text += _render_formatted_value('RU', ru);
    text += _render_formatted_value('JAP', jap);
    return text;
}

function format_local_dress_size(size) {
    /**
     * TODO Make local formatting for more than A/CH/D/NL/S
     */
    return size;
}
function format_pants_size_male(size) {
    us_ca = size - 28;
    uk_aus_nz = size - 26;
    a_ch_d_nl_s = size;
    b_e_f_p = size + 2;
    i = size + 6;
    ru = size + 8;
    jap = size - 25;

    eu_sml = {
        44: 'S',
        46: 'S',
        48: 'M',
        50: 'M',
        52: 'L',
        54: 'L',
        56: 'XL',
        58: 'XL',
        60: '2XL',
        62: '2XL'
    }
    us_sml = {
        30: 'XS',
        32: 'XS',
        34: 'S',
        36: 'S',
        38: 'M',
        40: 'M',
        42: 'L',
        44: 'L',
        46: 'XL',
        48: '1X',
        50: '2X',
        52: '&gt;2X',
        54: '&gt;2X'
    }

    text = _render_formatted_value('Size', a_ch_d_nl_s + ' (' + eu_sml[a_ch_d_nl_s] + ')');
    /*
    text = _render_formatted_value('US/CA', us_ca + ' (' + us_sml[a_ch_d_nl_s] + ')</b><br/>';
    text += _render_formatted_value('UK/AUS/NZ', uk_aus_nz);
    text += _render_formatted_value('A/CH/D/NL/S', a_ch_d_nl_s + ' (' + eu_sml[a_ch_d_nl_s] + ')</b><br/>';
    text += _render_formatted_value('B/E/F/P', b_e_f_p);
    text += _render_formatted_value('I', i);
    text += _render_formatted_value('RU', ru);
    text += _render_formatted_value('JAP', jap);
    */
    return text;
}

function format_local_pants_size_male(size) {
    /**
     * TODO Make local formatting for more than A/CH/D/NL/S
     */
    return size;
}

function format_pants_size_female(size) {
    us_ca = size - 28;
    uk_aus_nz = size - 26;
    a_ch_d_nl_s = size;
    b_e_f_p = size + 2;
    i = size + 6;
    ru = size + 8;
    jap = size - 25;

    eu_sml = {
        30: 'XS',
        32: 'XS',
        34: 'XS',
        36: 'S',
        38: 'S',
        40: 'M',
        42: 'M',
        44: 'L',
        46: 'L',
        48: 'XL',
        50: 'XL',
        52: '2XL',
        54: '2XL'
    }
    us_sml = {
        30: 'XS',
        32: 'XS',
        34: 'S',
        36: 'S',
        38: 'M',
        40: 'M',
        42: 'L',
        44: 'L',
        46: 'XL',
        48: '1X',
        50: '2X',
        52: '&gt;2X',
        54: '&gt;2X'
    }

    text = _render_formatted_value('Size', a_ch_d_nl_s + ' (' + eu_sml[a_ch_d_nl_s] + ')');
    /*
    text = _render_formatted_value('US/CA', us_ca + ' (' + us_sml[a_ch_d_nl_s] + ')</b><br/>';
    text += _render_formatted_value('UK/AUS/NZ', uk_aus_nz);
    text += _render_formatted_value('A/CH/D/NL/S', a_ch_d_nl_s + ' (' + eu_sml[a_ch_d_nl_s] + ')</b><br/>';
    text += _render_formatted_value('B/E/F/P', b_e_f_p);
    text += _render_formatted_value('I', i);
    text += _render_formatted_value('RU', ru);
    text += _render_formatted_value('JAP', jap);
    */
    return text;
}

function format_local_pants_size_female(size) {
    /**
     * TODO Make local formatting for more than A/CH/D/NL/S
     */
    return size;
}

function format_shoe_size_male(size) {
    pp_conv = 2/3; // Paris point conversion from cm
    in_conv = 2.54; // Inch convertion from cm
    last_cm = size * pp_conv;
    last_in = last_cm / in_conv;

    eu = size;
    uk_aus_nz = round_to(last_in * 3 - 25, 0.5);
    us_ca = uk_aus_nz + 1;
    us_ath = round_to(last_cm - 20, 0.5);
    asia = round_to(last_cm - 2, 0.5);
    kr = asia * 10;
    jap = uk_aus_nz + 19;

    text = _render_formatted_value('EU', pretty_fraction(eu));
    text += _render_formatted_value('UK/AUS/NZ', pretty_fraction(uk_aus_nz));
    text += _render_formatted_value('US/CA', pretty_fraction(us_ca));
    text += _render_formatted_value('US ath', pretty_fraction(us_ath));
    text += _render_formatted_value('ASIA', asia);
    text += _render_formatted_value('KR', kr);
    text += _render_formatted_value('JAP', jap);
    return text;
}

function format_local_shoe_size_male(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    eu = Math.floor(size) + ((size - Math.floor(size)) ? '½':'');
    return eu;
}

function format_shoe_size_female(size) {
    pp_conv = 2/3; // Paris point conversion from cm
    in_conv = 2.54; // Inch convertion from cm
    last_cm = size * pp_conv;
    last_in = last_cm / in_conv;

    eu = size;
    uk = round_to(last_in * 3 - 25.5, 0.5);
    aus_nz = uk + 1
    us_ca = uk + 2.5;
    us_ath = round_to(last_cm - 19, 0.5);
    asia = round_to(last_cm - 2, 0.5);
    kr = asia * 10;
    jap = uk + 19;

    text = _render_formatted_value('EU', pretty_fraction(eu));
    text += _render_formatted_value('UK', pretty_fraction(uk));
    text += _render_formatted_value('AUS/NZ', pretty_fraction(aus_nz));
    text += _render_formatted_value('US/CA', pretty_fraction(us_ca));
    text += _render_formatted_value('US ath', pretty_fraction(us_ath));
    text += _render_formatted_value('ASIA', asia);
    text += _render_formatted_value('KR', kr);
    text += _render_formatted_value('JAP', jap);
    return text;
}

function format_local_shoe_size_female(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    eu = Math.floor(size) + ((size - Math.floor(size)) ? '½':'');
    return eu;
}

function format_shirt_size_male(size) {
    in_conv = 2.54; // Inch convertion from cm
    eu = size;
    us_uk = round_to(size / in_conv + 0.04, 0.5); // 0.04 used to fix the scale a bit
    text = _render_formatted_value('EU', eu);
    text += _render_formatted_value('US/UK', pretty_fraction(us_uk));
    return text;
}

function format_local_shirt_size_male(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

function format_shirt_size_female(size) {
    eu = size;
    us = size - 8;
    uk = size - 6;
    text = _render_formatted_value('EU', eu);
    text += _render_formatted_value('US', us);
    text += _render_formatted_value('UK', uk);
    return text;
}

function format_local_shirt_size_female(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

function format_suit_size_male(size) {
    jap_sizes = {
        42: 'S',
        44: 'S',
        46: 'S',
        48: 'M',
        50: 'L',
        52: 'L',
        54: 'LL',
        56: 'LL',
        58: 'LL'
    }
    eu = size;
    us_uk = size - 10;
    jap = jap_sizes[size];
    text = _render_formatted_value('EU', eu);
    text += _render_formatted_value('US/UK', us_uk);
    text += _render_formatted_value('JAP', jap);
    return text;
}

function format_local_suit_size_male(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

function format_bust_girth(size) {
    in_conv = 2.54; // Inch convertion from cm
    eu = size;
    us_uk = round_to(size / in_conv + 0.04, 0.5); // 0.04 used to fix the scale a bit
    text = _render_formatted_value('Metric (SI)', eu + ' cm');
    text += _render_formatted_value('Imperial', us_uk + ' in');
    return text;
}

function format_local_bust_girth(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

function format_waist_girth(size) {
    in_conv = 2.54; // Inch convertion from cm
    eu = size;
    us_uk = round_to(size / in_conv + 0.04, 0.5); // 0.04 used to fix the scale a bit
    text = _render_formatted_value('Metric (SI)', eu + ' cm');
    text += _render_formatted_value('Imperial', us_uk + ' in');
    return text;
}

function format_local_waist_girth(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

function format_hip_girth(size) {
    in_conv = 2.54; // Inch convertion from cm
    eu = size;
    us_uk = round_to(size / in_conv + 0.04, 0.5); // 0.04 used to fix the scale a bit
    text = _render_formatted_value('Metric (SI)', eu + ' cm');
    text += _render_formatted_value('Imperial', us_uk + ' in');
    return text;
}

function format_local_hip_girth(size) {
    /**
     * TODO Make local formatting for more than EU
     */
    return size;
}

/**
 * Range formatting functions for range sliders
 */

function format_age_range(start, end) {
    return start + ' - ' + end + ' years';
}

function format_general_score_range(start, end) {
    return start + ' - ' + end;
}

function format_bust_size_range(start, end) {
    return start + ' - ' + end;
}
function format_height_range(start, end) {
    // TODO Act according to user settings!

    return start + ' cm' + ' - ' + end + ' cm';
}
function format_weight_range(start, end) {
    // TODO Act according to user settings!
    return parseFloat(start).toFixed(1) + ' kg' + ' - ' + parseFloat(end).toFixed(1) + ' kg';
}


/**
 * function field_tooltip(String name, String label, String help_text)
 *
 * Hooks for rendering a tooltip for a form field.
 *
 * name:        The name of the field
 * label:       The label of the tooltip (currently not used!)
 * help_text:   The help text to be displayed
 *
 */
field_tooltip = function(name, label, help_text) {
    $('#help_' + name).qtip({
        content: help_text,
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle', // Position the tooltip above the link
                tooltip: 'leftMiddle'
            },
            adjust: {
                screen: true // Keep the tooltip on-screen at all times
            }
        },
        style: {
            tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
            border: {
                width: 0,
                color: '#0093D9'
            },
            name: 'themeroller', // Use the default light style
            width: 300 // Set the tooltip width
        }
    });
    /*
    $('#id_' + name).qtip({
        content: help_text,
        show: 'focus',
        hide: 'blur',
        position: {
            corner: {
                target: 'topMiddle', // Position the tooltip above the link
                tooltip: 'bottomMiddle'
            },
            adjust: {
                screen: true // Keep the tooltip on-screen at all times
            }
        },
        style: {
            tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
            border: {
                width: 0,
                color: '#0093D9'
            },
            name: 'themeroller', // Use the default light style
            width: 300 // Set the tooltip width
        }
    });
    */
}

/**
 * function tooltip(String name, String label, String help_text)
 *
 * Hooks for rendering a tooltip hovering a DOM object based on class.
 *
 * cls:         The class to look for
 * label:       The label of the tooltip (currently not used!)
 * help_text:   The help text to be displayed
 *
 */
tooltip = function(id, label, help_text) {
    $('#' + id).qtip({
        content: help_text,
        show: 'mouseover',
        hide: 'mouseout',
        position: {
            corner: {
                target: 'rightMiddle', // Position the tooltip above the link
                tooltip: 'leftMiddle'
            },
            adjust: {
                screen: true // Keep the tooltip on-screen at all times
            }
        },
        style: {
            tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
            border: {
                width: 0,
                color: '#0093D9'
            },
            name: 'themeroller', // Use the default light style
            width: 300 // Set the tooltip width
        }
    });
}

/**
 * function showAddressOnMap(String address, GMap2 map)
 *
 * Displays an address on a Google Map and centers the
 * map on that location.
 *
 * address:     The address to be displayed
 * map:         The map where the address should be displayed
 *
 */
showAddressOnMap = function(address, map) {
    var geocoder = new GClientGeocoder();

    geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
                alert(address + " not found");
            }
            else {
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                marker.openInfoWindowHtml(address);
            }
        }
        );
}

toggleEnabled = function(field_name, enable) {
    if(enable) {
        $('#id_' + field_name + '_slider').slider('enable');
        $('#id_' + field_name + '_td').css('color','inherit');
        $('#id_' + field_name + '_td').find('input').removeAttr('disabled');
        $('#id_' + field_name + '_td').find('input').css('color','inherit');
    }
    else {
        $('#id_' + field_name + '_slider').slider('disable');
        $('#id_' + field_name + '_td').css('color','#888888');
        $('#id_' + field_name + '_td').find('input').attr('disabled','disabled');
        $('#id_' + field_name + '_td').find('input').css('color','#888888');
    }
}

renderSlider = function(field_name, min, max, step) {
    $(function() {
        $("#id_" + field_name + "_slider").slider({
            value: $("#id_" + field_name + "").val(),
            min: min,
            max: max,
            step: step,
            slide: function(event, ui) {
                $("#id_" + field_name + "_value").html(eval('format_' + field_name)(ui.value));
                $("#id_" + field_name + "").val(ui.value);
            }
        });
        value = $("#id_" + field_name + "_slider").slider("value");
        $("#id_" + field_name + "_value").html(eval('format_' + field_name)(value));
        $("#id_" + field_name + "").val(value);
    });
}

renderPopupSlider = function(field_name, min, max, step) {
    $(function() {
        std_vals[field_name] = $("#id_" + field_name + "").val();
        if($("#id_" + field_name).val() != '' && $("#id_" + field_name).val() != 'NaN')
        $("#id_" + field_name + "_display_box").val(
            eval('format_local_' + field_name)(
                $("#id_" + field_name + "").val()
                )
        );
        $("#id_" + field_name + "_slider").slider({
            value: $("#id_" + field_name + "").val(),
            min: min,
            max: max,
            step: step,
            slide: function(event, ui) {
                $("#id_" + field_name + "_value").html(eval('format_' + field_name)(ui.value));
                $("#id_" + field_name + "").val(ui.value);
            }
        });
        value = $("#id_" + field_name + "_slider").slider("value");
        $("#id_" + field_name + "_value").html(eval('format_' + field_name)(value));
        $("#id_" + field_name + "").val(value);
        $("#id_" + field_name + "_dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 'auto',
            width: 550,
            modal: true,
            buttons: {
                Cancel: function() {
                    value = std_vals[field_name];
                    $("#id_" + field_name + "_slider").slider('option', 'value', value);
                    $("#id_" + field_name + "_value").html(eval('format_' + field_name)(value));
                    $("#id_" + field_name + "").val(value);
                    $(this).dialog('close');
                },
                OK: function() {
                    std_vals['" + field_name + "'] = $("#id_" + field_name + "").val();
                    $("#id_" + field_name + "_display_box").val(
                        eval('format_local_' + field_name)(
                            $("#id_" + field_name + "").val()
                            )
                        );
                    $(this).dialog('close');
                }
            }
        });
        $("#id_" + field_name + "_display_box").click(function(){
            $("#id_" + field_name + "_dialog").dialog('open');
        });
    });
}

renderRangeSlider = function(field_name, min, max, step) {
    $(function() {
        if($('#id_' + field_name).val()) {
            values = $('#id_' + field_name).val().split('|');
        }
        else {
            values = [min, max];
        }
        $('#id_' + field_name + '_slider').slider({
            range: true,
            values: values,
            min: min,
            max: max,
            step: step,
            slide: function(event, ui) {
                $('#id_' + field_name + '_value').html(eval('format_' + field_name + '_range')(ui.values[0], ui.values[1]));
                $('#id_' + field_name ).val(ui.values[0] + '|' + ui.values[1]);
            }
        });
        values = [$('#id_' + field_name + '_slider').slider("values", 0),
        $('#id_' + field_name + '_slider').slider("values", 1)];
        $('#id_' + field_name + '_value').html(eval('format_' + field_name + '_range')(values[0], values[1]));
        $('#id_' + field_name).val(values[0] + '|' + values[1]);
    });
}

renderSelectSlider = function(field_name, labels, label_src, tooltip_src) {
    $(function() {
        std_vals['%(name)s'] = $("#id_%(name)s").val();
        $("#id_%(name)s_display_box").val(
            eval('format_' + field_name)(
                $("#id_%(name)s").val()
                )
            );
        $('#id_' + field_name).selectToUISlider({
            labels: labels,
            tooltip: true,
            name: 'slider_' + field_name,
            tooltipSrc: tooltip_src,
            labelSrc: label_src,
            sliderOptions: {
                change: function(event, ui) {
                    value = $('#id_' + field_name + ' :selected').val();
                    $('#id_' + field_name + '_value').html(eval('format_' + field_name)(value));
                }
            }
        });
        value = $('#id_' + field_name + ' :selected').val();
        $('#id_' + field_name + '_value').html(eval('format_' + field_name)(value));
        $("#id_" + field_name + "_dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 'auto',
            width: 550,
            modal: true,
            buttons: {
                Cancel: function() {
                    value = std_vals['" + field_name + "'];
                    $("#id_" + field_name + "_slider").slider('option', 'value', value);
                    $("#id_" + field_name + "_value").text(eval('format_' + field_name)(value));
                    $("#id_" + field_name + "").val(value);
                    $(this).dialog('close');
                },
                OK: function() {
                    std_vals['" + field_name + "'] = $("#id_" + field_name + "").val();
                    $("#id_" + field_name + "_display_box").val(
                        eval('format_' + field_name)(
                            $("#id_" + field_name + "").val()
                            )
                        );
                    $(this).dialog('close');
                }
            }
        });
        $("#id_" + field_name + "_display_box").click(function(){
            $("#id_" + field_name + "_dialog").dialog('open');
        });

    });
}

renderBraSizeSliders = function() {
    $(function() {
        bra_fields = ['bust_size', 'cup_size'];
        _update_value = function() {
            size = $('#id_bust_size :selected').val();
            cup = $('#id_cup_size :selected').val();
            text = format_bra_size(size, cup);
            $('#id_bra_size_value').html(text);
        }
        for(k in bra_fields) {
            field_name = bra_fields[k];
            std_vals[field_name] = $("#id_" + field_name + " :selected").val();
            $("#id_" + field_name + "_hidden").val(std_vals[field_name]);
            $("#id_" + field_name).hide();
            $("#id_" + field_name).selectToUISlider({
                labels: false,
                tooltip: false,
                name: 'slider_' + field_name,
                sliderOptions: {
                    change: _update_value
                }
            });
            $("#id_slider_" + field_name + "_slider").bind('slide', function(event, ui) {
                setTimeout(_update_value, 100);
            });

            size = $('#id_bust_size :selected').val();
            cup = $('#id_cup_size :selected').val();
            text = format_bra_size(size, cup);
            $('#id_bra_size_value').html(text);
        }
        $("#id_bra_size_display_box").val(
            format_local_bra_size(std_vals['bust_size'], std_vals['cup_size'])
            );
        $("#id_bra_size_dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 'auto',
            width: 500,
            modal: true,
            buttons: {
                /*
                Cancel: function() {
                    for(k in fields) {
                        field_name = fields[k];
                        value = std_vals[field_name];
                        //$("#id_" + field_name + "_slider").slider('option', 'value', value);
                        //$("#id_" + field_name + "_value").text(eval('format_' + field_name)(value));
                        $("#id_" + field_name).val(value);
                    }
                    $(this).dialog('close');
                },
                */
                OK: function() {
                    for(k in bra_fields) {
                        field_name = bra_fields[k];
                        std_vals[field_name] = $("#id_" + field_name + " :selected").val();
                        $("#id_" + field_name + "_hidden").val(std_vals[field_name]);
                    }
                    $("#id_bra_size_display_box").val(
                        format_local_bra_size(std_vals['bust_size'], std_vals['cup_size'])
                    );
                    $(this).dialog('close');
                }
            }
        });
        $("#id_bra_size_display_box").click(function(){
            $("#id_bra_size_dialog").dialog('open');
        });
    });
}

renderJeansSizeSliders = function(male, minw, maxw, stepw, minh, maxh, steph) {
    $(function() {
        if(male){
            sex = 'male';
        }
        else {
            sex = 'female';
        }
        jeans_fields = ['jeans_size_width_' + sex, 'jeans_size_height_' + sex];
        min = [];
        max = [];
        step = [];
        min[jeans_fields[0]] = minw;
        max[jeans_fields[0]] = maxw;
        step[jeans_fields[0]] = stepw;
        min[jeans_fields[1]] = minh;
        max[jeans_fields[1]] = maxh;
        step[jeans_fields[1]] = steph;
        _update_jeans_value = function() {
            width = $('#id_jeans_size_width_' + sex + '_slider').slider('option', 'value');
            height = $('#id_jeans_size_height_' + sex + '_slider').slider('option', 'value');
            text = format_jeans_size(width, height);
            $('#id_jeans_size_' + sex + '_value').html(text);
            image_width = (width || 25) / 34 * 100;
            image_height = (height || 25) / 38 * 200;
            $('#jeans_image_' + sex).css('width', image_width + 'px');
            $('#jeans_image_' + sex).css('height', image_height + 'px');
            $('#jeans_image_' + sex).css('margin', (200 - image_height)/2 + 'px 0');
        }
        for(k in jeans_fields) {
            field_name = jeans_fields[k];
            std_vals[field_name] = $("#id_" + field_name).val();
            $("#id_" + field_name).val(std_vals[field_name]);
            $("#id_" + field_name + "_slider").slider({
                value: $("#id_" + field_name + "").val(),
                min: min[field_name],
                max: max[field_name],
                step: step[field_name],
                orientation: (field_name == 'jeans_size_width_' + sex) ? "horizontal" : "vertical",
                slide: function(event, ui) {
                    setTimeout(_update_jeans_value, 100);
                }
            });
            width = $('#id_jeans_size_width_' + sex).val();
            height = $('#id_jeans_size_height_' + sex).val();
            text = format_jeans_size(width, height);
            $('#id_jeans_size_' + sex + '_value').html(text);
        }
        $("#id_jeans_size_" + sex + "_display_box").val(
            format_local_jeans_size(std_vals['jeans_size_width_' + sex], std_vals['jeans_size_height_' + sex])
        );
        $("#id_jeans_size_" + sex + "_dialog").dialog({
            bgiframe: true,
            autoOpen: false,
            height: 'auto',
            width: 500,
            modal: true,
            buttons: {
                /*
                Cancel: function() {
                    for(k in fields) {
                        field_name = fields[k];
                        value = std_vals[field_name];
                        //$("#id_" + field_name + "_slider").slider('option', 'value', value);
                        //$("#id_" + field_name + "_value").text(eval('format_' + field_name)(value));
                        $("#id_" + field_name).val(value);
                    }
                    $(this).dialog('close');
                },
                */
                OK: function() {
                    var error = $('#id_jeans_size_' + sex + '_error');
                    if(!($('#id_jeans_size_width_' + sex + '_slider').slider('option', 'value') > 0) ||
                        !($('#id_jeans_size_height_' + sex + '_slider').slider('option', 'value') > 0)) {
                        error.addClass('ui-state-error ui-corner-all');
                        error.css('padding', '.3em .7em');
                        error.html('<span class="ui-icon ui-icon-circle-arrow-w" style="float: left; margin: -1px 2px -1px -2px;"></span>You must set both the width and height of you jeans!');
                        return false;
                    }
                    error.removeClass('ui-state-error ui-corner-all');
                    error.css('padding', '0');
                    error.html('');
                    for(k in jeans_fields) {
                        field_name = jeans_fields[k];
                        std_vals[field_name] = $("#id_" + field_name + '_slider').slider('option', 'value');
                        $("#id_" + field_name).val(std_vals[field_name]);
                    }
                    $("#id_jeans_size_" + sex + "_display_box").val(
                        format_local_jeans_size(std_vals['jeans_size_width_' + sex], std_vals['jeans_size_height_' + sex])
                    );
                    $(this).dialog('close');
                }
            }
        });
        $("#id_jeans_size_" + sex + "_display_box").click(function(){
            $("#id_jeans_size_" + sex + "_dialog").dialog('open');
            _update_jeans_value();
        });
    });
}

/**
 * function pretty_fraction(float i)
 *
 * Returns a more textual version of a floating point
 * number, if possible. Currently supports 1/4, 1/2 and
 * 3/4 fractions.
 *
 * i:       The number to format
 *
 * returns: A formatted string if matches exist,
 *          otherwise just i.
 */
pretty_fraction = function(i) {
    frac = i - Math.floor(i);
    switch(frac) {
        case 1/2:
            return Math.floor(i) + '½';
        case 1/4:
            return Math.floor(i) + '¼';
        case 3/4:
            return Math.floor(i) + '¾';
        default:
            return i;
    }
}

/**
 * function round_to(i, to)
 *
 * Rounds the number "i" to the nearest "to".
 *
 * i:       The number to round
 * to:      The number to round to
 *
 * returns: The rounded result
 */
round_to = function(i, to) {
    return Math.round(i / to) * to;
}

/**
 * Activate hovering triggers for <button>s.
 */
$(document).ready(function(){
    //all hover and click logic for buttons
    $("button.ui-state-default:not(.ui-state-disabled), a.ui-state-default").livequery(
        function(){
            $(this).hover(
                function(){
                    $(this).addClass("ui-state-hover");
                },
                function(){
                    $(this).removeClass("ui-state-hover");
                }
            );
        },
        function() {
            $(this)
                .unbind('mouseover')
                .unbind('mouseout');
        }
    );
});

/**
 * Apply themeroller CSS to QTip
 */
$.fn.qtip.styles['defaults'].background = undefined;
$.fn.qtip.styles['defaults'].color = undefined;
$.fn.qtip.styles['defaults'].tip.background = undefined;
$.fn.qtip.styles['defaults'].title.background = undefined;
$.fn.qtip.styles['defaults'].title.fontWeight = undefined;

$.fn.qtip.styles.themeroller = {
    classes: {
        tooltip: 'ui-widget',
        tip: 'ui-widget',
        title: 'ui-widget-header',
        content: 'ui-state-highlight ui-corner-all'
    }
};

/**
 * Global variables
 */

std_vals = [];

// use it to gather data for ajax form submission
// @returns array of inputs
function get_inputs_for_ajax_request(element){
    var this_inputs = $(element).find(':input');
    var inputs = [];

    for(i=0; i<this_inputs.length; i++){
        if(this_inputs[i].name){ // skip fields without the name

            if( $(this_inputs[i] ).is(':radio') || $(this_inputs[i] ).is(':checkbox') ){    // spacial case for radiobuttons and checkboxes (send only checked)
                if( $(this_inputs[i] ).is(":checked")){
                    inputs.push(this_inputs[i].name + '=' + this_inputs[i].value);
                }
            }
            else{   // if not radio/checkbox - send all
                inputs.push(this_inputs[i].name + '=' + this_inputs[i].value);
            }
        }
    }

    return inputs;
}
