(function($) {
    $(function() {

        // 行の背景を一行おきに変える。
        // 列をドラッグで順番変更可能にする。
        jQuery.extend(jQuery.jgrid.defaults, {
            altRows: true,
            sortable: true
        });

        function get_area_list(mode, v6, v7) {
            var valstr = '';
            $.ajax({  //Make the Ajax Request
                type: 'POST',
                url: '/list/area?' +
                'field02=' + $('#gs_field02').val() +
                // '&field06=' + v6 +
                '&field07=' + v7 +
                '&field08=' + $('#gs_field08').val(),
                async: false,
                // data で渡したものが sinatora 側で上手く受け取れないので....
                //data: {
                //    field02: $('#gs_field02').val(),
                //    field06: $('#gs_field06').val(),
                //    field07: $('#gs_field07').val(),
                //    field08: $('#gs_field08').val()
                //    },
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(response) {
                    try {
                        valstr = make_valstr(response, mode);
                    } catch (e) {
                        jAlert(e.message);
                    }
                },
                error: function(data, textStatus) {
                    jAlert('An error has occured retrieving data!');
                }
            });
            return valstr;
        };

        function get_area2_list(mode, v6, v7) {
            var valstr = '';
            $.ajax({  //Make the Ajax Request
                type: 'POST',
                url: '/list/area2?' +
                'field02=' + $('#gs_field02').val() +
                '&field06=' + v6 +
                //'&field07=' v7 +
                '&field08=' + $('#gs_field08').val(),
                async: false,
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(response) {
                    try {
                        valstr = make_valstr(response, mode);
                    } catch (e) {
                        jAlert(e.message);
                    }
                },
                error: function(data, textStatus) {
                    jAlert('An error has occured retrieving data!');
                }
            });
            return valstr;
        };

        function make_valstr(response, mode) {
            var item, value, i;
            var success = response.success;
            var message = response.message;
            var len = message.length;

            if (mode === 'value') {
                valstr = ':All;';
                for (i = 0; i < len; i++) {
                    value = message[i].value;
                    item = message[i].item;
                    valstr += value + ':' + item;
                    if (i < len - 1) {
                        valstr += ';';
                    }
                }
            } else {
                valstr = '<option value="">All</option>';
                for (i = 0; i < len; i++) {
                    value = message[i].value;
                    item = message[i].item;
                    valstr += '<option value="' + value + '">' + item + '</option>';
                }
            }
            return valstr;
        };

        $('<button id="setcol_zipcode">列表示の設定</button>' +
            '<table id="grid_zipcode"></table><div id="pager_zipcode"></div>')
        .appendTo('body');

        $('#grid_zipcode').jqGrid({
            url: '/zipcode.json',
            mtype: 'GET',
            datatype: 'json',
            colNames: ['郵便番号', '都道府県', '市区町村', '町域名'],
            colModel: [
            {
                name: 'field02',
                index: 'field02',
                width: 140
            },
            {
                name: 'field06',
                index: 'field06',
                width: 140,
                stype: 'select',
                search: true,
                searchoptions: {
                    'value': get_area_list('value', '', '')
                }
            },
            {
                name: 'field07',
                index: 'field07',
                width: 200
            },
            {
                name: 'field08',
                index: 'field08',
                width: 200
            }
            ],
            rownumbers: true,
            rownumWidth: 80,
            scroll: 1,
            rowNum: 100,
            // rowList:[5, 10,20,50,100, 200, 500, 1000],
            pager: '#pager_zipcode',
            sortname: '_id',
            sortorder: 'asc',
            viewrecords: true,
            width: 800,
            // height: 'auto',
            height: 400,
            caption: 'sinatra-mongioid sample',

            loadComplete: function() {
                var f6 = $('#gs_field06').val();
                var f72 = $('#gs_field07_2').val();

                if ($('#gs_field07_2').length == 0) {
                    html = '<select style="width: 100%;display:none" name="field07_2" id="gs_field07_2" title="5000件以下になると選択リストになります。"><option value="">All</option></select>';
                    $('#gs_field07').before(html);
                
                    $('#gs_field07_2').change(function () {
                        var v = $('#gs_field07_2').val();
                        $("#gs_field07").val(v);
                        $("#gs_field07").text(v);
                        $('#grid_zipcode')[0].triggerToolbar();
                    });
                }

                // 入力タイプがなぜか 切り替わらない...
                //jQuery('#grid_zipcode').jqGrid('setColProp','field06', {
                //    searchoptions: {
                //        value: get_area_list()
                //    }
                //});
                $('#gs_field06').html(get_area_list('html', f6, f72));
            
                var numberOfRecords = $("#grid_zipcode").getGridParam("records");
                if (numberOfRecords < 5000) {
                    $('#gs_field07').hide();
                    $('#gs_field07_2').show();
                    $('#gs_field07_2').html(get_area2_list('html', f6, f72));
                } else {
                    $('#gs_field07').show();
                    $('#gs_field07_2').hide();
                }
                // alert(v72);
                $('#gs_field06').val(f6);
                $('#gs_field07_2').val(f72);
                $('#gs_field07').val(f72);
            }
        });
        // grid を drag でリサイズ可能にする
        jQuery('#grid_zipcode').jqGrid('gridResize', {
            minWidth: 100,
            maxWidth: 2000,
            minHeight: 32,
            maxHeight: 800
        });

        <!-- jQuery('#grid_zipcode').jqGrid('sortableRows'); -->

        // grid を drag で移動可能にする
        jQuery(jQuery('#gbox_grid_zipcode')[0]).draggable({
            handle: 'div.ui-jqgrid-titlebar'
        });
        // 列表示 on/off 設定機能
        jQuery('#setcol_zipcode').click(function() {
            jQuery('#grid_zipcode').setColumns({
                // updateAfterCheck: true
                });
        });
        // toolbar での列絞り込み機能
        jQuery('#grid_zipcode').jqGrid('filterToolbar', {
            stringResult: true,
            searchOnEnter: true
        });
    });
})(jQuery);
