/* Copyright 2008 CogniTom Academic Design & Tsutomu Kawamura
 * http://jsmap.cognitom.com/
 * office@cognitom.com
 * ------------------------------------------------------------------
 *
 * jsmap world edition
 *
 * - version 0.3.1
 * - release 2008.11.3
 * 
 * ------------------------------------------------------------------
 * 本スクリプトは、Apache License Version 2.0に基づいてライセンスされます。
 * あなたがこのファイルを使用するためには、本ライセンスに従わなければなりません。
 * 本ライセンスのコピーは下記の場所から入手できます。
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * 適用される法律または書面での同意によって命じられない限り、本ライセンスに基づい
 * て頒布されるソフトウェアは、明示黙示を問わず、いかなる保証も条件もなしに「現状
 * のまま」頒布されます。本ライセンスでの権利と制限を規定した文言については、本ラ
 * イセンスを参照して下さい。
 * ------------------------------------------------------------------
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


/**
 * Globals
 */
var jsmwRegList = ['NoAmerica', 'SoAmerica','SouthAsia', 'FarEast', 'Oceania'];
var jsmwPath;
var jsmwData = [];
if (isIE=='undefined') var isIE = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent));


/**
 * Region
 */
var jsmwRegions = [];
var jsmwRegion = function(d){
	this.initialize = function(d){
		jsmwRegions.push(this);//グローバル配列に登録
		this.name = d.name;//地域名
		this.data = d.data;//国マップデータ
	};
	this.getCountryByIdx = function(idx){ return this.data[idx] };
	this.getIdxByCountryCode = function(countryCode){ for (var i=0; i<this.data.length; i++) if (this.data[i][0] == countryCode) return i; return -1 };
	
	this.initialize(d);//コンストラクタ呼び出し
};

/**
 * Field
 */
var jsmwFields = {};
var jsmwField = function(id){
	this.initialize = function(id){
		jsmwFields[id] = this;//グローバル配列に登録
		this.id = id;//input要素のid
		this.regionNum = 0;//表示中の地方番号(日本の場合は0〜3)
		this.cur = -1;//フォーカス位置(カーソル移動順の何番目か)
		this.hiding = true;
		this.refocusing = false;
		this.supressClickTimer = false;
		
		var elm = document.getElementById(id);
		var prt = elm.parentNode;
		
		var div = document.createElement('div');
		div.id = 'map_'+id; div.className = 'jsmw';
		prt.insertBefore(div,elm);
		
		var box = document.createElement('input');
		box.id = 'box_'+id; box.className = 'jsmw'; box.type = 'text'; box.readOnly = true; box.value = jsmwLanguage[elm.value];
		prt.insertBefore(box,elm);
		
		var hdn = document.createElement('input');
		hdn.id = elm.id; hdn.name = elm.name; hdn.type = 'hidden'; hdn.value = elm.value;
		prt.replaceChild(hdn,elm);
		
		eval("var f1 = function(e){ jsmwFields['"+this.id+"'].evFocus(e); };"); box.onfocus = f1;
		eval("var f2 = function(e){ jsmwFields['"+this.id+"'].evBlur(e); };"); box.onblur = f2;
		eval("var f3 = function(e){ jsmwFields['"+this.id+"'].evMouseDown(e); };"); box.onmousedown = f3;
		
		this.changeRegion(this.regionNum);
	};
	this.evFocus = function(e){ this.show(); this.supressClick(); };
	this.evBlur = function(e){ this.hide(); this.clearKeyDown(); };
	this.evMouseDown = function(e){ if (this.supressClickTimer) return; if (this.hiding) this.show(); else this.hide(); };
	this.supressClick = function(){ if (!this.supressClickTimer) this.supressClickTimer = setTimeout("jsmwFields['"+this.id+"'].supressClickTimer = false;", 100); };
	this.changeRegion = function(num){
		this.regionNum = num;
		this.region = jsmwRegions[this.regionNum];
		var html = '';
		//ボディー
		html += '<ul class="body" style="background-image:url('+jsmwPath+'region/'+this.region.name+'.png)">';
		for (var i=0; i<this.region.data.length; i++){
			var arr = this.region.data[i];
			var s = arr[0], x = arr[1], y = arr[2], w = arr[3], h = arr[4];
			html += '<li id="'+this.id+'_li_'+i+'" onmousedown="jsmwFields[\''+this.id+'\'].setAndHide()" onmouseover="jsmwFields[\''+this.id+'\'].focus('+i+')" style="left:'+x+'px;top:'+y+'px;width:'+w+'px;height:'+h+'px;" /></li>';
		}
		html += '</ul>';
		//ヘッダ
		html += '<ul class="header">';
		var n;
		n = (this.regionNum < jsmwRegions.length-1) ? this.regionNum+1 : 0;
		html += '<li class="right" onmouseover="jsmwTheme.header.highlight(this)" onmouseout="jsmwTheme.header.dehighlight(this)" onmousedown="jsmwFields[\''+this.id+'\'].goNextRegion(); return false;"><span>'+jsmwLanguage[jsmwRegions[n].name]+'</span></li>';
		n = (this.regionNum > 0) ? this.regionNum-1 : jsmwRegions.length-1;
		html += '<li class="left" onmouseover="jsmwTheme.header.highlight(this)" onmouseout="jsmwTheme.header.dehighlight(this)" onmousedown="jsmwFields[\''+this.id+'\'].goPrevRegion(); return false;"><span>'+jsmwLanguage[jsmwRegions[n].name]+'</span></li>';
		html += '</ul>';
		document.getElementById('map_'+this.id).innerHTML = html;
	};
	this.nextRegion = function(focusFlag){
		var n = (this.regionNum+1 < jsmwRegions.length) ? this.regionNum+1 : 0;
		this.changeRegion(n);
		this.cur = -1;
		this.focus(0);
		//if (!focusFlag) this.cur = -1;
		//	else this.focus(0);
	};
	this.prevRegion = function(focusFlag){
		var n = (this.regionNum > 0) ? this.regionNum-1 : jsmwRegions.length-1;
		this.changeRegion(n);
		this.cur = -1;
		this.focus(this.region.data.length-1)
		//if (!focusFlag) this.cur = this.region.order.length; 
		//	else this.focus(this.region.order.length-1);
	};
	this.goNextRegion = function(){ this.nextRegion(); this.refocusing = true; document.getElementById(this.id).focus(); };
	this.goPrevRegion = function(){ this.prevRegion(); this.refocusing = true; document.getElementById(this.id).focus(); };
	this.show = function(){
		document.getElementById('map_'+this.id).style.display = 'block';
		this.setKeyDown();
		if (this.refocusing) this.refocusing = false;
			else this.focusByInput();
		this.hiding = false;
	};
	this.focus = function(cur){
		if (this.cur >= 0 && (li = document.getElementById(id+'_li_'+this.cur))) jsmwTheme.country.dehighlight(li);
		this.cur = cur;
		if (li = document.getElementById(id+'_li_'+this.cur)) jsmwTheme.country.highlight(li);
		if (box = document.getElementById('box_'+id)) box.value = jsmwLanguage[this.region.data[this.cur][0]];
	};
	this.focusNext = function(){ var cur = this.cur+1; if (cur >= this.region.data.length) this.nextRegion(true); else this.focus(cur); };
	this.focusPrev = function(){ var cur = this.cur-1; if (cur < 0) this.prevRegion(true); else this.focus(cur); };
	this.focusByInput = function(){
		var countryCode = document.getElementById(this.id).value;
		var idx = this.region.getIdxByCountryCode(countryCode);
		if (idx >= 0){
			this.focus(idx);
		} else {
			for (var i=0; i<jsmwRegions.length; i++)
				if (this.regionNum != i){
					idx = jsmwRegions[i].getIdxByCountryCode(countryCode);
					if (idx >= 0){
						this.changeRegion(i);
						this.focus(idx);
					}
				}
		}
	};
	this.setAndHide = function(){ this.set(); this.hide(); };
	this.set = function(){ if ((country = this.region.getCountryByIdx(this.cur)) && (elm = document.getElementById(id))) elm.value = country[0]; };
	this.hide = function(){
		if (jsmwLanguage[document.getElementById(this.id).value] != document.getElementById('box_'+this.id).value)
			document.getElementById('box_'+this.id).value = jsmwLanguage[document.getElementById(this.id).value];
		document.getElementById('map_'+this.id).style.display = 'none';
		this.hiding = true;
	};
	this.keydown = function(e){
		if (!e)
			e = event;
		if (elm = document.getElementById(this.id)){
			var c = (e.keyCode) ? e.keyCode : e.charCode;
			switch (c){
				case 63232: case 63276: case 33: case 38: if (this.hiding){ this.show(); } else { this.focusPrev(); this.set(); } return false;//[↑]キー
				case 63233: case 63277: case 34: case 40: if (this.hiding){ this.show(); } else { this.focusNext(); this.set(); } return false;//[↓]キー
				case 63234: case 39: this.nextRegion(); return false;//[→]キー
				case 63235: case 37: this.prevRegion(); return false;//[←]キー
				case 13: case 27: this.hide(); return false;//[esc]キー or [enter]キー
				case 9: return true;//[tab]キー
				//default: elm.value=c;return false;
			}
		}
	};
	this.setKeyDown = function(){ 
		eval("var keydown = function(e){ return jsmwFields['"+this.id+"'].keydown(e); };");//thisをバインドするため
		if (isIE) document.getElementById(this.id).onkeydown = keydown; else document.onkeydown = keydown;
	};
	this.clearKeyDown = function(){ if (isIE) document.getElementById(this.id).onkeydown = null; else document.onkeydown = null; };
	
	this.initialize(id);//コンストラクタ呼び出し
};

/**
 * Setups
 */
function setupJsmw(){
	var script;
	var scripts = document.getElementsByTagName("script");
	for (var i=0; i<scripts.length; i++){
		if (scripts[i].src && scripts[i].src.match(/jsmap_world\/map\.js(\?.*)?$/)){
			script = scripts[i];
		}
	}
	var language = (tmp = script.src.match(/\?.*language=([a-z0-9_]*)/)) ? tmp[1] : 'ja';//デフォルトで日本に設定
	var theme = (tmp = script.src.match(/\?.*theme=([a-z0-9_]*)/)) ? tmp[1] : 'blue';//デフォルトでsimpleに設定
	var path = script.src.replace(/map\.js(\?.*)?$/,'');
	document.write('<sc'+'ript type="text/javascript" src="'+path+'language/'+language+'.js"></script>');//言語データ
	document.write('<sc'+'ript type="text/javascript" src="'+path+'theme/'+theme+'/theme.js"></script>');//テーマデータ
	document.write('<link rel="stylesheet" type="text/css" href="'+path+'theme/'+theme+'/layout.css" />');//テーマのCSSファイル
	
	for (var i=0; i<jsmwRegList.length; i++) 
		document.write('<sc'+'ript type="text/javascript" src="'+path+'region/'+jsmwRegList[i]+'.js"></script>');//地図データ
	
	if (window.attachEvent) window.attachEvent('onload', setupJsmwOnLoad);//IE
		else if (window.addEventListener) window.addEventListener('load', setupJsmwOnLoad, true);//W3C
			else window.onload = setupJsmwOnLoad;
	
	jsmwPath = path;
}
function setupJsmwOnLoad(){
	for (var i=0; i<jsmwData.length; i++) 
		new jsmwRegion(jsmwData[i]);
	
	var temp = document.getElementsByTagName("input"), inputs = Array(temp.length);
	for (var i=0; i<temp.length; i++)
		inputs[i] = temp[i];
	for (var i=0; i<inputs.length; i++){
		if (inputs[i].className && inputs[i].className == 'world'){
			new jsmwField(inputs[i].id);
		}
	}
}
setupJsmw();
