/**
 * jQuery setFileSize plugin
 * リンク参照先のファイルサイズを取得して表示する
 * 
 */
(function ($) {
    var name_space = 'setFileSize';
    $.fn[name_space] = function () {
        var elements = $(this);

        function ajax(url, type, async) {
            var xhr = false;
            xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); /* HTTPリクエスト実行 */
            xhr.open(type, url, async);
            xhr.send(null);
            return xhr;
        }

        function get() {
            return function () {
                var $this = $(this);
                var url = this.href + "?nocash=" + Math.floor(Math.random() * 10000);
                var xhrObj = ajax(url, "HEAD", true);
                xhrObj.onreadystatechange = function () {
                    if (xhrObj.readyState == 4 && xhrObj.status == 200) {
                        var fileSize = xhrObj.getResponseHeader("Content-Length");
                        var fileType = xhrObj.getResponseHeader("Content-Type");
                        fileSize = parseInt(fileSize, 10);
                        var units = [
                            [1024 * 1024 * 1024, 'GB'],
                            [1024 * 1024, 'MB'],
                            [1024, 'KB'],
                            [1, 'bytes']
                        ];
                        for (var i = 0; i < units.length; i++) {
                            var unitSize = units[i][0];
                            var unitText = units[i][1];
                            if (fileSize >= unitSize) {
                                fileSize = fileSize / unitSize;
                                fileSize = Math.ceil(fileSize * 10) / 10;
								fileSize = Math.round(fileSize);
                                break;
                            }
                        }
                        fileType = fileType.split('/')[1].toUpperCase();
                        return add(fileType, fileSize, unitText);
                    }
                }

                function add(type, size, unitText) {
                    if ($this.next('img').length == 0) {
                        $this.after(" [" + type + "]（" + size + unitText + "）");
                    }
                    else {
                        ($this.next('img').attr("src").match(/pdf/)) ? $this.next().after(" [" + type + "]（" + size + unitText + "）") : $this.after(" [" + type + "]（" + size + unitText + "）");
                    }
                }
            }
        }
        elements.each(get());
        return this;
    };
})(jQuery);



