var CaduceusClass = Class.create();

CaduceusClass.prototype = {
	initialize: function(callback, frequency) {

		this.browser = this.checkBrowser();

		var bodyClassName = document.body.className;
		var bodyId = document.body.id;

		// class名から method名を作成 (ex: bodyTop -> initBodyTop)
		var initByClassName = 'init' + bodyClassName.substr(0,1).toUpperCase() + bodyClassName.substr(1);

		// bodyのclassによる初期化 (class名、method共にあれば)
		bodyClassName && this[initByClassName] && this[initByClassName]();


		// id名から method名を作成 (ex: bodyTop -> initBodyTop)
		var initById = 'init' + bodyId.substr(0,1).toUpperCase() + bodyId.substr(1);

		// bodyのclass名とid名が同じだった場合の２重初期化を防止
		if (initByClassName != initById) {
			// bodyのidによる初期化 (id、method共にあれば)
			bodyId && this[initById] && this[initById]();
		}

		// 「クリップボードへコピー」ボタン
		if ($('btClip')) {
			this.codeId = 'stickyCode';
			Event.observe($('btClip'), 'click', this.clip.bind(this), false);
		}

		// フォーカス時に全選択
		if ($('stickyCode')) {
			$('stickyCode').onfocus = function () {
				this.select();
			}
		}

/*
		if ($('special') && $('lbSpecial')) {
			var str = $('lbSpecial').innerHTML;
			$('lbSpecial').style.display = 'none';
			$('special').innerHTML = str;
			$('special').style.visibility = 'visible';
		}

		if ($('what') && $('lbWhat')) {
			var str = $('lbWhat').innerHTML;
			$('lbWhat').style.display = 'none';
			$('what').innerHTML = str;
			$('what').style.visibility = 'visible';
		}
*/


	},

	initBodyTopPage: function () {
		if ($('gotoPlay')) {
			setTimeout(function() {
			$('gotoPlay').innerHTML = '<a href="javascript:(function(){angelbank.open()})()">時給力を診断する</a>';
			}, 550);
		}

	},

	initBodyResultPage: function () {
	    if (! /Netscape/.test(navigator.userAgent)) {
			RUZEE.ShadedBorder.create({ corner:8, shadow:0 }).render('advice');
		} else {
			$('advice').style.backgroundColor = '#ffd8d8';
		}

		if ($('gotoPlay')) {
			setTimeout(function() {
			$('gotoPlay').innerHTML = '<a href="javascript:(function(){angelbank.open()})()">もう一度診断する</a>';
			}, 300);
		}

	},

	initBodyEntry: function () {
		this.industryXjob();

		Event.observe($('industry'), 'change', this.industryXjob, false);
		Event.observe($('btEntry'), 'click', this.sendEntryForm.bind(this), false);
		$('name').focus();
	},

	industryXjob: function() {
		var indId = $F('industry');

		$('job').innerHTML = '';
/*
		var c = $('job').childNodes;
		for (var i=0; i<c.length; i++) {
			$('job').removeChild(c[i]);
		}
*/

		var html = '';
		for (var i=0; i<ind[indId].length; i++) {

			var opt = document.createElement('option');
			opt.value = ind[indId][i].jobId;
			opt.appendChild(document.createTextNode(ind[indId][i].name));
			$('job').appendChild(opt);


//			html += '<option value="' + ind[indId][i].jobId + '">' + ind[indId][i].name + '</option>';

		}

//		$('job').innerHTML = html;


/*
<!--
<? foreach ($jobs as $job_list): ?>
<option class="ind_<?=$job_list["industry_id"]?>" value="<?=$job_list["id"]?>"><?=$job_list["name"]?></option>
<? endforeach; ?>
-->
*/


	},

	sendEntryForm: function() {

		// validation
		var iName = $('name');
		var iIncome = $('income');

		// 両端のスペース・tab除去
		this.trimer(iName);
		this.trimer(iIncome);

		// 年収 全->半
		iIncome.value = iIncome.value.toHankakuAscii();
		iIncome.value = iIncome.value.replace(/\D/g, '');
		iIncome.value = iIncome.value - 0;


		var fields = [
			'name',
			'age',
			'industry',
			'job',
			'income',
			'hours',
			'rest',
			'pid'
		];

		var errors = [];

		// 空欄チェック
		for (var i=0; i<fields.length; i++) {
			if ($F(fields[i]) == '') {
				errors.push(fields[i]);
			}
		}

		if (errors.length) {
			this.displayErrors(errors);
//			return false;
		}
		// 〆 validation


		this.w = window.open('', 'angelbank');

		var pars =
			'name=' + $F('name') +
			'&age='  + $F('age')  +
			'&industry=' + $F('industry') +
			'&job='  + $F('job')  +
			'&income=' + $F('income') +
			'&hours=' + $F('hours') +
			'&rest=' + $F('rest')+
			'&pid=' + $F('pid')+

			'&t=' + (new Date); // anti cache

		new Ajax.Request(
			'/entry',
			{
				method: 'post',
				parameters: pars, 
				onComplete: this.entryResponse.bind(this),
				onFailure: this.entryError
			}
		);
	},


	entryResponse: function(xhr) {
		var r = xhr.responseText;

		if (r.match(/error:(.*)$/i)) {
			this.displayErrors(RegExp.$1.split(','));
			this.w.close();
		}

		if (r.match(/^[0-9a-zA-Z]+$/)) {
			this.w.location.href = 'http://' + location.hostname + '/result/' + r;
			this.w.focus();
		}

	},

	entryError: function(xhr) {
//		alert(xhr.getAllResponseHeaders());
		whis.w.close();
	},

	trimer: function(elm) {
		elm.value = elm.value.replace(/[\r\n\t]/g, '');
		elm.value = elm.value.replace(/^[ 　]+/g, '');
		elm.value = elm.value.replace(/[ 　]+$/g, '');
	},

	displayErrors: function(errors) {

		var fields = $$('.inputError');
		for (var i=0;i<fields.length;i++) {
			fields[i].innerHTML = '';
		}

		for (var i=0; i<errors.length; i++) {
			var e = 'error_' + errors[i];
			if ($(e)) {
				$(e).innerHTML = '(入力内容に誤りがあります)';
				// new Effect.Highlight($(e));
				new Effect.Highlight($(e), { startcolor: '#ff8888', endcolor: '#ffffff', duration: 1.2 });
			}
		}
	},

	checkAfiId: function(ev) {
		var inputAmazon  = $('amazon_id');
		var inputRakuten = $('rakuten_id');

		if (!(inputAmazon && inputRakuten)) {
			return false;
		}

		var noneStr = '(なし)';
		var noneColor = '#777777';

		if (ev) {
			var elm = Event.element(ev);

			switch (ev.type) {
				case 'focus':
					if (elm.value == noneStr) {
						elm.value = '';
						elm.style.color = '';
					}
					break;

				case 'blur':
					if (elm.value == '') {
						elm.value = noneStr;
						elm.style.color = noneColor;
					}

					break;
			}
		} else {
			if (inputAmazon && (inputAmazon.value == '' || inputAmazon.value == noneStr)) {
				inputAmazon.value = noneStr;
				inputAmazon.style.color = noneColor;
			} else {
				inputAmazon.style.color = '';
			}

			if (inputRakuten && (inputRakuten.value == '' || inputRakuten.value == noneStr)) {
				inputRakuten.value = noneStr;
				inputRakuten.style.color = noneColor;
			} else {
				inputRakuten.style.color = '';
			}
		}
	},


	clip: function(ev) {
		var code = $(this.codeId);
		if (code) {
			code.select();

			if (clipbrd) {
				clipbrd.copyText(code.value);
			}
		}
	},

	clipResult: function(ev) {
		var result = $(this.resultId);
		if (result) {
			result.select();

			if (clipbrd) {
				clipbrd.copyText(result.value);
			}
		}

	},


	checkBrowser: function () {
		var ua = navigator.userAgent;
		var browser = null;

		(!!window.ActiveXObject)  && (browser = 'msie');
		(ua.match('Gecko')) 	  && (browser = 'mozes');
		(ua.match('AppleWebKit')) && (browser = 'safari');
		(!!window.opera)		  && (browser = 'opera');
		(ua.match('Konqueror'))   && (browser = 'konqueror');

		return browser;
	},


	applyLineBreaker: function(node) {
		var s = document.createElement('script');
		s.setAttribute('charset', 'utf-8');
		s.setAttribute('type', 'application/x-javascript');
		s.setAttribute('src', '/lib/external/linebreak.js');
		document.body.appendChild(s);
//		lineBreaker(node);
	},

	initBodyadminSalary: function () {
		this.adminindustryXjob();

		Event.observe($('searchindustry'), 'change', this.adminindustryXjob, false);
	},

	adminindustryXjob: function() {
		var indId = $F('searchindustry');
		$('searchjob').innerHTML = '';

		var html = '';
		for (var i=0; i<ind[indId].length; i++) {

			var opt = document.createElement('option');
			opt.value = ind[indId][i].jobId;
			opt.appendChild(document.createTextNode(ind[indId][i].name));
			$('searchjob').appendChild(opt);
		}

	}


}




Event.observe(window, 'load', function(){
	new CaduceusClass();
}, false);

