/***********************************************************************
 util.js
 ***********************************************************************/

/* 準備 */
var thisScriptBaseUrl;
var srcPattern = /(util\.js(\?.*)?)$/;
var scriptTags = document.getElementsByTagName('script');
for(var i=0; i<scriptTags.length; i++) {
	var script = scriptTags[i];
	if(script.src.match(srcPattern)) {
		thisScriptBaseUrl=script.src.substr(0, script.src.length - RegExp.$1.length);
		break;
	}
}

/**
 * Javascript を読み込む
 */
var includedJs = {};
function requireJs(js) {
	if(includedJs[js]) return;
	includedJs[js] = js;
	
	if(!js.match(/^(https?:|\/)/)) js = thisScriptBaseUrl + js;
	try{
		document.write('<script type="text/javascript" src="'+js+'" charset="utf-8"><\/script>');
	} catch(e) {
		var script = document.createElement('script');
		script.type = 'text/javascript';
		script.src = js;
		script.charset='utf-8';
		document.getElementsByTagName('head')[0].appendChild(script);
	}
}
/**
 * スタイルシートを読み込む
 */
var includedCss = {};
function requireCss(css) {
	if(includedCss[css]) return;
	includedCss[css] = css;

	if(!css.match(/^(https?:|\/)/)) css = thisScriptBaseUrl + css;
	try{
		document.write('<link rel="stylesheet" href="'+css+'" type="text/css" \/>');
	} catch(e) {
		// for xhtml+xml served content, fall back to DOM methods
		var link = document.createElement('link');
		link.rel = 'rel/stylesheet';
		link.type = 'text/css';
		link.href = css;
		document.getElementsByTagName('head')[0].appendChild(link);
	}
}
/**
 * 関数コール
 */
function _call() {
	if(!arguments && arguments.length < 1) {
		return;
	}
	var func = arguments[0];
	var args = [];
	for(var i = 1; i < arguments.length; i++) {
		args[i-1] = arguments[i];
	}
	func.apply(this, args);
	if(/*@cc_on!@*/false && !window.XMLHttpReques) { // IE6バグ回避
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	}
	return false;
}
/***********************************************************************
 ウインドウ
 ***********************************************************************/
/**
 * ウインドウを開く
 */
var windowOpenList = {}
function windowOpen  (url, name, att) {
	var windows = windowOpenList;
	var att_str = '';
	if(name && windows[name] && !windows[name].closed) {
		var w = windows[name];
		w.location.replace(url);
		w.focus();
		windows[name] = w;
	}
	else {
		if(att) {
			var a = [];
			for(var key in att) a.push(key + '=' + att[key]);
			att_str = a.join(',');
		}
		var w = window.open(url, name, att_str);
		w.focus();
		if(name)
			windows[name] = w;
	}
}
/***********************************************************************
 配列操作
 ***********************************************************************/
/**
 * 要素の重複を除いた配列を取得
 */
function arrayUnique  (array, strict) {
	var re = [], v;
	if(typeof strict=='undefined' || strict) {
		for(var i = 0; i < array.length; i++) {
			v = array[i];
			for(var j=0, flg = true; j< re.length && flg; j++) {
				if(v === re[j]) flg = false;
			}
			if(flg) re.push(v);
		}
	}
	else {
		var o = {};
		for(var i = 0;i < array.length;i++) {
			v = array[i];
			if((v in o)?(false):(o[v]=true)) re.push(v);
		}
	}
	return re;
}
/**
 * 配列内を検索
 */
function arraySearch  (needle, array) {
	for(var i=0; i<array.length; i++) { if(array[i] === needle) return i;}
	return null;
}
/**
 * 配列内に要素が存在するか
 */
function inArray (needle, array) {
	for(var i=0; i<array.length; i++) { if(array[i] === needle) return true; }
	return false;
}
/**
 * 配列の共通部分を取得
 */
function arrayIntersect (a1, a2) {
	var re = [];
	for(var i=0; i<a1.length; i++) {
		if(in_array(a1[i], a2)) { re.push(a1[i]); }
	}
	return re;
}
/**
 * 連想配列をマージ(a1の要素をa2で上書き)
 */
function assocMerge (a1, a2) {
	var re = {};
	for(var i in a1) re[i] = a1[i]
	for(var i in a2) re[i] = a2[i];
	return re;
}
/***********************************************************************
 文字列操作
 ***********************************************************************/
/**
 * 前後の空白を削除
 */
function trim (str) {
	return str.replace(/(^\s+|\s+$)/, '');
}
/**
 * パスを正規化
 */
function _path (path) {
	var src_path = path.split('/');
	var dest_path = [];
	for(var i=0; i<src_path.length; i++) {
		var n = src_path[i];
		if(n == '..')     { dest_path.pop();   }
		else if(n == '.') { /* 何もしない */   }
		else if(n == '' ) { /* 何もしない */   }
		else              { dest_path.push(n); }
	}
	return (path.charAt(0)=='/'?'/':'') + dest_path.join('/');
}

/**
 * 相対パスを作成
 */
function relative_path(path, current_path) {
	var o_path = path.split('/');
	var c_path = current_path.split('/');
	while(o_path.length>0 && c_path.length>0 && o_path[0]==c_path[0]) {
		o_path.shift();
		c_path.shift();
	}
	var re = "./";
	for(var i=0; i < c_path.length - 1; i++) {
		re += "../";
	}
	re += o_path.join('/');
	re = re.replace(/\.\/\.\.\//, '../');
	return re;
}
/**
 * 絶対URLを取得
 */
function getRealUrl(src) {
	var e = document.createElement('span');
	e.innerHTML = '<a href="' + src + '" />';
	src = e.firstChild.href;
	e = null;
	return src;
}
/***********************************************************************
 Cookie
 ***********************************************************************/
/**
 * Cookieを設定
 */
function setCookie (key , value , expires, path){
	if (key == '' || key == null) return false;

	var cookie = [escape(key) + "=" + escape(value)];
	if(typeof expires != 'undefined' && expires != '' && expires != null) {
		dt = new Date();
		dt.setTime(dt.getTime() + (expires * 1000 * 60 * 60 * 24));
		cookie.push("expires=" + dt.toGMTString());
	}
	if(typeof path != 'undefined' && path != '' && path != null) {
		cookie.push("path=" + escape(path));
	}
	document.cookie =  cookie.join(';', cookie) + ';';
}
/**
 * Cookieを取得
 */
function getCookie (key){
	var c = document.cookie.split(";");
	for(var i = 0; i < c.length; i++) {
		var key_value = c[i].split('=');
		if(unescape(trim(key_value[0])) == key)
			return unescape(trim(key_value[1]));
	}
	return null;
}
/**
 * Cookieを削除
 */
function delCookie (key) {
	var dt = new Date();
	document.cookie = escape(key) + "=;expires=" + dt.toGMTString();
}
/***********************************************************************
 IFrame
 ***********************************************************************/
/**
 * IFrameのDocumentを取得
 */
function getIframeDocument(iframe) {
	return (iframe.contentDocument)?
			(iframe.contentDocument):
			(iframe.contentWindow.document);
}
function getIframeWindow(iframe) {
	return iframe.contentWindow;
}
/**
 * IFrameの読み込み時イベントハンドラを設定
 */
function setIframeOnload(iframe, callback) {
	if(/*@cc_on!@*/false && !window.XMLHttpRequest){
		// IE6バグ回避
		iframe.observe('readystatechange', function() {
			if (this.readyState == "complete") {
				callback(iframe)
				this.onreadystatechange = function(){}; // IEメモリリーク回避
			}
		});
	}
	else {
		iframe.observe('load', function() {callback(iframe)});
	}
}
/**
 * IFrameの読み込み時イベントハンドラを解除
 */
function unsetIframeOnload(iframe) {
	if(/*@cc_on!@*/false && !window.XMLHttpRequest){
		// IE6バグ回避
		//iframe.stopObserving('readystatechange');
	}
	else {
		iframe.stopObserving('load');
	}
}
/**
 * IFrameを作成
 */
function createIframe(attributes, onload) {
	var iframe = new Element('iframe', attributes);
	if(onload) {
		setIframeOnload(iframe, onload);
	}
	return iframe;
}
/**
 * IFrameのサイズを取得
 */
function getIframeDemensions(iframe) {
	var iframeDoc = getIframeDocument(iframe);
	var w = iframeDoc.documentElement.scrollWidth || iframeDoc.body.scrollWidth;
	var h = iframeDoc.documentElement.scrollHeight || iframeDoc.body.scrollHeight;
	return {w:w, h:h, width:w, height:h};
}
var backgroundSubmitFormIframeCount = 0;
function backgroundSubmitForm(form, onload) {
	var count = backgroundSubmitFormIframeCount;
	var iframeName = 'backgroundSubmitFormIframe' + (count++);
	var target = form.target; // 元のtargetを退避
	var iframe = createIframe({
		style:'display:none;width:100%;height:500px;',
		id  :iframeName,
		name:iframeName,
		src : 'javascript:void(0)'
	}, function() {
		if(getIframeDocument(iframe).location == 'about:blank') return;
		setTimeout(function(){document.body.removeChild(iframe)}, 500);
		if(onload) onload();
	});
	document.body.appendChild(iframe);
	form.target = iframeName;
	form.submit();
	form.target = target;
}

