
comunibase = {
	domain: location.protocol + "//" + location.host + "/",
	
	ajax: function(param, func){
		d = new Date();
		param += (param ? "&":"?") + "serial=" + d.getFullYear()+d.getMonth()+1+d.getDate()+d.getHours()+d.getMinutes()+d.getSeconds()+d.getMilliseconds();
		new Ajax.Request(this.domain, {
			parameters : param, 
			method: "get",
			onComplete : func
		});
	},
	
	ajaxHTML: function(a){
		
		if(!a || !a.uri) return;
		if(!a || !a.base) return;
		
		this.content = a.base;
/*
		if(this.loading.src==""){
			this.loading.src = "/pcstorage/img/loading.gif";
			this.loading.style.position = "absolute";
		}
		this.loading.style.left = NTAgis.P(this.width/2-50);
		this.loading.style.top  = NTAgis.P(this.height/2-25);
		this.loading.style.display="block";
		this.base.appendChild(this.loading);
*/
		var uri=a.uri, param="";
		if(typeof a.param=="string"){
			var parameters = a.param.split("&");
			for(var i=0; i<parameters.length; i++){
				var key = parameters[i].split("=")[0], value=parameters[i].split("=")[1];
				if(value.match(/[^a-zA-Z0-9-_%]/)){
					value = EscapeUTF8(value);
				}
				param += (i>0?"&":"") + key + "=" + value;
			}
		}else if(typeof a.param=="object"){
			param = $H(a.param).toQueryString();
		}
		if(a.form){
			param = Form.serialize(a.form);
		}
		d = new Date();
		if(param != ""){
			param +="&";
		}else{
			param +="?";
		}
		param += "serial=" + d.getFullYear()+d.getMonth()+1+d.getDate()+d.getHours()+d.getMinutes()+d.getSeconds()+d.getMilliseconds();
		
		this.action = a.uri + "?" + param;
		if(a.func){
			this.onExpandFunc = a.func;
		}
		var options = new Object();
		options.parameters = param;
		options.onComplete = this.expand.bind(this);
		if(a.method && a.method == "post"){
			options.method = "post";
		}else{
			options.method = "get";
		}
		new Ajax.Request(uri,options);
	},
	
	expand: function(response){
		this.content.innerHTML = "";
		this.content.innerHTML = this.analyzeHTML(response.responseText);

		this.executeScript(response.responseText, this.action);
		this.content.scrollTop = 0;
		(this.onExpandFunc||function(){})();
		this.onExpandFunc = function(){};
	},

	ScriptFragment: '<script[^>]*>([\r\n\s\t]*<\![-]*)?((?:\n|\r|.)*?)(\/\/[\s\t\-]*>)?[\r\n]*</script>',
	analyzeHTML: function(html){
		// HTMLタグを返却
		return html.replace(new RegExp(this.ScriptFragment, 'img'), '');
	},
	executeScript: function(html, action){
		var matchAll = new RegExp(this.ScriptFragment, 'img');
		var matchOne = new RegExp(this.ScriptFragment, 'im');
		var scripts = (html.match(matchAll) || []).map(function(scriptTag) {
			return (scriptTag.match(matchOne) || ['','',''])[2];
		});
		scripts.each(function(value,idx){
			try{
				if(value) eval(value);
			}catch(e){
/*
				var options = new Object();
				options.parameters = "message=" + EscapeUTF8(e.message) + "&script="+EscapeUTF8(value) + "&action=" + EscapeUTF8(action||"") + "&line=" + (e.number & 0xffff);
				options.method="post";
				new Ajax.Request("/pcnavi/mjx/scripterr.jsp", options);
*/
				alert("error:" + value);
//				throw e;
			}
		});
		return scripts;
	},
	
	/**
	*	windowがロードされているかを判定
	*	@return	boolean		ロード完了：true/未ロード：false
	**/
	isWindowLoaded: function(){
		return (this.loaded || false);
	},
	
	isnull:function(obj,name){
		var text = String(obj.value).replace(/^[ 　]*/gim, "");
		if(text==""){
			alert(name+"を入力してください。");
			obj.focus();
			return false;
		}
		return true;
	},

	isnum: function(obj, name){
		if(obj.value != ""){
			if(isNaN(obj.value)){
				alert(name+"は半角英数字のみで入力してください");
				obj.focus();
				return false;
			}
		}
		return true;
	},

	issame:function(){
		args = $A(arguments), value=args.shift(), ret=true;
		args.each(function(ag){
			if(value!=ag) ret=false;
		});
		return ret;
	},

	ischecked: function(obj){
		if(obj && obj.length && obj.length>1){
			obj.each(function(obj){
				if(obj.checked) return true;
			});
			return false;
		}else{
			return obj.checked;
		}
	}
};

$NDEvent.add(window, "load", function(){comunibase.loaded = true});

comunibase.keyword = Object.extend(Object.extend({}, comunibase),{
	check: function(form){
		if(!this.isnull(form.keyword,"キーワード")) return false;
	}
});

comunibase.auth = Object.extend(Object.extend({}, comunibase),{
	login: function(form){
		if(!this.isnull(form.mail,"メールアドレス")) return false;
		if(!this.isnull(form.pwd,"パスワード")) return false;
	},
	password: function(form){
		if(!this.isnull(form.mail,"登録したメールアドレス")) return false;
	}
});



comunibase.data = Object.extend(Object.extend({}, comunibase),{});

comunibase.data.form = Object.extend(Object.extend({}, comunibase.data),{

	preview: function(form, element){
		if(!this.insert(form, false)){
			return false;
		}
		this.ajaxHTML({uri:this.domain, base:element ,action:"post", form:form, func:function(){
			$("data_preview").style.display = "";
			$("data_form").style.display = "none";
		}});
	},

	form: function(){
		$("data_preview").style.display = "none";
		$("data_form").style.display = "";
	},

	addPreviewFunction: function(func){
		if(!this.prevFunc) this.prevFunc = [];
		this.prevFunc.push(func);
	},

	
	addInsertFunction: function(func){
		if(!this.submitFunc) this.submitFunc = [];
		this.submitFunc.push(func);
	},
	
	insert: function(form, isconfirm){
		if(!this.isnull(form.data_name,"データ名称") || !this.isnull(form.data_ruby,"データかな") || !this.isnull(form.exp1_exp,"データ説明")){
			this.form();
			return false;
		}

		if(form.data_ruby.value.match(new RegExp('[^あ-んー、]','img'))){
			alert("データ名かなには平仮名のみを入力して下さい");
			return false;
		}

		(this.submitFunc||[]).each(function(func){
			func.apply(window);
		});

//		var elements  =$A(document.getElementsByClassName("mustNumeric", form));
		
		var iserror=false;

		Form.getElements(form).each((function(element){
			if(iserror) return;
			if(element.className == "mustNumeric"){
				if(!this.isnum(element,element.title)){
					iserror = true;
				}
			}
		}).bind(this));
		
		if(iserror){
			this.form();
			return false;
		}

		if(isconfirm==null || isconfirm){
			return confirm("登録します。よろしいですか？");
		}
		return true;
	}
});

comunibase.db = Object.extend(Object.extend({}, comunibase),{});

comunibase.db.form = Object.extend(Object.extend({}, comunibase.db),{

	step1: function(form){
		if(!this.isnull(form.db_name,"データベース名称")) return false;
		if(!this.isnull(form.db_exp,"データベース説明文")) return false;
		if(!this.isnull(form.cat_name,"カテゴリ設定")) return false;
		return true;
	},
	
	/**
	*	DB作成STEP1の簡単設定の選択による詳細条件の指定
	*
	*
	*
	**/
	config: function(){
		form = document.dbbase;
		if(form.config[0].checked){
			form.visibility[0].checked = true;		//閲覧条件
			form.communicate[0].checked = true;		//コミュニケーションパーツ参加条件
			form.permitter[0].checked = true;		//データ投稿条件
			form.modification[0].checked = true;	//データ変更権限
			form.alliance[0].checked = true;		//ビルダー登録承認有無
		}
		if(form.config[1].checked){
			form.visibility[0].checked = true;		//閲覧条件
			form.communicate[0].checked = true;		//コミュニケーションパーツ参加条件
			form.permitter[1].checked = true;		//データ投稿条件
			form.modification[1].checked = true;	//データ変更権限
			form.alliance[0].checked = true;		//ビルダー登録承認有無
		}
		if(form.config[2].checked){
			form.visibility[2].checked = true;		//閲覧条件
			form.communicate[2].checked = true;		//コミュニケーションパーツ参加条件
			form.permitter[0].checked = true;		//データ投稿条件
			form.modification[0].checked = true;	//データ変更権限
			form.alliance[1].checked = true;		//ビルダー登録承認有無
		}
		if(form.config[3].checked){
			form.visibility[3].checked = true;		//閲覧条件
			form.communicate[3].checked = true;		//コミュニケーションパーツ参加条件
			form.permitter[1].checked = true;		//データ投稿条件
			form.modification[1].checked = true;	//データ変更権限
			form.alliance[1].checked = true;		//ビルダー登録承認有無
		}
	},
	display_setting: function(ancher){
		if($("custom").style.display == "none"){
			$("custom").style.display = "";
			var img = new Image();
			img.src= "http://strg.communibase.com/img/bt_close.gif";
			ancher.width=78;
			ancher.height=25;
			ancher.src = img.src;
		}else{
			$("custom").style.display = "none";
			var img = new Image();
			img.src= "http://strg.communibase.com/img/bt_morecreate.gif";
			ancher.width=91;
			ancher.height=25;
			ancher.src = img.src;
		}
	},
	
	builder: function(form){
		if(!this.isnull(form.keystring, "英数字")) return false;
		if(!this.ischecked(form.agree)){
			alert("規約への同意を行ってください");
			return false;
		}
		return true;
	},
	
	advance: function(ancher){
		if($("advance").style.display == "none"){
			$("advance").style.display = "";
			var img = new Image();
			img.src= "http://strg.communibase.com/img/bt_close.gif";
			ancher.width=78;
			ancher.height=25;
			ancher.src = img.src;
		}else{
			$("advance").style.display = "none";
			var img = new Image();
			img.src= "http://strg.communibase.com/img/bt_moresearch.gif";
			ancher.width=114;
			ancher.height=25;
			ancher.src = img.src;
		}
	}
});

comunibase.db.top = Object.extend(Object.extend({}, comunibase.db),{
	move : 470,
	mover : null,
	moveLeft: function(element){
		var frameWidth = element.parentNode.offsetWidth;
		var selfWidth = element.offsetWidth;
		var max = frameWidth - selfWidth;

		if(!this.mover) this.mover= new NTAgis.Mover(element,{});
		
		if(element.offsetLeft - this.move < max){
			this.mover.setOption({left: max,speed:1});
		}else{
			this.mover.setOption({left: element.offsetLeft - this.move,speed:1});
		}
		this.mover.run();
	},
	
	/**
	* 日(24時間表示)のスケジュールを右へスクロールする
	*
	*
	**/
	moveRight: function(element){
		if(!this.mover) this.mover= new NTAgis.Mover(element,{});

		if(element.offsetLeft + this.move < 0){
			this.mover.setOption({left:element.offsetLeft + this.move,speed:1});
		}else{
			this.mover.setOption({left:0,speed:1});
		}
		this.mover.run();
	}
});

comunibase.db.bbs = Object.extend(Object.extend({}, comunibase.db),{
	check: function(form){
		if(!this.isnull(form.title, "タイトル")) return false;
		if(!this.isnull(form.detail, "内容")) return false;
		return confirm("掲示板に投稿します。よろしいですか？");
	}
});

comunibase.data.grapevine = Object.extend(Object.extend({}, comunibase.data),{
	check: function(form){
		if(!this.isnull(form.title, "タイトル")) return false;
		if(!this.isnull(form.detail, "内容")) return false;
		return confirm("クチコミを投稿します。よろしいですか？");
	}
});

comunibase.data.judge = Object.extend(Object.extend({}, comunibase.data),{
	vote: function(element, judge, dbid, dataid, colname){
		if(confirm("投票してよろしいですか？")){
		
			this.target = colname;
			
			this.ajax("next=judge&judge=" + (judge?1:0) + "&dbid=" + dbid + "&dataid=" + dataid + "&col=" + colname, this.onVoted.bind(this));
		}
	},
	
	onVoted: function(context){
		eval("res = "+context.responseText);
		if(res.status == "error"){
			alert(res.msg);
		}else{
//			alert(res.msg);
			this.reload(this.target, new Number(res.yes), new Number(res.no));
		}
	},
	
	reload: function(judgeName,yesCount,noCount){

		if(yesCount==0 && noCount==0) return;

		var yes_width = Math.round(yesCount*100/(yesCount+noCount));
		var no_width  = Math.round(noCount*100/(yesCount+noCount));

		
		if(yes_width) new NTAgis.Resizer($(judgeName+"_yes"), {startx:0, endy:8, endx:yes_width, speed:1, interval:200})
		if(no_width) new NTAgis.Resizer($(judgeName+"_no"), {startx:0, endy:8, endx:no_width, speed:1, interval:200})
		
		$(judgeName+"_yes_count").innerHTML = yesCount;
		$(judgeName+"_no_count").innerHTML = noCount;
	
	}
});

comunibase.data.score = Object.extend(Object.extend({}, comunibase.data),{

	openForm: function(element){
//		$NDElement.alpha(element,85);
		element.style.display = "";
		new NTAgis.Resizer(element, {startx:1,starty:1,endx: element.parentNode.offsetWidth-6, endy:element.parentNode.offsetHeight - 6});
		
	},

	closeForm: function(element){
		new NTAgis.Resizer(element, {endx: 1, endy:1, func:function(){element.style.display='none';}});
	},

	vote: function(element, $name, dbid, dataid, segment, mode){
	
		this.target = $name;
		this.mode = mode;
		
		var input = ($($name+"_input") ||{});
		var score = input.value;
		
		if(!this.isnull(input,"点数")) return false;
		if(!this.isnum(input,"点数")) return false;
		
		if(score > 100 || score < -1){
			alert("点数は0から100の間で入力してください");
			return false;
		}

		if(confirm("投票してよろしいですか？")){
			this.ajax("next=score&score=" + score + "&dbid=" + dbid + "&dataid=" + dataid + "&segment=" + segment, this.onVoted.bind(this));
			this.closeForm(element);
			($($name+"_input") ||{}).value = "";
		}
	},

	onVoted: function(context){
	
//	alert(context.responseText);
	
		eval("res = "+context.responseText);
		if(res.status=="error"){
			alert(res.msg);
		}else{
			if(this.mode == 1 || this.mode == 2){
				this.reloadAvarage(res.score, res.count);
			}else{
			}
		}
	},
	
	reloadAvarage: function(score,count){
		for(var i=0; i<score.length; i++){
			var top = -(score.charAt(i) * 40);
			new NTAgis.Mover($(this.target + "_score" + i), {top: top, speed: 1, speed:1, interval: 100*i});
		}
		($(this.target + "_count")||{}).innerHTML = count;
	}

});

comunibase.data.album = Object.extend(Object.extend({}, comunibase.data),{
	insert: function(form){
		if(!this.isnull(form.title, "画像タイトル")) return false;
		if(!this.isnull(form.image, "画像ファイル")) return false;
		return true;
	}
});

comunibase.data.bookmark = Object.extend(Object.extend({}, comunibase.data),{
	insert: function(form){
		if(!this.isnull(form.title, "タイトル")) return false;
		if(form.target[0].checked){
			if(!this.isnull(form.url, "URL")) return false;
		}else{
			if(!this.isnull(form.tag, "HTMLタグ")) return false;
			
			var html = form.tag.value;
			if(html.match(new RegExp("(<script|<frame|<iframe)","im"))){
				alert("script,frame,iframeタグは使用できません");
				return false;
			}
			
		}
		return true;
	}
});

comunibase.data.review = Object.extend(Object.extend({}, comunibase.data),{
	insert: function(form){
		if(!this.isnull(form.title, "レビュータイトル")) return false;
		if(!this.isnull(form.detail, "レビュー内容")) return false;
		return true;
	
	}
});

/**
* 投票パーツ
*
*
**/
comunibase.data.vote = Object.extend(Object.extend({}, comunibase.data),{
	insert: function(form){
		return confirm("投票してよろしいですか？");
	}
});

comunibase.data.table = Object.extend(Object.extend({}, comunibase.data),{
	modify: function(form){
		iserror=false;
		Form.getElements(form).each((function(element){
			if(iserror) return;
			if(element.className == "mustNumeric"){
				if(!this.isnum(element,element.title)){
					iserror = true;
				}
			}
		}).bind(this));

		if(iserror){
			return false;
		}
		
		return true;
	
	}
});



comunibase.user = Object.extend(Object.extend({}, comunibase),{});

comunibase.user.regist = Object.extend(Object.extend({}, comunibase.user),{
	check: function(form){
		if(!this.isnull(form.mail,"メールアドレス")) return false;
		if(!this.isnull(form.user_name,"ニックネーム")) return false;
		
		if(form.user_name.value.toLowerCase() == "comunibase" || form.user_name.value.match(new RegExp("(こ|コ|ｺ)(み|ミ|ﾐ)(ゅ|ュ|ｭ)(に|ニ|ﾆ)(べ|ベ|ﾍﾞ)(ー|-|―|－|‐|～)?(す|ス|ｽ)"))){
			alert("入力されたニックネームはご使用になれません。");
			return false;
		}
		
		if(!this.isnull(form.pwd,"パスワード")) return false;
		if(!this.isnull(form.confirmation,"パスワード(確認用)")) return false;
		if(!this.issame(form.pwd.value, form.confirmation.value)){
			alert("パスワードとパスワード(確認用)には同じ文字を指定してください");
			return false;
		}
		
	},
	
	confirmation: function(form){
		if(!this.ischecked(form.permit)){
			alert("利用規約に同意して下さい");
			return false;
		}
	
	}
});

comunibase.user.config = Object.extend(Object.extend({}, comunibase.user),{

	mail: function(form){
		if(!this.isnull(form.mail,"新しいメールアドレス")) return false;
		if(!this.isnull(form.confirmation,"新しいメールアドレス(確認)")) return false;
	
		if(!this.issame(form.mail.value, form.confirmation.value)){
			alert("メールアドレスとメールアドレス(確認用)には同じ文字を指定してください");
			return false;
		}
		return true;
	},

	password: function(form){
		if(!this.isnull(form.current,"現在のパスワード")) return false;
		if(!this.isnull(form.pwd,"新しいパスワード")) return false;
		if(!this.isnull(form.confirmation,"新しいパスワード(確認)")) return false;

		if(!this.issame(form.pwd.value, form.confirmation.value)){
			alert("パスワードとパスワード(確認用)には同じ文字を指定してください");
			return false;
		}
		return true;
	},
	
	form: function(element, self){
	
		if(element.style.display==''){
			element.style.display = 'none';
			
			self.innerHTML = '[変更する]';
		}else{
			element.style.display = ''
			self.innerHTML = '[閉じる]';
		}
	}
});

comunibase.user.favorite = Object.extend(Object.extend({}, comunibase.db),{
	addDB: function(dbid, userid){
		if(confirm("このデータベースをお気に入りに追加します。\nよろしいですか？")){
			this.ajax("next=userfavoritedb&action=add&dbid="+dbid+"&uid="+userid, this.onExecuted.bind(this));
		}
	},

	addData: function(dbid, dataid, userid){
		if(confirm("このデータをお気に入りに追加します。\nよろしいですか？")){
			this.ajax("next=userfavoritedata&action=add&dbid="+dbid+"&dataid="+dataid+"&uid="+userid, this.onExecuted.bind(this));
		}
	},
	
	onExecuted: function(context){
		eval("res = "+context.responseText);
		if(res.msg) alert(res.msg);
	},
	
	changeDBVisible: function(dbid, userid, visible, image){
		this.ajax("next=userfavoritedb&action=visibility&dbid="+dbid+"&uid="+userid+"&visibility="+visible, this.onExecuted.bind(this));
	},
	
	changeDataVisible: function(dataid, userid, visible, image){
		this.ajax("next=userfavoritedb&action=visibility&dataid="+dataid+"&uid="+userid+"&visibility="+visible, this.onExecuted.bind(this));
	}
});

comunibase.user.pal = Object.extend(Object.extend({}, comunibase.user),{
});

comunibase.user.msg = Object.extend(Object.extend({}, comunibase.user),{
	send: function(form){
	
		if(!this.isnull(form.title,"件名")) return false;
		if(!this.isnull(form.body,"内容")) return false;
	
		return confirm("メッセージを送信します。よろしいですか？");
	
	},
	
	remove: function(form){
		return confirm("選択されたメッセージを削除します。よろしいですか？");
	
	}
});

comunibase.config = Object.extend(Object.extend({}, comunibase),{
	checkContact: function(form){
		if(!this.isnull(form.contact_name,"お名前")) return false;
		if(!this.isnull(form.contact_mail,"連絡先メールアドレス")) return false;
		if(!this.isnull(form.contact_value,"詳細内容")) return false;
//		if(!this.isnull(form.contact_url,"該当ページURL")) return false;
		return true;
	
	},
	checkAdvertisement: function(form){
		if(!this.isnull(form.ad_company,"会社名")) return false;
		if(!this.isnull(form.ad_address,"会社所在地")) return false;
		if(!this.isnull(form.ad_tel,"会社連絡先")) return false;
		if(!this.isnull(form.ad_name,"ご担当者名")) return false;
		if(!this.isnull(form.ad_mail,"メールアドレス")) return false;
		if(!this.isnull(form.ad_url,"会社URL")) return false;
		if(!this.isnull(form.ad_value,"問い合わせ内容")) return false;
//		if(!this.isnull(form.contact_url,"該当ページURL")) return false;
		return true;
	
	}	
});

