//--
//-- LUSH Japan Site's Javascript Module, version 1.0.0
//--
//============================================================================
//-- 注意事項
//--  ・非同期のイベント(XMLHTTP.onreadystatechange)を使用している関係上、
//--    複数のインスタンスを生成することは出来ません。
//--
//--
//-- 関数説明
//--  ・各関数は、LUSH.xxxx となっています。
//--  ・引数が [ ] で囲ってある箇所は、任意項目です。
//----------------------------------------------------------------------------
//-- $(element)
//--   概要：document.getElementById のショートカットとして使用できます。
//--   引数：<String> element    HTMLタグのID
//--
//-- $T(arguments)
//--   概要：成功するまで引数の内容を順に試します。
//--   引数：<function> arguments    試みる関数
//--
//-- submit(formId)
//--   概要：指定したフォームIDをsubmitします。
//--   引数：<String> formId    フォームID
//--
//-- onClick(formId,buttonName)
//--   概要：ボタン名を指定して、指定したフォームIDをsubmitします。
//--   引数：<String> formId        フォームID
//--         <String> buttonName    ボタン名
//--
//--   メモ：<input type="hidden" name="onClick"> を自動生成し、
//--         ボタン名を value に設定しています。
//--         ボタン名を取得する際は、Request.Form("onClick") にて取得できます。
//--
//-- openSubWin(url [, windowOption])
//--   概要：サブウインドウを開きます。
//--   引数：<String> url               サブウインドウで開くURL
//--         <Hash>   [windowOption]    サブウインドウのオプション
//--                      <Number> [width]     幅
//--                      <Number> [height]    高さ
//--                      <String> [target]    ウインドウ名
//--
//============================================================================
// function MM_swapImgRestore() { //v3.0
//   var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
// }
// 
// function MM_preloadImages() { //v3.0
//   var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
//     var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
//     if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
// }
// 
// function MM_findObj(n, d) { //v4.01
//   var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
//     d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
//   if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
//   for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
//   if(!x && d.getElementById) x=d.getElementById(n); return x;
// }
// 
// function MM_swapImage() { //v3.0
//   var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
//    if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
// }

function gene_window(mypage, myname, w, h, scroll) {
  var win_width = (screen.width - w) / 2;
  var win_height = (screen.height - h) / 2;
  win_detail ='height='+h+',width='+w+',top='+win_height+',left='+win_width+',scrollbars='+scroll;
  win = window.open(mypage, myname, win_detail)
  if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); } }
function gene_window_x(mypage, myname, w, h, scroll) {
  var win_width = (screen.width - w) / 2;
  var win_height = (screen.height - h) / 2;
  win_detail ='height='+h+',width='+w+',top=0,left=0,scrollbars='+scroll;
  win = window.open(mypage, myname, win_detail)
  if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); } }


function LUSH_Engin() {

	if (typeof LUSH != 'undefined') return;

	this.instances = new Object;
	this.instancesLength = 0;
	this.Zip2Adr_Config = new Array;

};
LUSH_Engin.prototype = {

	init : function(s) {
		this.env = s;
		this._defaultSet('http_protocol','http://');
		this._defaultSet('server_name', 'www.lushjapan.com');
		this._defaultSet('root_url', '/');
		this._defaultSet('subwin_width', '720');
		this._defaultSet('subwin_height', '500');
		this._defaultSet('subwin_target', 'LUSHJapanSubWindow');
	},

	$ : function(element) {
		if (typeof element == 'string') {
			return this.$T(
				function(){ return document.getElementById(element); }
// 				function(){ return document.all(element)             },
// 				function(){ return document.layers[element]          }
			)
		}
	},

	$T : function() {
		var retVal;
		for (var i = 0; i < arguments.length; i++) {
			var fnc = arguments[i];
			try {
				retVal = fnc();
				break;
			} catch (e) {}
		}
		return retVal;
	},

	$HS : function(hashstring) {
		if (typeof hashstring != 'string') { return; }
	
		var arrHash = new Array;
		var posSt = new Number;
		var posEd = new Number;
		var arrHashstring = new Array;
		hashstring = this.Trim(hashstring);
	
		// out of '{' '}'
		hashstring = hashstring.toString().substring(1, hashstring.toString().length - 1);
		hashstring = this.Trim(hashstring);
	
		if ( typeof hashstring !='undefined' ) {
			// divide item
			arrHashstring = hashstring.split(',');
			for (var item in arrHashstring) {
				if (typeof item == 'undefined') { break; }
			
				// divides into name to value
				var arrItem = arrHashstring[item].split(':');
				var name  = this.Trim(arrItem[0]);
				var value = this.Trim(arrItem[1]);
			
				// out of '
				name = name.substring(1, name.length - 1);
			
				if ( value.toLowerCase() == 'true' ) {
					value = true;
				} else {
					if ( value.toLowerCase() == 'false' ) {
						value = false;
					} else {
						if ( value.charAt(0) == '\'' && value.charAt(value.length - 1) == '\'' ) {
							// out of '
							value = value.substring(1, value.length - 1);
						} else {
							// number.NaN ?
							value = value - 0;
						}
					}
				}
			
				arrHash[ name ] = value;
			}
		}
		return arrHash;
	},

	Trim : function(inText) {
		if (typeof inText == 'number') { inText = inText.toString() }
		if (typeof inText != 'string') { return; }
	
		var retstr = inText;
	
		retstr = this.LTrim(retstr);
		retstr = this.RTrim(retstr);
	
		return retstr;
	},

	RTrim : function(inText) {
		if (typeof inText == 'number') { inText = inText.toString() }
		if (typeof inText != 'string') { return; }
	
		var Len = inText.length - 1;
		var wkstr = new String;
		var retstr = new String;
	
		for ( var i = Len; i >= 0; i-- ) {
			wkstr = inText.charAt(i);
		
			if ( wkstr != ' ' && wkstr != '　' && wkstr != '' && wkstr != null  ) {
				i++;	// back count
				retstr = inText.substring(0,i);
				break;
			}
		}
		return retstr;
	},

	LTrim : function(inText) {
		if (typeof inText == 'number') { inText = inText.toString() }
		if (typeof inText != 'string') { return; }
	
		var Len = inText.length;
		var wkstr = new String;
		var retstr = new String;
	
		for ( var i = 0; i < Len; i++ ) {
			wkstr = inText.charAt(i);
		
			if ( wkstr != ' ' && wkstr != '　' && wkstr != '' && wkstr != null ) {
				retstr = inText.substring(i,Len);
				break;
			}
		}
		return retstr;
	},

	go : function(url) {
		location.href = getFullURL(url);
	},

	getFullURL : function(url) {
		var u = new String;
		u  = this.env['http_protocol'];
		u += this.env['server_name'];
		u += this.env['root_url'];
		u += url;
		return u;
	},

	submit : function(formId) {
		var f = this.$(formId);
		if (f) {
			f.submit();
		} else { alert('[LUSH.submit] not found formId'); }
	},

	onClick : function(formId,buttonName) {
		var f = this.$(formId);
		if (f) {
			f.innerHTML += '<input type="hidden" name="onClick" value="' + buttonName + '">';
			f.submit();
		} else { alert('[LUSH.onClick] not found formId'); }
	},

	selectedValue : function(elementName, value) {
		if (this.$(elementName)) {
			if (this.$(elementName).options) {
				var o = this.$(elementName).options;
				for (var i = 0; o.length; i++) {
					if ( o[i].value == value ) {
						return i;
						break;
					}
				}
			}
		}
	},

	_subWindow : Object,
	openSubWin : function(url, windowOption) {
		if (typeof url == 'string') {
			var style = new String;
			var target = new String;
			style = 'resizable=yes,status=yes,scrollbars=yes';
			if (windowOption && windowOption.width ) { style  += ',width='  + this.getEnv('subwin_width',  windowOption.width); } else { style += ',width='  + this.env['subwin_width'];  }
			if (windowOption && windowOption.height) { style  += ',height=' + this.getEnv('subwin_height', windowOption.height);} else { style += ',height=' + this.env['subwin_height']; }
			if (windowOption && windowOption.target) { target  = this.getEnv('subwin_target', windowOption.target);             } else { target = this.env['subwin_target'];              }
		
			url = this.getFullURL(url);
			this._subWindow = window.open(url, target, style);
			this._subWindow.focus();
		
			// document.getElementsByTagName('body').item(0).attachEvent('onunload', );
			LUSH.addEvent(window, "unload", LUSH_Engin.prototype.unloadHandler);
			LUSH.addEvent(window.document, "beforeunload", LUSH_Engin.prototype.unloadHandler);
		
		} else { alert('[LUSH.openSubWin] url is not string'); }
	},

	closeSubWin : function() {
		if (this._subWindow.close) {
			this._subWindow.close();
		}
	},


	Zip2Adr : function(cnf) {
		// input validate ---------------------------------
		if (!cnf) {
			alert('[LUSH.Zip2Adr] config is not found');
			return;
		}
	
		if (!this.$(cnf.eId)) {
			alert('[LUSH.Zip2Adr] element(eId) is not found');
			return;
		}
		if ( (!this.$(cnf.z1)) || (!this.$(cnf.z2)) ) {
			alert('[LUSH.Zip2Adr] element(z1 or z2) is not found');
			return;
		}
		if ( (!this.$(cnf.pSel)) || (!this.$(cnf.cTxt)) || (!this.$(cnf.bTxt)) ) {
			alert('[LUSH.Zip2Adr] element(pSel or cTxt or bTxt) is not found');
			return;
		}
	
		var zipCode = this.$(cnf.z1).value + this.$(cnf.z2).value;
		var errTag = this.$(cnf.eId);
	
		if (zipCode.length == 0) {
			errTag.innerHTML = '郵便番号を入力してください。';
			return;
		} else {
			errTag.innerHTML = '　';
		}
	
		// save config data
		this.Zip2Adr_Config = cnf;
		// ------------------------------------------------
	
		// HTTP instance ----------------------------------
		var o = new LUSH_Engin.HTTP();
		var inst_id = o.instType + this.instancesLength;	// ex. 'http0'
		var isInit = o.init(inst_id,{});
		if (isInit == false) return;
	
		var postData = new String;
		postData  = 'do=zip2adr'
		postData += '&zipcode=' + zipCode;
	
		o.setURL('function/lib_webservice.asp');
		o.readyState_2 = this.Zip2Adr_readyState2;
		o.readyState_3 = this.Zip2Adr_readyState3;
		o.readyState_4 = this.Zip2Adr_readyState4;
	
		// add instances
		this.instances[inst_id] = o;
		this.instancesLength ++;
		this.instances[inst_id].send(postData);
		// ------------------------------------------------
	},
	
	Zip2Adr_readyState2 : function() {
		// load config data
		var errTag = LUSH.$(LUSH.Zip2Adr_Config.eId);
		errTag.innerHTML = '準備中・・・';
	},
	Zip2Adr_readyState3 : function() {
		// load config data
		var errTag = LUSH.$(LUSH.Zip2Adr_Config.eId);
		errTag.innerHTML = '検索中・・・';
	},
	Zip2Adr_readyState4 : function(e) {
		// load config data
		var cnf = LUSH.Zip2Adr_Config;
		var errTag = LUSH.$(cnf.eId);
		if (e.status == '200') {
			errTag.innerHTML = '　';
		
			var adrData
			var zip1 = new String;
			var zip2 = new String;
			adrData = LUSH.$HS( e.responseText )
		
			if ( adrData.IsFound == false ) {
				errTag.innerHTML = '該当する住所が見つかりませんでした。';
			} else {
				if (LUSH.$(cnf.pSel) && typeof adrData.PrefCd != 'undefined') { LUSH.$(cnf.pSel).selectedIndex = LUSH.selectedValue(cnf.pSel, adrData.PrefCd); }
				if (LUSH.$(cnf.pTxt) && typeof adrData.Pref != 'undefined')   { LUSH.$(cnf.pTxt).value = adrData.Pref;           }
				if (LUSH.$(cnf.cTxt) && typeof adrData.City != 'undefined')   { LUSH.$(cnf.cTxt).value = adrData.City;           }
				if (LUSH.$(cnf.bTxt) && typeof adrData.Chou != 'undefined')   { LUSH.$(cnf.bTxt).value = adrData.Chou;           }
			
				if (adrData.Zipcode) {
					zip1 = adrData.Zipcode.substring(0, 3);
					zip2 = adrData.Zipcode.substring(3, 7);
				}
				if ( LUSH.$(cnf.z1) && LUSH.$(cnf.z2) ) {
					LUSH.$(cnf.z1).value = zip1;
					LUSH.$(cnf.z2).value = zip2;
				}
			}
		} else {
			errTag.innerHTML = '接続に失敗しました。[HTTP status:' + e.status + ']';
		}
	},




	_defaultSet : function(key, def_val) {
		var v = (typeof(this.env[key]) == "undefined") ? def_val : this.env[key];
		this.env[key] = v;
	},

	getEnv : function(key, val) {
		var v = (typeof(this.env[key]) == "undefined") ? '' : this.env[key];
		return (typeof(val) == "undefined") ? v : val;
	},



	hoge : function(){}
};

LUSH_Engin.prototype.addEvent = function(o, n, h) {
	if (o.attachEvent)
		o.attachEvent("on" + n, h);
	else
		o.addEventListener(n, h, false);
};

LUSH_Engin.prototype.unloadHandler = function() {

	LUSH._subWindow.close();

};

var lush = LUSH_Engin;
var LUSH = new LUSH_Engin();


// HTTP
LUSH_Engin.HTTP = function() {
	if (typeof LUSH == 'undefined') return;

	this.http_id = '';
	this.instType = 'http';
	this.http = Object;

	// readyState
	// 0 : The request is not initialized
	// 1 : The request has been set up
	// 2 : The request has been sent
	// 3 : The request is in process
	// 4 : The request is complete
	this.readyState = 0;
	this.readyState_2 = function(){};
	this.readyState_3 = function(){};
	this.readyState_4 = function(e){};
	this.URL = ''
	this.method = 'POST'
	this.status = '';
	this.responseText = '';
};
LUSH_Engin.HTTP.prototype = {
	init : function(id, s) {
		this.http_id = id;
		this.env = s;
		this.http = LUSH.$T(
			function(){ return new XMLHttpRequest()                    },
			function(){ return new ActiveXObject('Msxml2.XMLHTTP')     },
			function(){ return new ActiveXObject('Microsoft.XMLHTTP')  }
			);
		if (!this.http) {
			return false;
		} else {
			if (this.http.readyState != 0) { this.http.about(); }
			return true;
		}
	},

	setURL : function(url) {
		this.URL = LUSH.getFullURL(url);
	},

	send : function(data) {
		if (this.URL == '') return false;
	
		this.http.open(this.method, this.URL, true);
		this.http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	
		this.http.onreadystatechange = Function( "LUSH_Engin.HTTP.prototype.callback('" + this.http_id + "')" );
		// this.http.onreadystatechange = Function( "LUSH.instances['" + this.http_id + "'].callback('" + this.http_id + "')" );
		this.http.send(data);
	},

	callback : function(id) {
	
		var inst = LUSH.instances[id];
	
		// window.status = '[' + id + ']readyState : ' + inst.http.readyState;
	
		inst.readyState = inst.http.readyState;
		if ( inst.http.readyState == 4 ) {
			inst.status = inst.http.status;
			inst.responseText = inst.http.responseText;
			if (inst.http.status == '500') {
				var w = window.open();
				w.document.open();
				w.document.write(inst.http.responseText);
				w.document.close();
			}
		}
	
		switch (inst.readyState) {
		case 2:
			inst.readyState_2();
			break;
		
		case 3:
			inst.readyState_3();
			break;
		
		case 4:
			inst.readyState_4( {
				 status : inst.status
				,responseText : inst.responseText
				} );
			break;
		}

	},

	hoge : ''
};

