/**
 * @brief jf_Board
 * Require : jQuery
 */
var jf_Board = {
	board_url_pattern:/\/board\/([^/?]*)[/]*([^?]*)/,

	/*** Attributes ***/
	DI_file : null,
	auth : {},

	passForm_modal : null,
	passForm_after_fn : null,


	/********************************************/
	/*** get URL data ***/
	/********************************************/
	get_base_url : function()
	{
		return location.href.match(/(\/admin|\/pims|)\/board\//)[0];
	},
	get_board : function()
	{
		return location.href.match(/\/board\/([^/]*)/)[1];
	},
	get_act : function()
	{
		return location.href.match(/\/board\/[^/]*\/([^/?]*)/)[1];
	},
	get_document_id : function()
	{
		var tmp	 = location.href.match(/\/board\/[^/]*\/([^/?]*\/)?([0-9]+)/);
		return (tmp==null)?"":tmp[2];
	},
	get_pims_id : function()
	{
		var tmp = location.href.match(/pims_id=([^&]*)/);
		return (tmp==null)?"":tmp[1];
	},



	/********************************************/
	/*** get URL ***/
	/********************************************/
	get_docsFirstList_URL : function()
	{
		if(this.auth.docsList==0)	return '/';

		var url = location.href.replace(/[&?](s_[^=]+|start|page)=[^&]*/g, "");	// remove Search information
		return url.replace(jf_Board.board_url_pattern, "/board/$1");
	},
	get_docsList_URL : function()
	{
		if(this.auth.docsList==0)	return '/';

		return location.href.replace(jf_Board.board_url_pattern, "/board/$1");
	},
	get_docView_URL : function(document_id)
	{
		if(this.auth.docView==0)	return this.get_docsFirstList_URL();

		return location.href.replace(jf_Board.board_url_pattern, "/board/$1/"+document_id);
	},
	get_docWrite_URL : function()
	{
		if(this.auth.docWrite==0)	return this.get_docsFirstList_URL();

		return location.href.replace(jf_Board.board_url_pattern, '/board/$1/docWrite');
	},
	get_docUpate_URL : function(document_id)
	{
		if(this.auth.docUpdate==0)	return this.get_docView_URL(document_id);

		if ( document_id!=null )
			return location.href.replace(jf_Board.board_url_pattern, "/board/$1/docUpdate/"+document_id);
		else
			return location.href.replace(jf_Board.board_url_pattern, "/board/$1/docUpdate/$2");
	},
	get_docReply_URL : function(document_id)
	{
		if(this.auth.docReply==0)	return this.get_docView_URL(document_id);

		if ( document_id!=null )
			return location.href.replace(jf_Board.board_url_pattern, "/board/$1/docReply/"+document_id);
		else
			return location.href.replace(jf_Board.board_url_pattern, "/board/$1/docReply/$2");
	},



	/********************************************/
	/*** go_URL ***/
	/********************************************/
	go_docsFirstList : function()
	{
		location.href = this.get_docsFirstList_URL();
	},
	go_docsList : function()
	{
		location.href = this.get_docsList_URL();
	},
	go_docWrite : function()
	{
		location.href = this.get_docWrite_URL();
	},
	go_docReply	: function(document_id)
	{
		location.href = this.get_docReply_URL(document_id);
	},
	go_docUpdate : function(document_id)
	{
		location.href = this.get_docUpate_URL(document_id);
	},
	go_docView	: function(document_id)
	{
		location.href = this.get_docView_URL(document_id);
	},


	/********************************************/
	/*** after ***/
	/********************************************/
	afterdocWrite : function(document_id)
	{
		this.go_docsFirstList();
	},
	afterdocReply : function(document_id)
	{
		this.go_docsFirstList();
	},
	afterdocUpdate : function(document_id)
	{
		this.go_docsList();
	},
	afterdocDelete : function(document_id)
	{
		this.go_docsList();
	},

	aftercmtWrite : function(comment_id)
	{
		this.relisting_comments();
	},
	aftercmtReply : function(comment_id)
	{
		this.relisting_comments();
	},
	aftercmtUpdate : function(comment_id)
	{
		this.relisting_comments();
	},
	aftercmtDelete : function(comment_id)
	{
		this.relisting_comments();
	},


	/********************************************/
	/*** procedure ***/
	/********************************************/
	proc_docDelete : function(document_id)
	{
		$.ajaxProcedure(location.href.replace(jf_Board.board_url_pattern, "/board/$1/docDeleteProc/"+(document_id==null?this.get_document_id():document_id)));
	},
	proc_docExpire : function(document_id)
	{
		$.ajaxProcedure(location.href.replace(jf_Board.board_url_pattern, "/board/$1/docExpireProc/"+(document_id==null?this.get_document_id():document_id)));
	},
	proc_cmtDelete : function(comment_id)
	{
		$.ajaxProcedure(location.href.replace(jf_Board.board_url_pattern, "/board/$1/cmtDeleteProc/"+this.get_document_id()+"/"+comment_id));
	},



	/********************************************/
	/*** render ***/
	/********************************************/
	_render_docListPrev : function(base_obj){},
	_render_docListAfter : function(base_obj){},
	render_docsList : function(json)
	{
		this.auth = json.auth;

		var base_obj = $("#docsList");

		this._render_docListPrev(base_obj);

		/*** Rendering ***/
		base_obj
			// SearchBox
			.find(".searchBox > form")
				.attachFormListSearch(this.get_docsList_URL())
				.end()

		/*** Buttons ***/
			.find(".board_btn_go_docsFirstList").click(function(){jf_Board.go_docsFirstList();}).end()
			.find(".board_btn_docWrite")
				.click(json.takingdocWrite=="Y" ? function(){$.ajaxProcedure('/boardExt/'+jf_Board.get_board()+'/docWrite');} : function(){jf_Board.go_docWrite();})
				.css("display", this.auth.docWrite==0?"none":"")
				.end()
		;

		this._render_docListAfter(base_obj);
	},
	_render_docViewAfter : function(base_obj){},
	render_docView : function(json)
	{
		this.auth = json.auth;

		var board = this.get_board();
		var document_id = this.get_document_id();

		var base_obj = $("#docView");

		/*** Buttons ***/
		if(this.auth.docUpdate == 0)
		{
			base_obj.find("button.board_btn_docUpdate").css("display", "none").end()
					.find("button.board_btn_docDelete").css("display", "none").end();
		}
		else if(this.auth.docUpdate == 1)
		{
			base_obj.find("button.board_btn_docUpdate").click(function(){jf_Board.on_openPassForm(function(){jf_Board.go_docUpdate();});}).end()
					.find("button.board_btn_docDelete").click(function(){jf_Board.on_openPassForm(function(){jf_Board.on_docDelete();});}).end();
		}
		else
		{
			base_obj.find("button.board_btn_docUpdate").click(function(){jf_Board.go_docUpdate();}).end()
					.find("button.board_btn_docDelete").click(function(){jf_Board.on_docDelete();}).end();
		}

		base_obj
			.find("button.board_btn_go_docsList").click(function(){jf_Board.go_docsList();}).css("display", this.auth.docsList==0?"none":"").end()
			.find("button.board_btn_docReply").click(function(){jf_Board.go_docReply();}).css("display", this.auth.docReply==0?"none":"").end()
			.find("button.board_btn_docExpire").click(function(){jf_Board.on_docExpire();}).css("display", this.auth.docExpire==0?"none":"").end()
			.find("button.board_btn_docPrint").click(function(){
						var hide_obj = $("#header,#footer,#snb,#aside,#floating,#locationbar,#docsList");
						hide_obj.hide();
						window.print();
						hide_obj.show();
					}).end()
			;

		/*** comment List ***/
		$("#cmtsList")
			.find("input.regdate").attr("readonly", "readonly").end()

			.find(".data[cmtUpdateAuth=0] .del_btn").css("display", "none").end()
			.find(".data[cmtUpdateAuth=1] .del_btn").click(function(){jf_Board.on_openPassForm($(this).parents("[data_id]").attr("data_id"));}).end()
			.find(".data[cmtUpdateAuth=2] .del_btn").click(function(){jf_Board.on_cmtDelete($(this).parents("[data_id]").attr("data_id"));}).end()
			.end()
		;
		/*** comment Write Form ***/
		var cmtWriteForm_obj = $("#cmtWrite form");
		switch(this.auth.cmtWrite)
		{
			case 0:
				cmtWriteForm_obj.hide();
				break;

			case 1:
				cmtWriteForm_obj
					.submit(function(){return false;})
					.find("textarea[name='content']")
						.attr("readonly", "readonly")
					;
				break

			case 2:
				cmtWriteForm_obj
					.attr("name", "jf_cmt_write_form")
					.attachFormAJAX(this.get_base_url()+board+"/cmtWriteProc/"+document_id)
					.find("textarea[name='content']").val("").end()
					;
				break;
		}

		/*** callback docViewAfter ***/
		this._render_docViewAfter(base_obj);


		$(document.body).ready(function(){
			/*** resize Images ***/
			var base_obj = $(".smartOutput");
			var width = base_obj.width();

			base_obj.find("img").each(function(){
				var this_obj = $(this);
				var image_width = this_obj.width();
				var image_height = this_obj.height();
				if(image_width>width)
				{
					var new_width	= width;
					var new_height	= Math.floor(width*image_height/image_width);
					this_obj
						.width(new_width).height(new_height)
						.attr("image_width", image_width).attr("image_height", image_height)
						.click(function(){
							var this_obj = $(this);
							var popup_width	= Number(this_obj.attr("image_width"));
							var popup_height= Number(this_obj.attr("image_height"));
							var new_win = window.open("about:blank", "_blank", "width="+popup_width+",height="+popup_height+",status=yes,menubar=no,resizable=no;scrollbars=no,location=no");
							new_win.document.write('<body style="margin:0"><img src="'+this_obj.attr("src")+'" onclick="window.close();" />');
						})
						;
				}
			});
		});
	},
	_render_docWriteAfter : function(base_obj){},
	_render_docWrite : function(json)
	{
		this.auth = json.auth;

		var board = this.get_board();
		var act	 = this.get_act();
		var document_id = this.get_document_id();

		var base_obj = $("#docWrite");

		/*** Create Board Write Form ***/
		base_obj.find("form")
			/* set name */
			.attr("name", "jf_doc_write_form")
			/* set content_type */
			.submit(function(){
				if(base_obj.find("textarea[name='content']").css("display") == "none")
					base_obj.find("input[name='content_type']").val("HTML");
			})
			/* FormAJAX */
			.attachFormAJAX(this.get_base_url()+board+"/"+act+"Proc/"+document_id)
			/* Create Hidden */
			.append($('<input type="hidden" name="content_type" />'))
			.append($('<input type="hidden" name="pims_id" value="'+this.get_pims_id()+'" />'))
			/* Reset Button */
			.find(".reset").click(function(){jf_Board.go_docsList();}).end()
			;

		if(act == "docUpdate")
		{
			/* FillForm */
			base_obj.find("form").autoFillForm(json.row);
		}

		/*** Buttons ***/
		base_obj
			.find(".board_btn_docDelete").click(function(){jf_Board.on_docDelete();}).css("display", this.auth.docUpdate==0?"none":"").end()
			.find(".board_btn_go_docsList").click(function(){jf_Board.go_docsList();}).css("display", this.auth.docsList==0?"none":"").end()
		;

		/*** Attach File ***/
		if(json.config.file_limit>0)
			this.render_upfile(json);
		else
			base_obj.find("div.attach").remove();

		/*** keep Session ***/
		keep_session();

		/*** callback docWriteAfter ***/
		this._render_docWriteAfter(base_obj);
	},
	render_docWrite : function(json)
	{
		this._render_docWrite(json);
	},
	render_docUpdate : function(json)
	{
		this._render_docWrite(json);
	},
	render_docReply : function(json)
	{
		this._render_docWrite(json);
	},
	render_upfile : function(json)
	{
		if((typeof jf_dynamicItem) == "undefined")
			return;

		var base_obj = $("#docWrite");

		// create upload button
		createUploadButton($("#btn_upload").attr("sdir", "files").attr("filefilter", "*.*").get(0));
		// file list
		base_obj
			.find("div.attach ul > li")
				.mouseover(function(){$(this).addClass("on");})
				.mouseout(function(){$(this).removeClass("on");})
				.append($('<input type="hidden" class="filename">'))
				.append($('<input type="hidden" class="regdate">'))
				.append($('<input type="hidden" class="is_new">'))
				.end()
		;

		this.DI_file = new jf_dynamicItem(base_obj.find("ul.files"));
		this.DI_file.setItemSelector("li");
		this.DI_file.setItemFormName("files");
		this.DI_file.setIsEmptyToHide(true);
		this.DI_file.setMinCount(0);
		this.DI_file.init();

		// add prevFiles
		if(json.files != null)
		{
			for(var i=0,loop=json.files.length; i<loop; i++)
			{
				this.onAddFile(json.files[i], 0);
			}
		}
	},
	onAddFile : function(json, is_new)
	{
		var obj = this.DI_file.add();
		var filesize = (isFinite(json.filesize) == true) ? toFileSize(json.filesize) : json.filesize;
		obj
			.find("input.filename").val(json.filename).end()
			.find("input.regdate").val(json.regdate).end()
			.find("input.is_new").val(is_new).end()
			.find("span.source_filename").html(json.source_filename).end()
			.find("span.filesize").html(filesize).end()
			;
	},

	on_openPassForm : function(after_fn)
	{
		if(this.passForm_modal == null)
		{
			this.passForm_modal
				= jQuery('<div class="passForm" style="margin: 15px 0;"><form><input type="password" name="pass" class="pass" /></form></div>')
					.dialog({
						modal: true,
						autoOpen : false,
						bgiframe: true,
						closeOnEscape: false,
						resizable: false,
						width: 300,
						height: 150,
						title: "비밀번호를 입력해주세요",
						buttons: {
								"취소": function(){
									$(this).dialog("close");
								},
								"확인": function(){
									$(this).find("form").submitAJAX();
								}
							}
					});
		}

		this.passForm_modal
			.dialog("open")
			.find("form")
				.attachFormAJAX(this.get_base_url()+this.get_board()+"/getDocAuthProc/"+this.get_document_id())
				.trigger("reset")
				.find("input[name='pass']").focus().end()
				.end();

		this.passForm_after_fn	= after_fn;
	},
	afterPassForm : function(is_ok)
	{
		if(is_ok)
		{
			this.passForm_modal.dialog("close");
			if(this.passForm_after_fn != null)
			{
				this.passForm_after_fn();
				this.passForm_after_fn	= null;
			}

		}
		else
		{
			alert("입력하신 비밀번호가 맞지 않습니다.");
		}
	},

	onInsertFile : function()
	{

	},

	relisting_comments : function()
	{
		location.reload();
	}

};

/*** call by user ***/
jf_Board.on_docDelete = function(document_id)
{
	if ( confirm("삭제하시겠습니까?")==true )
	{
		this.proc_docDelete(document_id);
	}
};
jf_Board.on_docExpire = function(document_id)
{
	if ( confirm("해당 게시물을 만료처리하시겠습니까?")==true )
	{
		this.proc_docExpire(document_id);
	}
};
jf_Board.on_cmtDelete = function(comment_id)
{
	if ( confirm("삭제하시겠습니까?")==true )
	{
		this.proc_cmtDelete(comment_id);
	}
};

/*** call by server ***/
jf_Board.on_noAuthority = function(enable_auth_name)
{
	if(enable_auth_name == null)
		alert("권한이 없습니다.");
	else
		alert(enable_auth_name + "만 이용 가능한 페이지입니다.");

	this.go_docsList();
};
jf_Board.on_write_limit = function(minute, count)
{
	var time_str = "";
	if(60*24*7 <= minute)
	{
		time_str += Math.floor(minute/(60*24*7)) + "주 ";
		minute	%= 60*24*7;
	}
	if(60*24 <= minute)
	{
		time_str += Math.floor(minute/(60*24)) + "일 ";
		minute	%= 60*24;
	}
	if(60 <= minute)
	{
		time_str += Math.floor(minute/(60)) + "시간 ";
		minute	%= 60;
	}
	if(0 < minute)
	{
		time_str += minute + "분";
	}

	alert(time_str + " 이내에 " + count + "건의 글만 등록가능합니다.");

	this.go_docsList();
};

jf_Board.afterdocExpire = function()
{
	alert("만료처리되었습니다.");
};
jf_Board.on_isExpireDoc = function()
{
	alert("만료된 게시물은 열람하실 수 없습니다.");
};
jf_Board.on_cmtLimitCount = function(limit_count)
{
	alert("해당 게시물에 대한 댓글은 "+limit_count+"회까지만 가능합니다");
};


//------------------------------------------------------------------------------------------------
/*** Uploader  ***/
jf_Uploader.afterAllComplete = function()
{
	for(k in jf_Uploader.completeData)
	{
		var row = jf_Uploader.completeData[k];

		switch(row.dir)
		{
			// attach Files
			case 'files':
				row.is_new = 1; // set new file
				jf_Board.onAddFile(row, 1);
				break;

			case 'images':
				// put filename to InputBox
				if(row.target_input_id)
					$("input#"+row.target_input_id).val(row.filename).trigger("change");
				break;

		}
	}
};
