﻿/*jslint nomen: true, browser: true, debug: true */
/*global jQuery, alert */
/*
	Cascade a dropdown list with 'childId' when dropdown list with 'parentId' changes.
	Difference from the existing cascade plugin for jQuery:
	- Loads an initial list on startup, not only on change.
	- Supports supplying first value in dropdown list. This was needed for localization.
	- Defaults are handy for the 'rubriek' -> 'merk' cascade.
*/
jQuery.fn.cascade = function(options) {
    var defaults = {
        parameterName: "rubriekID"
    };
    // Extend our default options with those provided.
    var opts = jQuery.extend(defaults, options);
    return this.each(function() {
    var current = jQuery(this);
        current.change(function() { parentChanged(opts, current); });
        parentChanged(opts, current);
    });
    function isError($msg, $msg2, $msg3) {
        //alert('cascade.js ' + $msg.responseText);
    }
    function fill($json, $opt) {
        var html = "<option value=''>" + $opt.firstValue + "</option>";
        var data = $json[0].d;

        if (data.length === 0) {
            jQuery($opt.childId).attr('disabled', true);
        }
        else {
            jQuery($opt.childId).removeAttr('disabled');
        }

        var sendChangeUpdate = false;
        for (var val in data) {
            if (data[val] == $opt.selectedValue) {
                html += "<option value='" + data[val] + "' selected='selected'>" + data[val] + "</option>";
                sendChangeUpdate = true;
            }
            else {
                html += "<option value='" + data[val] + "'>" + data[val] + "</option>";
            }
        }

        jQuery($opt.childId).html(html);
        if (sendChangeUpdate==true) {
            jQuery($opt.childId).trigger('change');
        }
    }

    function populateChild($opt, $rubriekid) {
        if ($rubriekid === "" && typeof ($rubriekid) == "undefined") {
            $rubriekid = "0";
        }

        jQuery.ajax({
            type: "POST",
            url: $opt.url,
            contentType: "application/json; charset=utf-8",
            data: "{'" + $opt.parameterName + "': '" + $rubriekid + "'}",
            dataType: "json",
            success: function(json) { fill([json], $opt); },
            error: isError
        });
    }
    function parentChanged($opt, $parent) {
        jQuery($opt.childId).html("<option value=''>laden...</option>").attr('disabled', true);

        var rubriekid = "0";
        var parentValue = $parent.filter(">option:selected");
        if (parentValue.size() == 1 && parentValue.val() !== "") {
            rubriekid = parentValue.val();
        }
        populateChild($opt, rubriekid);
    }
};
