$(document).ready(function () {

    $("select.linkselect").linkselect();

    $(".AxForm .AxSubmitButton").parent('div').addClass('greenbutton').parent('div').parent('div').addClass('AxFormButton');
    $('.AxFormLine:not(".AxFormButton")').addCorners();
    $('.contourField').addCorners();

    $('.AxForm .AxFormControl select').each(function () {
        createDropDown($(this));
    });

    $(".dropdown dt a").click(function (e) {
        e.preventDefault();
        $(this).parents('.dropdown').find('ul').toggle();
    });    

    $(".dropdown dd ul li a").click(function (e) {
        e.preventDefault();
        var text = $(this).html();
        $(this).parents('.dropdown').find("dt a").html(text);
        $(this).parents('.dropdown').find("ul").hide();

        $(this).parents('ul').find('.selected').removeClass('selected');
        $(this).addClass('selected');

        var source = $(this).parents('.AxFormControl').find('select');
        source.val($(this).find("span.value").html())
    });
});

function createDropDown(source) {   
    var selected = source.find("option[selected]");
    var options = source.find("option");

    source.after('<dl class="dropdown"></dl>')
    source.parent().find(".dropdown").append('<dt><a href="#">' + selected.text() +
                '<span class="value">' + selected.val() +
                '</span></a></dt>')
    source.parent().find(".dropdown").append('<dd><ul></ul></dd>')   

    var first = true;

    options.each(function () {
        if (first == false) {
            source.parent().find(".dropdown dd ul").append('<li><a href="#">' +
            $(this).text() + '<span class="value">' +
            $(this).val() + '</span></a></li>');
        }
        else {
            first = false;
        }
    });
    source.hide();
}
