(function() {

    var signup = {}

    function enable_disable_instruments(enable) {
        var instrument_selector = $('#instrument_selector');

        if(enable) {
            instrument_selector.removeAttr('style')
            $('input', instrument_selector).removeAttr('disabled').removeAttr('style');
            $('select', instrument_selector).removeAttr('disabled').removeAttr('style');
        }
        else {
            instrument_selector.css('color', '#AAA')
            $('input', instrument_selector).attr('disabled', 'disabled').css('color', '#AAA');
            $('select', instrument_selector).attr('disabled', 'disabled').css('color', '#AAA');
        }
    }

    // instruments are selectable if musician = true
    signup.handle_register_as_changes = function handle_register_as_changes() {

        var initial_value = $('input.register-as:checked').val();
        enable_disable_instruments(initial_value == "true");

        $('input.register-as').change(function() {
            var value = $(this).val()
            enable_disable_instruments(value == "true")
        })
    }

    // register form elements relating to location to update appropriately as the user makes changes
    signup.handle_location_changes = function handle_location_changes()  {

        var country_select = $('#country_select')
        var region_select = $('#region_select')
        var city_select  = $('#city_select')

        country_select.change(function() {
            var selected_country = $(this).val()
            if(selected_country) {
                // set region disabled while updating
                region_select.attr('disabled', true);

                $.ajax('/api/regions', {
                    data : { country: selected_country },
                    dataType : 'json'
                }).done(regions_done).fail(regions_fail).always(function() { region_select.attr('disabled', false) })
            }
        })

        function regions_done(data) {
            region_select.children().remove()

            region_select.append("<option value=''>Select State/Province</option>")

            $(data.regions).each(function(index, item) {
                region_select.append("<option value=" + item +  ">" + item +  "</option>")
            })
        }

        function regions_fail() {
            alert("something went wrong in looking up regions")
        }

        region_select.change(function() {
            var selected_country = country_select.val()
            var selected_region = $(this).val()

            // only update
            if(selected_country && selected_region) {
                // set city disabled while updating
                city_select.attr('disabled', true);

                $.ajax('/api/cities', {
                    data : { country: selected_country, region: selected_region },
                    dataType : 'json'
                }).done(cities_done).fail(cities_fail).always(function() { city_select.attr('disabled', false) })
            }
        })

        function cities_done(data) {
            city_select.children().remove()

            city_select.append("<option value=''>Select City</option>")

            $(data.cities).each(function(index, item) {
                city_select.append("<option value=" + item +  ">" + item +  "</option>")
            })
        }

        function cities_fail() {
            alert("something went wrong in looking up cities")
        }
    }

    signup.handle_completion_submit = function handle_completion_submit() {

        // based on rails date_select element, gather up birth_date selected by the user.
        // returns null if any field (day/month/year) is left blank
        function gather_birth_date() {
            var month = $('#jam_ruby_user_birth_date_2i').value
            var day = $('#jam_ruby_user_birth_date_3i').value
            var year = $('#jam_ruby_user_birth_date_1i').value

            if(month != null && month.length > 0 && day != null && day.length > 0 && year != null && year.length > 0) {
                return month + "-" + day + "-" + year;
            }
            else {
                return null;
            }
        }

        // looks in instrument_selector parent element, and gathers up all
        // selected elements, and the proficiency level declared
        function gather_instruments() {
            var instruments_parent_element = $(".instrument_selector")

            var instruments = []
            $('input[type=checkbox]:checked', instruments_parent_element).each(function(i) {

                // traverse up to common parent of this intrument, and pick out proficienc selector
                var proficiency = $('select.proficiency_selector', $(this).closest('tr')).val()

                instruments.push({
                    instrument_id: $(this).attr('name'),
                    proficiency_level: proficiency,
                    priority : i
                })
            });

            return instruments;
        }

        $('form.edit_jam_ruby_user').submit(function() {

            var form = $(this)

            var submit_data = {};
            // gather up all fields from the form
            submit_data.first_name = $('#jam_ruby_user_first_name').val()
            submit_data.last_name = $('#jam_ruby_user_last_name').val()
            submit_data.password = $('#jam_ruby_user_password').val()
            submit_data.password_confirmation = $('#jam_ruby_user_password_confirmation').val()
            submit_data.country = $('#jam_ruby_user_country').val()
            submit_data.state = $('#jam_ruby_user_state').val()
            submit_data.city = $('#jam_ruby_user_city').val()
            submit_data.birth_date = gather_birth_date()
            submit_data.instruments = gather_instruments()
            //submit_data.photo_url = $('#jam_ruby_user_instruments').val()


            $.ajax({
                type: "POST",
                url: "/api/users/complete/"  + gon.signup_token,
                contentType: 'application/json',
                data: JSON.stringify(submit_data)
            }).done(completion_done).fail(completion_fail)

            return false;
        })

        function completion_done(data) {
            // we can redirect on to client
            window.location.href = '/client'

        }

        function completion_fail(xhr, status) {
            // if status = 422, then we can display errors
            if(xhr.status == 422) {
                data = JSON.parse(xhr.responseText)
                var errors = $('#errors')
                errors.children().remove()
                var list = $("<ul></ul>")
                errors.append(list)
                $(data).each(function(i) {
                    list.append("<li>" + this + "</li>")
                })
            }
            else {
                alert("something went wrong with the service. please try again later")
            }
        }

    }

    window.signup = signup
})()