var SATUtil = {
	/**
	 * スクリプトが存在するディレクトリのパスを返す
	 */
	resourcePath:function(filename) {
	    if (!SATUtil.resourcePath.dir) {
	        $("script").each(function() {
	            if (this.src.indexOf('/SATUtil.js') > 0) {
	                var path = this.src.split('/');
	                path[path.length - 1] = '';
	                SATUtil.resourcePath.dir = path.join('/');
	                return false;
	            }
	        });
	    }
	    return SATUtil.resourcePath.dir + filename;
	},
	/**
	 * フォーム要素をクリアする
	 */
	clearElement: function(elem) {
		if (Array.prototype.isPrototypeOf(elem)) {
			for (var i = 0; i < elem.length; i++) {
				SATUtil.clearElement(elem[i]);
			}
		} else {
			var type = (elem.tagName == "INPUT" ? elem.tagName + '.' + elem.type : elem.tagName).toLowerCase();
			switch(type) {
			case "input.text":
			case "input.password":
			case "textarea":
				elem.value = "";
				break;
			case "select":
				elem.selectedIndex = 0;
				break;
			case "input.radio":
			case "input.checkbox":
				elem.checked = false;
				break;
			}
		}
	},
	/**
	 * フォームをクリアする
	 */
	clearForm: function(form) {
		if (typeof(form) == "string") {
			form = document.getElementById(form);
		}
		if (form.tagName == "FORM") {
			// エレメントをクリアする
			var cl = function(elem) {
			}
			var elements = form.elements;
			for (var i = 0; i < elements.length; i++) {
				SATUtil.clearElement(elements[i]);
			}
		}
	},
	
	/**
	 * 日付文字列を整形する
	 * @param string format Y,m,d,H,iが使える。
	 */
	dateFormat:function(format, t) {
	    function zf(num) {
	        return num < 10 ? '0' + num : num;
	    }
	    var date = t ? new Date(t.replace(/\-/g, '/')) : new Date();
	    var Y = date.getFullYear();
	    var m = zf(date.getMonth() + 1);
	    var d = zf(date.getDate());
	    var H = zf(date.getHours());
	    var i = zf(date.getMinutes());
	    return format.replace(/Y/g, Y).replace(/m/g, m).replace(/d/g, d).replace(/H/g, H).replace(/i/g, i);
	},
	
	/**
	 * IE専用のモーダルダイアログを表示する
	 */
	modalDialog:function(url, width, height, argObj, additionalStates) {
	    var sw = screen.availWidth  ;
	    var sh = screen.availHeight ;
	    var top = Math.floor((sh - height) / 2);
	    var left = Math.floor((sw - width) / 2);
	    var states = {
	        status:"yes",
	        scrollbars:"no",
	        help:"no",
	        dialogWidth:width + "px",
	        dialogHeight:height + "px",
	        dialogLeft:left + "px",
	        dialogTop:top + "px"
	    };
	    if (additionalStates) {
	        for (var i in additionalStates) {
	            states[i] = additionalStates[i];
	        }
	    }
	    var ar = [];
	    for (key in states) {
	        ar.push(key + ":" + states[key]);
	    }
	    return window.showModalDialog(url, argObj, ar.join(";"));
	},
	
	/**
	 * 子ウィンドウを開くための便利メソッド
	 */
	childWindow:function(url, name, width, height, additionalStates) {
	    function makeStateString(obj, obj2) {
	        var ar = [];
	        for (key in obj) {
	            ar.push(key + "=" + obj[key]);
	        }
	        if (obj2) {
	            for (key in obj2) {
	                ar.push(key + "=" + obj2[key]);
	            }
	        }
	        return ar.join(",");
	    }
	    var sw = screen.availWidth  ;
	    var sh = screen.availHeight ;
	    if (height < 0) {
	        height = sh;
	    }
	    if (width < 0) {
	        width = sw;
	    }
	
	    var top = Math.floor((sh - height) / 2);
	    var left = Math.floor((sw - width) / 2);
	    var state = {
	        location:"no",
	        width:width,
	        height:height,
	        left:left,
	        top:top
	    };
	    var str = makeStateString(state, additionalStates);
	    return window.open(url, name, str);
	},
	/**
	 * 改行コードをbrタグに変換する
	 */
	nl2br:function(str) {
	    return str ? str.replace(/\r\n|\r|\n/g, "<br>") : "";
	},
	/**
	 * Cookieを扱いやすいオブジェクトにする
	 */
	parseCookie: function() {
		var c = document.cookie;
		var ret = {};
        var qStr = c.split(/; */);
        for (var i = 0; i < qStr.length; i++) {
            var pair = qStr[i].split('=');
            ret[pair[0]] = pair[1];
        }
        return ret;
	},
	/**
	 * onsubmit="return SATUtil.preventDoubleSubmit()"のように使う
	 */
	preventDoubleSubmit: function() {
		if (SATUtil.nowSubmitting) {
			return false;
		} else {
			SATUtil.nowSubmitting = true;
			return true;
		}
	}
};


/**
 * デバッグ用
 */
var DebugInspector = {
	debugging: true,
    showWindow:function(obj, limitDepth) {
    	if (!DebugInspector.debugging) {
    		return;
    	}
        var w = SATUtil.childWindow("", "_blank", 600, 700, {
            resizable:"yes",
            scrollbars:"no"
        });
        var html = [];
        html.push("<html><head>");
        html.push("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=Windows-31J\">");
        html.push("</head><body style='margin:0;padding:0;height:100%'>");
        html.push("<textarea id='t' style='width:100%;height:100%'>");
        html.push("</textarea>");
        html.push("</body></html>");

        w.document.open();
        w.document.write(html.join("\n"));
        w.document.close();
        w.document.getElementById('t').value = DebugInspector.inspect(obj, limitDepth);
    },
    alert:function(obj, limitDepth) {
    	if (!DebugInspector.debugging) {
    		return;
    	}
        alert(DebugInspector.inspect(obj, limitDepth));
    },
    /**
     * オブジェクトの要素を再帰的にたどって文字列にする。
     * @param obj 監査対象オブジェクト
     * @param limitDepth 構造をたどる深さの制限
     * @param depth （内部で使う）
     * @param already （内部で使う）
     */
    inspect:function(obj, limitDepth, depth, already) {
        depth = depth || 0;
        limitDepth = limitDepth || 3;
        already = already || [];
        for (var i = 0; i < already.length; i++) {
            if (already[i] === obj) {
                return "already";
            }
        }
        if (obj === null) {
            return "null";
        } else if (typeof(obj) == "number"
            || typeof(obj) == "string"
            || typeof(obj) == "boolean"
            || typeof(obj) == "date") {
            return ("" + obj).replace("<", "&lt;").replace(">", "&gt;");
        } else if (typeof(obj) == "function") {
            return "(function)";
        } else if (typeof(obj) == "object") {
            if (depth > limitDepth) {
                return "too deep";
            } else {
                if (obj.outerHTML && obj.tagName) {
                    return "HTMLObject &lt;" + obj.tagName + " id=\"" + obj.id + "\"&gt;";
                } else {
                    already.push(obj);

                    var indent = "";
                    for (var i = 0; i < depth; i++) {
                        indent += "    ";
                    }
                    if (Array.prototype.isPrototypeOf(obj)) {
                        var html = ["[\n"];
                        for (var i = 0; i < obj.length; i++) {
                            html.push(indent + "    ");
                            try {
                                html.push(DebugInspector.inspect(obj[i], limitDepth, depth + 1, already));
                            } catch (e) {
                                html.push(e);
                            }
                            html.push("\n");
                        }
                        html.push(indent + "]");
                        return html.join("");
                    } else {
                        var html = ["{\n"];
                        for (key in obj) {
                            html.push(indent + "    ");
                            html.push(key);
                            html.push(" : ");
                            try {
                                html.push(DebugInspector.inspect(obj[key], limitDepth, depth + 1, already));
                            } catch (e) {
                                html.push(e);
                            }
                            html.push("\n");
                        }
                        html.push(indent + "}");
                        return html.join("");
                    }
                }
            }
        }
    }
}

