$(function() {
    var models = [];

    $.specializationsController = function(url) {
        $("select.make").change(function() {
            var $this = $(this);
            var $yearFrom = $this.parents("div.specializations").find(".yearFrom");
            var $yearTo = $this.parents("div.specializations").find(".yearTo");

            $.ajax({
                url: url + "makes/" + $this.val() + "/models.json",
                dataType: "json",
                success: function(data, textStatus) {
                    // Cache models
                    models = data;

                    var $model = $this.parents("div.specializations").find(".model");
                    $model.find("option[value!=0]").remove();

                    disableSelect($yearFrom);
                    disableSelect($yearTo);

                    for (var i=0;i<models.length;++i){
                        var modelName = models[i].name;
                        $model.append($("<option />").attr("value", modelName).text(modelName));
                    }

                    enableSelect($model);
                },
                error: function(xhr, textStatus, errorThrown){
                    error("we are temporarily experiencing a problem, please try again in a moment");
                }
            });
        });

        $("select.model").change(function(){
            var $this = $(this);
            var $yearFrom = $this.parents("div.specializations").find(".yearFrom");
            var $yearTo = $this.parents("div.specializations").find(".yearTo");
            var selectedModelName = $this.val();
            for (var i=0;i<models.length;++i){
                var model = models[i];
                if (model.name == selectedModelName)
                {
                    $this.removeClass("highlight");

                    $yearFrom.find("option[value!=0]").remove();
                    $yearTo.find("option[value!=0]").remove();

                    enableSelect($yearFrom);
                    enableSelect($yearTo);

                    for (var j=0;j<model.years.length;++j){
                        var year = model.years[j];
                        var $option = $("<option />").attr("value", year).text(year);
                        $yearFrom.append($option);
                        $yearTo.append($option.clone());
                    }

                    break;
                }
            }
        });

        var $add = $("div.specializations").find("input.positive-action");
        $add.click(function() {
            var $this = $(this);
            var $div = $this.parents("div.specializations");
            var $make = $div.find(".make");
            var $model = $div.find(".model");
            var $yearFrom = $div.find(".yearFrom");
            var $yearTo = $div.find(".yearTo");

            var $hiddenMake = toHiddenField($make);
            var $hiddenModel = toHiddenField($model);
            var $hiddenYearFrom = toHiddenField($yearFrom);
            var $hiddenYearTo = toHiddenField($yearTo);

            var $tr = $("<tr />");
            var $removeButton = $("<input type='button' class='negative-action delete' />");

            $removeButton.click(function() {
                $hiddenMake.remove();
                $hiddenModel.remove();
                $hiddenYearFrom.remove();
                $hiddenYearTo.remove();
                $tr.remove();
            });

            $tr.append($("<td />").html($removeButton));
            $tr.append($("<td />").text($make.val()));
            $tr.append($("<td />").text($model.val()));
            $tr.append($("<td />").html($yearFrom.val() + "<span>&nbsp;to&nbsp;</span>" + $yearTo.val()));

            $("form#question")
                    .append($hiddenMake)
                    .append($hiddenModel)
                    .append($hiddenYearFrom)
                    .append($hiddenYearTo);

            $("table#specializations tbody").append($tr);

            var replaceExp = /(question\[specializations\])(\[[^\[]+\])/;

            var updateIndex = function(name) {
                var matches = name.match(replaceExp);
                var indx = matches[2];
                indx = indx.replace("[", "").replace("]", "");
                indx = parseInt(indx);
                indx = indx += 1;
                name = name.replace(replaceExp, "$1[" + indx.toString() + "]");
                return name;
            };

            $make.attr("name", updateIndex($make.attr("name")));
            $model.attr("name", updateIndex($model.attr("name")));
            $yearFrom.attr("name", updateIndex($yearFrom.attr("name")));
            $yearTo.attr("name", updateIndex($yearTo.attr("name")));
        });

        var $tblSpecializations = $("table#specializations");
        var $removeButtons = $tblSpecializations.find(".negative-action");
        $removeButtons.click(function() {
            var $this = $(this);
            var id = $this.attr("id");
            var indx = id.replace("remove_specialization_", "");
            $("form input[type=hidden][name^='question[specializations][" + indx + "]']").remove();
            $this.parents("tr").remove();
        });

        return this;
    };
    
    function disableSelect($select) {
        $select.attr("disabled", "disabled").removeClass("highlight");
    };

    function enableSelect($select) {
        $select.removeAttr("disabled").addClass("highlight");
    }

    var toHiddenField = function($selector) {
        return $("<input type='hidden' />")
                .attr("name", $selector.attr("name"))
                .val($selector.val());
    };
});
