var MY_ID = document.location.pathname.split('/');
var TEAM_URL = MY_ID[1];
var MESSAGES = {};
var TOAST_NOW;
var TOAST_TODAY;
var JSON_USER_DEFINED = "-1";
var JSON_FAIL = "0";
var JSON_SUCCESS = "1";
var JSON_NOT_LOGIN = "2"; 
var JSON_DATA_REQUIRED = "3"; 
var JSON_DEMO_MSG = "4";
var JSON_ALERT_MSG = "5";
var JSON_OBSERVER_MSG = "6";
var TOAST_FORM_ARR = [];

// IE style background-image cache bug
try {document.execCommand('BackgroundImageCache', false, true)} catch(e){} 

//* ---------------------------toast.general--------------------*//
var I18n = {
	t: function(key, options){
		var keys = key.split(".");
		if (typeof(I18N_MESSAGES) != "undefined") {
			var i18n = I18N_MESSAGES; 
			var msg = "";
			for( var i = 0; i < keys.length; i++ ){
				if ( i18n ){
					i18n = i18n[keys[i]];
					msg = i18n || "";
				}
			}
			
			if ( msg != "" && typeof msg == "string" && options ){
				$.each(options, function(key, val){
					msg = msg.replace(new RegExp("{{"+key+"}}", "g"), val);
				});
			}
			
			if ( $.inArray('alert', keys) > -1 ){
				msg = msg.replace(new RegExp("<br />", "ig"), "\n");
			}
			return msg ? msg : key;
		}
	}
};

String.prototype.toHtml = function (){
	return this.replace(new RegExp("<", "g"), "&lt;")
			   .replace(new RegExp(">", "g"), "&gt;")
			   .replace(new RegExp("\"", "g"), "&quot;");
};

String.prototype.toText = function (){
	return this.replace(new RegExp("<br>", "ig"), "\r\n")
			   .replace(new RegExp("&lt;", "ig"), "<")
			   .replace(new RegExp("&gt;", "ig"), ">")
			   .replace(new RegExp("&amp;", "ig"), "&");
};

function array_unique(array) {
	var a = []
	var l = array.length;
	for( var i = 0 ; i < l ; i++ ){
		for( var j = i+1; j < l; j++ ){
			if( array[i] === array[j] )
				j = ++i;
		}
		a.push(array[i]);
	}
	return a;
}

function getLength(value){
	var total_len=0;
	for(i = 0; i<value.length; i++){
		total_len++;
		if(value.charCodeAt(i) > 127) total_len++;
	}
	return total_len;
};

function makeSubstr(value,len){
	var total_len = 0;
	var new_value = '';
	
	for(var i=0;i<value.length; i++){
		total_len++;
		if(value.charCodeAt(i) > 127) total_len++;
	
		if(total_len>len) break;
		else new_value += value.charAt(i);
	}
	return new_value;
};

function toast_clip(text){
	var xIE4Up,xUA=navigator.userAgent.toLowerCase();
	if(navigator.vendor!='KDE' && document.all && xUA.indexOf('msie')!=-1)
		xIE4Up=parseFloat(navigator.appVersion)>=4;
	if(xIE4Up){
		window.clipboardData.setData('Text', text);
		alert(MESSAGES['copy']);
	}
	else
		alert(MESSAGES['copy only IE']);
};

function toast_ajax_error(response, text_status){
	// lost communication to the server(ff:0, ie:12029)
	if(response.status != "0" && response.status != "12029"){
	/*--
	if(response.status == "200"){
		// ~ing 
		var error_layer = $("<div id='toast_ajax_message'></div>");
		error_layer.appendTo("body");
		$("#toast_ajax_message").html(response.responseText);
		$.extend($.blockUI.defaults.overlayCSS,
			{backgroundColor: '#000', opacity: '0.4'});

		$.blockUI($("#toast_ajax_message"),{textAlign:'justify',border:'none'});
	}
	else
	--*/
	if(response.status == "404" ||
		response.status == "500" || 
		response.status == "503") 
		alert(MESSAGES[response.status]);
	else
		alert(response.status + "::" + text_status);
	}
};

function toast_error_handle(result){
	if(result.status == JSON_NOT_LOGIN) 
		toast_login_handle(result);
	else
	if(result.status == JSON_DATA_REQUIRED) 
		alert(MESSAGES["data required"]);
	else if(result.status == JSON_DEMO_MSG)
		toast_demo_handle(result);
	else if(result.status == JSON_ALERT_MSG)
		alert(result.message);
	else if(result.status == JSON_OBSERVER_MSG)
		toast_observer_handle(result);	
	else
		alert("[ERROR:"+result.status + "] ajax fail");
};

var notice_select;
var last_notice_line = 0;
var curr_notice_line = 0;
var NOTICE_DIV=null;

var notice_html = "/view" + (I18n.t("locale") == "ko" ? "" : "/"+I18n.t("locale")) + "/notice.html"
function toast_scroll_notice() {
	if(NOTICE_DIV!=null&&NOTICE_DIV.size()>0){
		var className=NOTICE_DIV.attr("class");
		NOTICE_DIV.load(notice_html, function(){
			toast_scroll_up("."+className, "div."+className+">p");
		});
	}else{
		$("#page_notice").load(notice_html, function(){
			toast_scroll_up("#page_notice", "div#page_notice>p");
		});
	}
};

function toast_scroll_up(elem, selector){
	notice_select = selector;
	headline_count = $(selector).size();
	
//	$(notice_select).css({'top':'215px','height':'20px','left':'5px'});
//	$(notice_select + ":eq("+curr_notice_line+")").css({'top':'5px','height':'20px'});
//	$(notice_select).css({'top':'5px','height':'20px','left':'5px','display':'none'});
	
	$(notice_select).css({'top':'5px','left':'5px','display':'none'});
	$(notice_select + ":eq("+curr_notice_line+")").css({'display':'block'});
	
	if(headline_count > 1){
		headline_interval = setInterval(toast_rotate,3000);  
		$(elem).hover(function(){
			clearInterval(headline_interval);
		}, function(){
			headline_interval = setInterval(toast_rotate,3000); 
		});
	}
};

function toast_rotate(){
	curr_notice_line = (last_notice_line + 1) % headline_count;
	/*--
	$(notice_select+":eq(" + last_notice_line + ")").animate(
		{top: -205},2500, function(){$(this).css('top','210px');}
	);
	$(notice_select+":eq(" + curr_notice_line + ")").animate({top: 5},"slow");
	--*/
//  $(notice_select+":eq(" + last_notice_line + ")").css({'top':'210px'});
//	$(notice_select+":eq(" + curr_notice_line + ")").css({top: 5});
	$(notice_select+":eq(" + last_notice_line + ")").css({'display':'none'});
	$(notice_select+":eq(" + curr_notice_line + ")").css({'display': 'block'});
	last_notice_line = curr_notice_line;
};

function toast_observer_check(){
	var memtype = $('meta[name="memtype"]').attr("content");
	if(memtype=="T" || memtype=="O"){
		toast_observer_handle();
		return true;
	}
	return false;
};

function toast_observer_handle(data){
	$.toast.pop_layer.add_layer( 
		{layer_observer: {type: 'poptype_z', block: true,
		pop_top_l: '<p class="alert">'+I18n.t("layer.observer_handle.alert")+'</p>',
		pop_content: '<div class="message"><p>'+I18n.t("layer.observer_handle.message")+'</p></div><p class="add_comment">'+I18n.t("layer.observer_handle.comment")+'</p>', 
		pop_bottom_r: '<a class="pop_ok">'+I18n.t("layer.confirm")+'</a>'}} );
	if(data && data.use) $("#layer_observer").find("p.add_comment").html(data.html);
	$.toast.pop_layer.show("layer_observer", {"left": 500, "top": 200});
};

//* ---------------------------toast.demo by zooniar --------------------*//

function toast_demo_handle(result){
	if(result.message == 'DEMO') {
		if (typeof result.html !== 'undefined' && result.html !== null) alert(result.html) ;
	}
	else {
		var login_elem = $(result.html);
		login_elem.appendTo("body");
		
		$.extend($.blockUI.defaults.overlayCSS,
		{backgroundColor: '#000', opacity: '0.4'});
		
		$.blockUI({
			message: $("#demo_alert"),
			css: {
				textAlign: 'justify',
				border: 'none'
			}
		});
	}
};

//* ---------------------------toast.login --------------------*//
function toast_login_handle(result){
/*
	var login_elem = $(result.html);
	login_elem.appendTo("body");

	$("#login_pop").find("input[toast]").toastValidate(
		{label_id:'#login_err_msg', callback:toast_login_error});

 	$.extend($.blockUI.defaults.overlayCSS,
		{backgroundColor: '#000', opacity: '0.4'});

	$.blockUI($("#login_pop"), {textAlign:'justify',border:'none'});
	if($("#login_pop #email").val())
		$("#login_pop #password").focus();
	else
		$("#login_pop #email").focus();
*/
	var url = '/'+TEAM_URL+'/team/loginform?rtnurl='+location.pathname;
	if( ( typeof result.rs ) !== 'undefined' && result.rs !== null )
		url += '&rs='+result.rs;
	document.location.href = url;
};

function toast_login_error(){
	$("#login_pop .login_error").show();
};

function toast_login_cancel(){
	$.unblockUI();
};

function toast_demo_cancel(){
	close_layer('demo_alert');
//	if(jQuery.browser.msie){
//		$(".blockUI").remove();
//	}else {
//		$.unblockUI();
//	}
};

function toast_login(){
	var toast_form = "login_form";
	if(!toast_validate_form(toast_form,
		{label_id:'#login_err_msg', callback:toast_login_error})) return;

	 var queryString = $("#"+toast_form).serialize();
	 $.ajax( {
	 	type: "POST",
		url: "/main/user/login", 
		dataType: "json",
		data: queryString,
		success: function(data){
			if(data.status == JSON_SUCCESS) $.unblockUI();
			else {
				$(".login_error>.message").html(data.message);
				$(".login_error").show();
			}
		},
		error : function(res, e){
			toast_ajax_error(res, "[mini login]:"+e);
		},
		complete : function(res, e){
			toast_validate_form_return(toast_form);
		}
	});
	return false ;
};

function toast_help(){
	var url = "";
	if (I18n.t("locale") == "ko"){
		url = "/main/user/help";
	}else{
		url = "/"+I18n.t("locale")+ "/main/user/help";
	}
	//window.open('/view/help/help_main.html',
	//window.open('/main/user/help', 
	window.open(url,
		'toast_help', 
		'location=no,menubar=no,status=no,titlebar=no,width=920,height=800,scrollbars=yes');
};

function toast_print(){
	var url = '/'+TEAM_URL+'/print/'+MY_ID[2]+'/'+MY_ID[3];
	if(MY_ID[4]) url += '/'+MY_ID[4];
	if(document.location.search) url += document.location.search;
	window.open(url, 'toast_print', 'scrollbars=yes,location=no,menubar=no,status=no,titlebar=no,width=820,height=665');
};

function toast_sms(id){
	if(id && id.indexOf("phone=") >= 0)
	window.open('/toast_msg/sms?teamurl='+TEAM_URL+(id?"&"+id:""), 
		'toast_messenger', 
		'location=no,menubar=no,status=no,titlebar=no,width=484,height=403');
	else
	window.open('/toast_msg/sms?teamurl='+TEAM_URL+(id?"&memid="+id:""), 
		'toast_messenger', 
		'location=no,menubar=no,status=no,titlebar=no,width=484,height=403');
};

function toast_memo(id){
	window.open('/toast_msg/memo?teamurl='+TEAM_URL+(id?"&memid="+id:""), 
	'toast_messenger', 
	'location=no,menubar=no,status=no,titlebar=no,width=484,height=403');
};

function toast_msg_box(id){
	window.open('/toast_msg/msg_box?teamurl='+TEAM_URL+(id?"&memid="+id:""), 
	'toast_messenger', 
	'location=no,menubar=no,status=no,titlebar=no,width=484,height=403');
};

function toast_pm_box(){
	var $personal_memo = $('div.personal_memo:first');
	if( $personal_memo.length ){
		$personal_memo.parent().parent().slideToggle();
//		reset_pm_height();
	}
};
//* ---------------------------toast.calendar --------------------*//

jQuery.fn.calendar = function(today){
	// day,month,year from today 
	var memorial_days = Array(
		new toast_day(1,1,1),
		new toast_day(3,1,1),
		new toast_day(5,5,1),
		new toast_day(6,6,1),
		new toast_day(8,15,1),
		new toast_day(10,3,1),
		new toast_day(12,25,1),
		new toast_day(12,0,2),
		new toast_day(1,1,2),
		new toast_day(1,2,2),
		new toast_day(4,8,2),
		new toast_day(8,14,2),
		new toast_day(8,15,2),
		new toast_day(8,16,2)
	);
	
	var lunarMonthTable = [
		[2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1],
		[2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1],
		[2, 2, 1, 5, 2, 1, 1, 2, 1, 2, 1, 2],   /* 2001 */
		[2, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1],
		[2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2],
		[1, 5, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2],
		[1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1],
		[2, 1, 2, 1, 2, 1, 5, 2, 2, 1, 2, 2],
		[1, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2],
		[2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2],
		[2, 2, 1, 1, 5, 1, 2, 1, 2, 1, 2, 2],
		[2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2],
		[2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1],   /* 2011 */
		[2, 1, 2, 5, 2, 2, 1, 1, 2, 1, 2, 1],
		[2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2],
		[1, 2, 1, 2, 1, 2, 1, 2, 5, 2, 1, 2],
		[1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1],
		[2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2],
		[1, 2, 1, 2, 1, 4, 1, 2, 1, 2, 2, 2],
		[1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2],
		[2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2],
		[2, 1, 2, 5, 2, 1, 1, 2, 1, 2, 1, 2]];
	
	var day = 0;
	$(this).each(function(){
		day = today.substr(6,2);
		var month = today.substr(4,2);
		var year = today.substr(0,4);
		
		var cal_id  = $(this).attr("id");
		$(this).append(makeCalendarDom(cal_id))
				.find("tbody").html(makeCalendar(cal_id, month, year));
		
		$(this).find("#s_cal_select").prepend(makeCalSelect(month, year));
		
		$(this).parent().find(".next").click(function(){
			if(month==12){
				month=1; year++;
			} else 
				month++;
				
			cal_div = $(this).parent().parent();
			$(cal_div).find("tbody")
				.html(makeCalendar($(cal_div).attr("id"), month, year));
		});
		$(this).parent().find(".pre").click(function(){
			if(month==1){
				month=12; year--;
			}
			else{
				month--;
			}
			
			cal_div = $(this).parent().parent();
			$(cal_div).find("tbody")
				.html(makeCalendar($(cal_div).attr("id"), month, year));
			
			$(cal_div).find("table").attr("date", year + "/"+month);
		});
		
		$(this).parent().find(".close").click(function(){
			$(this).parent().parent().hide("slow");
		});
		
		$(this).parent().find("select").click(function(){
			year = parseInt($(".year option:selected").text(), 10);
			month = parseInt($(".month option:selected").text(), 10);
		
			cal_div = $(this).parent().parent();
			$(cal_div).find("tbody")
				.html(makeCalendar($(cal_div).attr("id"), month, year)); 
		});
		$(this).parent().find("#toast_cal_go").click(function(){
			month = TOAST_TODAY.substr(4,2);
			year = TOAST_TODAY.substr(0,4);
		
			cal_div = $(this).parent().parent();
			$(cal_div).find("tbody")
			.html(makeCalendar($(cal_div).attr("id"), month, year));
			
			var today_year = year; 
			var today_month = String(parseInt(month), 10);
			$(cal_div).find("#s_cal_select select.month").selectOptions(today_month, true);
			$(cal_div).find("#s_cal_select select.year").selectOptions(today_year, true);
		});
		
		$(this).find("#s_cal_table a").click(function(){
			alert($(this).text());
			$(this).parents("table").attr("toast_date", year+"/"+month +"/"+ $(this).text());
		});
	});
	
	function makeCalendarDom(id_name){
		var dom_node = "";
		if(id_name == "side_calendar")
		dom_node = 
			"<div id='s_cal_info'>\
				<p id='s_cal_year'></p>\
				<p id='s_cal_month'></p>\
				<a class='pre'>\
				<a class='next'></a>\
			</div>\
			<table id='s_cal_table'>\
				<thead><tr><th class='sun'>"+MESSAGES["sun"]+"</th><th>"+MESSAGES["mon"]+"</th><th>"+MESSAGES["tue"]+"</th><th>"+MESSAGES["wed"]+"</th><th>"+MESSAGES["thu"]+"</th><th>"+MESSAGES["fri"]+"</th><th class='sat'>"+MESSAGES["sat"]+"</th></tr>\
				</thead>\
				<tbody></tbody>\
			</table>\
			<div id='s_cal_select'><a href='javascript:void(0)' id='toast_cal_go'></a></div>";
		else
		if(id_name == "cal_mini") 
			dom_node = 
			"<div id='cal_mini_top'>\
				<a class='pre'>"+MESSAGES["pre month"]+"</a>\
				<p></p>\
				<a class='next'>"+MESSAGES["next month"]+"</a>\
				<a class='today'>"+MESSAGES["today"]+"</a>\
				<a class='close'>"+MESSAGES["close"]+"</a>\
			</div>\
			<div id='cal_mini_body'>\
				<table id='s_cal_table'>\
				<thead><tr><th class='sun'>"+MESSAGES["sun"]+"</th><th>"+MESSAGES["mon"]+"</th><th>"+MESSAGES["tue"]+"</th><th>"+MESSAGES["wed"]+"</th><th>"+MESSAGES["thu"]+"</th><th>"+MESSAGES["fri"]+"</th><th class='sat'>"+MESSAGES["sat"]+"</th></tr></thead>\
				<tbody></tbody>\
				</table>\
			</div>";
		return dom_node; 
	}

	function toast_day(month, day, type){
		this.month = month;
		this.day = day;
		this.type = type;
	}

	function getHolidays(year, month, day){
		var lunar = getLunarDay(year, month, day);
		for(var i = 0; i < memorial_days.length; i++)  {
			if(memorial_days[i].type == 1 &&
				memorial_days[i].month == month &&
				memorial_days[i].day == day) return true;
			if(memorial_days[i].type == 2 &&
				memorial_days[i].month == lunar.month &&
				memorial_days[i].day == lunar.day) return true;
		}
	}

	function makeCalendar(cal_id, month, year){
		var mm = parseInt(month, 10);
		var yy = parseInt(year, 10);
		
		var i = 0;
		var days = getDaysInMonth(mm,yy);
		var dd = days < day ? 1 : day;
		var firstOfMonth = new Date (yy, mm-1, 1);
		var startPos = firstOfMonth.getDay();
		days += startPos;
		
		if(lunarMonthTable[year - 1 - 1999][11] == 1)
			memorial_days[7].day = 29;
		else if(lunarMonthTable[year - 1 - 1999][11] == 2)
			memorial_days[7].day = 30;
		
		var dom_node = "<tr>";
		for(i = 0; i < startPos; i++) dom_node += "<td></td>";
		
		cal_class = "";
		for(i = startPos; i < days; i++){
			if(i%7 == 0){
				dom_node += "</tr>";
				if(i < days-1) dom_node += "<tr>"; 
			}
			if((i-startPos+1) == dd) cal_class = "today";
			else if(i%7 == 0) cal_class = "sun"; 
			else if(i%7 == 6) cal_class = "sat";
			else cal_class = "";
			
			if(getHolidays(yy, mm, (i-startPos+1))) cal_class += " holiday";
			
			if(cal_id == "cal_mini")
			dom_node += "<td class='"+cal_class+"'><a>"+parseInt(i-startPos+1, 10)+"</a></td>"; 
			else
			dom_node += "<td class='"+cal_class+"'>"+parseInt(i-startPos+1, 10)+"</td>"; 
		}
		
		for(i=days; i<days+7; i++){
			if(i%7 == 0){	
				dom_node += "</tr>"; break;
			}
			dom_node += "<td></td>";
		}
	
		if(cal_id == "side_calendar"){
			$("#s_cal_year").html(yy);
			$("#s_cal_month").html(mm);
		}
		else 
		if(cal_id == "cal_mini")
			$("#"+cal_id).find("p").html(yy+" <strong>"+mm+"</strong>");
		
		return dom_node;
	}

	function makeCalSelect(month,year){
		month = parseInt(month, 10);
		year = parseInt(year, 10);
		
		var dom_node = "<select class='year'>";
		for(i = year - 5; i <= year + 5 ; i++)
			dom_node += "<option value='"+i+"' "+ (i==year?" selected>":">")+i+MESSAGES["year"]+"</option>";
		dom_node += "</select>";
		
		dom_node += "<select class='month'>";
		for(i=1;i<=12;i++)
			dom_node += "<option value='"+i+"' "+ (i==month?" selected>":">")+i+MESSAGES["month"]+"</option>";
		dom_node += "</select>";
		
		return dom_node;
	}

	function getDaysInMonth(month,year)  {
		var days = 0;
		if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12)  days=31;
		else if(month==4 || month==6 || month==9 || month==11) days=30;
		else if(month==2){
			if(isLeapYear(year)) days=29; 
			else days=28;
		}
		return days;
	}

	function isLeapYear (Year){
		if(((Year % 4)==0) && ((Year % 100)!=0) || ((Year % 400)==0)) 
			return (true);
		else 
			return (false); 
	}

	function getLunarDay(year, month, day)
	{
		var solYear, solMonth, solDay;
		var lunYear, lunMonth, lunDay;
		var lunLeapMonth, lunMonthDay; 
		var i, lunIndex;

		var solMonthDay = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

		if(year >= 2000){
			solYear = 2000; solMonth = 1; solDay = 1;
			lunYear = 1999; lunMonth = 11; lunDay = 25; lunLeapMonth = 0;

			solMonthDay[1] = 29; lunMonthDay = 30; 
		}
		lunIndex = lunYear - 1999;

		while (true){
			if(year == solYear && month == solMonth && day == solDay)
				return new toast_day(lunMonth, lunDay, 2);

			if(solMonth == 12 && solDay == 31){
				solYear++;
				solMonth = 1;
				solDay = 1;

				if(solYear % 400 == 0) solMonthDay[1] = 29;
				else if(solYear % 100 == 0) solMonthDay[1] = 28;
				else if(solYear % 4 == 0) solMonthDay[1] = 29;
				else solMonthDay[1] = 28;
			}
			else if(solMonthDay[solMonth - 1] == solDay){
				solMonth++; solDay = 1; 
			}
			else
				solDay++;

			if(lunMonth == 12 &&
				((lunarMonthTable[lunIndex][lunMonth - 1]==1 && lunDay ==29) ||
				(lunarMonthTable[lunIndex][lunMonth - 1]==2 && lunDay == 30))){
				lunYear++; lunMonth = 1; lunDay = 1;

				lunIndex = lunYear - 1999;

			if(lunarMonthTable[lunIndex][lunMonth - 1] == 1)
				lunMonthDay = 29;
			else if(lunarMonthTable[lunIndex][lunMonth - 1] == 2)
				lunMonthDay = 30;
			}
			else if(lunDay == lunMonthDay){
				if(lunarMonthTable[lunIndex][lunMonth - 1] >= 3 && 
					lunLeapMonth == 0){
					lunDay = 1;
					lunLeapMonth = 1;
				}
				else {
					lunMonth++;
					lunDay = 1;
					lunLeapMonth = 0;
				}

				if(lunarMonthTable[lunIndex][lunMonth - 1] == 1)
					lunMonthDay = 29;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 2)
					lunMonthDay = 30;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 3)
					lunMonthDay = 29;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 4 && 
					lunLeapMonth == 0)
					lunMonthDay = 29;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 4 &&
					 lunLeapMonth == 1)
					lunMonthDay = 30;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 5 &&
				 	lunLeapMonth == 0)
					lunMonthDay = 30;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 5 &&
				 	lunLeapMonth == 1)
				 	lunMonthDay = 29;
				else if(lunarMonthTable[lunIndex][lunMonth - 1] == 6)
					lunMonthDay = 30;
			}
			else lunDay++;
		}
	}
};

//* ---------------------------blockUI plugin v 2.23 --------------------*//
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(E($){5(/1\\.(0|1|2)\\.(0|1|2)/.1d($.W.13)||/^1.1/.1d($.W.13)){2z(\'D 2A 1r 2B.2.3 2C 2D!  2E 2F 2G v\'+$.W.13);L}$.W.1W=$.W.X;7 v=F.2H||0;7 w=$.R.14&&(($.R.1X<8&&!v)||v<8);7 A=$.R.14&&/2I 6.0/.1d(1Y.2J)&&!v;$.D=E(a){1I(Y,a)};$.1Z=E(a){1s(Y,a)};$.21=E(a,b,c,d){7 e=$(\'<J 15="21"></J>\');5(a)e.1J(\'<1t>\'+a+\'</1t>\');5(b)e.1J(\'<22>\'+b+\'</22>\');5(c==1u)c=2K;$.D({1e:e,X:2L,S:24,1f:1g,Z:c,16:1g,1v:d,G:$.D.17.25})};$.W.2M=E(a){L H.1K({S:0}).1w(E(){5($.G(H,\'K\')==\'2N\')H.I.K=\'2O\';5($.R.14)H.I.2P=1;1I(H,a)})};$.W.1K=E(a){L H.1w(E(){1s(H,a)})};$.D.1X=2.23;$.D.17={1e:\'<1t>2Q 2R...</1t>\',G:{1x:0,1L:0,18:\'30%\',M:\'2S%\',19:\'35%\',2T:\'1M\',26:\'#1N\',1a:\'2U 2V #2W\',1O:\'#27\',1P:\'28\'},1h:{1O:\'#1N\',1Q:0.6,1P:\'28\'},25:{18:\'2X\',M:\'1y\',19:\'\',2Y:\'1y\',1a:\'T\',1x:\'2Z\',1Q:0.6,1P:1i,26:\'#27\',1O:\'#1N\',\'-31-1a-29\':\'1y\',\'-32-1a-29\':\'1y\'},2a:/^33/i.1d(Y.34.36||\'\')?\'37:1g\':\'38:39\',1z:1g,2b:24,2c:N,1f:N,2d:N,2e:N,2f:N,X:3a,S:3b,Z:0,16:N,2g:N,2h:N,1v:1i,2i:4};7 B=1i;7 C=[];E 1I(c,d){7 e=(c==Y);7 f=d&&d.1e!==1u?d.1e:1u;d=$.1A({},$.D.17,d||{});d.1h=$.1A({},$.D.17.1h,d.1h||{});7 g=$.1A({},$.D.17.G,d.G||{});f=f===1u?d.1e:f;5(e&&B)1s(Y,{S:0});5(f&&2j f!=\'3c\'&&(f.11||f.13)){7 h=f.13?f[0]:f;7 j={};$(c).12(\'D.1R\',j);j.O=h;j.1j=h.11;j.P=h.I.P;j.K=h.I.K;5(j.1j)j.1j.2k(h)}7 z=d.2b;7 k=($.R.14||d.1z)?$(\'<2l 15="D" I="z-1B:\'+(z++)+\';P:T;1a:T;1L:0;1x:0;K:1C;18:1k%;1l:1k%;M:0;19:0" 3d="\'+d.2a+\'"></2l>\'):$(\'<J 15="D" I="P:T"></J>\');7 m=$(\'<J 15="D 3e" I="z-1B:\'+(z++)+\';P:T;1a:T;1L:0;1x:0;18:1k%;1l:1k%;M:0;19:0"></J>\');7 n=e?$(\'<J 15="D 1S 3f" I="z-1B:\'+z+\';P:T;K:2m"></J>\'):$(\'<J 15="D 1S 3g" I="z-1B:\'+z+\';P:T;K:1C"></J>\');5(f)n.G(g);5(!d.2h||!($.R.3h&&/3i/.1d(1Y.3j)))m.G(d.1h);m.G(\'K\',e?\'2m\':\'1C\');5($.R.14||d.1z)k.G(\'1Q\',0.0);$([k[0],m[0],n[0]]).3k(e?\'Q\':c);7 p=w&&(!$.1m||$(\'3l,3m\',e?1i:c).1n>0);5(A||p){5(e&&d.2d&&$.1m)$(\'3n,Q\').G(\'1l\',\'1k%\');5((A||!$.1m)&&!e){7 t=1o(c,\'2n\'),l=1o(c,\'2o\');7 q=t?\'(0 - \'+t+\')\':0;7 r=l?\'(0 - \'+l+\')\':0}$.1w([k,m,n],E(i,o){7 s=o[0].I;s.K=\'1C\';5(i<2){e?s.U(\'1l\',\'3o.3p(F.Q.3q, F.Q.1p) - (1r.1m?0:\'+d.2i+\') + "V"\'):s.U(\'1l\',\'H.11.1p + "V"\');e?s.U(\'18\',\'1r.1m && F.1b.2p || F.Q.2p + "V"\'):s.U(\'18\',\'H.11.1T + "V"\');5(r)s.U(\'19\',r);5(q)s.U(\'M\',q)}1q 5(d.1f){5(e)s.U(\'M\',\'(F.1b.2q || F.Q.2q) / 2 - (H.1p / 2) -3r + (3s = F.1b.1c ? F.1b.1c : F.Q.1c) + "V"\')}1q 5(!d.1f&&e){7 a=(d.G&&d.G.M)?2r(d.G.M):0;7 b=\'((F.1b.1c ? F.1b.1c : F.Q.1c) + \'+a+\') + "V"\';s.U(\'M\',b)}})}5(f){n.1J(f);5(f.13||f.3t)$(f).1D()}5(($.R.14||d.1z)&&d.16)k.1D();5(d.X){5(d.16)m.1W(d.X);5(f)n.X(d.X)}1q{5(d.16)m.1D();5(f)n.1D()}1E(1,c,d);5(e){B=n[0];C=$(\':3u:3v:3w\',B);5(d.2g)1F(1G,20)}1q 1M(n[0],d.2c,d.1f);5(d.Z){7 u=1F(E(){e?$.1Z(d):$(c).1K(d)},d.Z);$(c).12(\'D.Z\',u)}};E 1s(a,b){7 c=a==Y;7 d=$(a);7 e=d.12(\'D.1R\');7 f=d.12(\'D.Z\');5(f){3x(f);d.2s(\'D.Z\')}b=$.1A({},$.D.17,b||{});1E(0,a,b);7 g=c?$(\'Q\').2t().2u(\'.D\'):$(\'.D\',a);5(c)B=C=1i;5(b.S){g.S(b.S);1F(E(){1U(g,e,b,a)},b.S)}1q 1U(g,e,b,a)};E 1U(a,b,c,d){a.1w(E(i,o){5(H.11)H.11.2k(H)});5(b&&b.O){b.O.I.P=b.P;b.O.I.K=b.K;5(b.1j)b.1j.3y(b.O);$(b.O).2s(\'D.1R\')}5(2j c.1v==\'E\')c.1v(d,c)};E 1E(b,a,c){7 d=a==Y,$O=$(a);5(!b&&(d&&!B||!d&&!$O.12(\'D.2v\')))L;5(!d)$O.12(\'D.2v\',b);5(!c.2e||(b&&!c.16))L;7 e=\'3z 3A 3B 3C\';b?$(F).1E(e,c,1V):$(F).3D(e,1V)};E 1V(e){5(e.2w&&e.2w==9){5(B&&e.12.2f){7 a=C;7 b=!e.2x&&e.1H==a[a.1n-1];7 c=e.2x&&e.1H==a[0];5(b||c){1F(E(){1G(c)},10);L 1g}}}5($(e.1H).2y(\'J.1S\').1n>0)L N;L $(e.1H).2y().2t().2u(\'J.D\').1n==0};E 1G(a){5(!C)L;7 e=C[a===N?C.1n-1:0];5(e)e.1G()};E 1M(a,x,y){7 p=a.11,s=a.I;7 l=((p.1T-a.1T)/2)-1o(p,\'2o\');7 t=((p.1p-a.1p)/2)-1o(p,\'2n\');5(x)s.19=l>0?(l+\'V\'):\'0\';5(y)s.M=t>0?(t+\'V\'):\'0\'};E 1o(a,p){L 2r($.G(a,p))||0}})(1r);',62,226,'|||||if||var||||||||||||||||||||||||||||||||blockUI|function|document|css|this|style|div|position|return|top|true|el|display|body|browser|fadeOut|none|setExpression|px|fn|fadeIn|window|timeout||parentNode|data|jquery|msie|class|showOverlay|defaults|width|left|border|documentElement|scrollTop|test|message|centerY|false|overlayCSS|null|parent|100|height|boxModel|length|sz|offsetHeight|else|jQuery|remove|h1|undefined|onUnblock|each|padding|10px|forceIframe|extend|index|absolute|show|bind|setTimeout|focus|target|install|append|unblock|margin|center|000|backgroundColor|cursor|opacity|history|blockMsg|offsetWidth|reset|handler|_fadeIn|version|navigator|unblockUI||growlUI|h2||1000|growlCSS|color|fff|default|radius|iframeSrc|baseZ|centerX|allowBodyStretch|bindEvents|constrainTabKey|focusInput|applyPlatformOpacityRules|quirksmodeOffsetHack|typeof|removeChild|iframe|fixed|borderTopWidth|borderLeftWidth|clientWidth|clientHeight|parseInt|removeData|children|filter|isBlocked|keyCode|shiftKey|parents|alert|requires|v1|or|later|You|are|using|documentMode|MSIE|userAgent|3000|700|block|static|relative|zoom|Please|wait|40|textAlign|3px|solid|aaa|350px|right|5px||webkit|moz|https|location||href|javascript|about|blank|200|400|string|src|blockOverlay|blockPage|blockElement|mozilla|Linux|platform|appendTo|object|embed|html|Math|max|scrollHeight|110|blah|nodeType|input|enabled|visible|clearTimeout|appendChild|mousedown|mouseup|keydown|keypress|unbind'.split('|'),0,{}))

//* ---------------------------ajaxfileupload --------------------*//
jQuery.extend({
	createUploadIframe: function(id, uri)
	{
		//create frame
		var frameId = 'jUploadFrame' + id;
			
		if(window.ActiveXObject){
			var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
		   	if(typeof uri== 'boolean'){
				io.src = 'javascript:false';
			}
			else if(typeof uri== 'string'){
				io.src = uri;
			}
		}
		else {
			var io = document.createElement('iframe');
			io.id = frameId;
			io.name = frameId;
		}
		io.style.position = 'absolute';
		io.style.top = '-1000px';
		io.style.left = '-1000px';

		document.body.appendChild(io);

		return io;
	},
	createUploadForm: function(id, fileElementId, addElementIds)
	{
		//create form
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var $form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
		var $oldElement = $('#' + fileElementId);
		var $newElement = $oldElement.clone();
		$oldElement.attr('id', fileId);
		$oldElement.before($newElement);
		$oldElement.appendTo($form);
		
		if( typeof addElementIds != 'undefined' ){
			for( var i = 0; i < addElementIds.length; i++ ){
				var addElementId = addElementIds[i];
				var $orgElement = $('#'+addElementId);
				var $addElement = $orgElement.clone();
				
				$orgElement.attr('id', 'jUploadAdd'+id);
				$addElement.attr('name', $orgElement.attr('name'));
				$orgElement.before($addElement);
				$orgElement.appendTo($form);
			}
		}
		
//		if(typeof addElementIds != undefined){
//			for( var i = 0 ; i < addElementIds.length; i++ ) {
//				var addElementId = addElementIds[i];
//				var orgElement = $('#'+ addElementId);
//				var addElement = $(orgElement).clone();
//				$(orgElement).attr('id', 'jUploadAdd'+id);
//				$(addElement).attr('name', $(orgElement).attr('name'));
//				$(orgElement).before(addElement);
//				$(orgElement).appendTo(form);
//			}
//		}
		//set attributes
		$form.css({
			'position': 'absolute', 
			'top': '-1200px', 
			'left': '-1200px'
		});
//		$(form).css('position', 'absolute');
//		$(form).css('top', '-1200px');
//		$(form).css('left', '-1200px');
//		$(form).appendTo('body');
		$form.appendTo('body');
		return $form;
	},

	ajaxFileUpload: function(s){
		// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		

		s = jQuery.extend({}, jQuery.ajaxSettings, s);
		var id = new Date().getTime();
		var form = jQuery.createUploadForm(id, s.fileElementId, s.addElementIds);
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		

		// Watch for a new set of requests
		if( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}			
		var requestDone = false;
		// Create the request object
		var xml = {};
		if( s.global )
			jQuery.event.trigger("ajaxSend", [xml, s]);
		// Wait for a response to come back
		var uploadCallback = function(isTimeout)
		{
			var io = document.getElementById(frameId);
			try 
			{
				if(io.contentWindow)
				{
					xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
					xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
				}
				else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
					xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}
			}catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
			if( xml || isTimeout == "timeout") 
			{
				requestDone = true;
				var status;
				try {
					status = isTimeout != "timeout" ? "success" : "error";
					// Make sure that the request was successful or notmodified
					if( status != "error" )
					{
						// process the data (runs the xml through httpData regardless of callback)
						var data = jQuery.uploadHttpData( xml, s.dataType );	
						// If a local callback was specified, fire it and pass it the data
						if( s.success )
							s.success( data, status );
							
						// Fire the global callback
						if( s.global )
							jQuery.event.trigger( "ajaxSuccess", [xml, s] );
					}
					else
						jQuery.handleError(s, xml, status);
				}
				catch(e) 
				{
					status = "error";
					jQuery.handleError(s, xml, status, e);
				}
				// The request was completed
				if( s.global )
					jQuery.event.trigger( "ajaxComplete", [xml, s] );
				// Handle the global AJAX counter
				if( s.global && ! --jQuery.active )
					jQuery.event.trigger( "ajaxStop" );
				// Process result
				if( s.complete )
					s.complete(xml, status);
				jQuery(io).unbind()
				setTimeout(function(){
					try 
					{
						$(io).remove();
						$(form).remove();
					} catch(e){
						jQuery.handleError(s, xml, null, e);
					}
				}, 100)
				xml = null;
			}
		}
		// Timeout checker
		if( s.timeout > 0 ) 
		{
			setTimeout(function(){
				// Check to see if the request is still happening
				if( !requestDone ) uploadCallback( "timeout" );
			}, s.timeout);
		}
		try 
		{
			// var io = $('#' + frameId);
			var form = $('#' + formId);
			$(form).attr('action', s.url);
			$(form).attr('method', 'POST');
			$(form).attr('target', frameId);
			if(form.encoding)
			{
				form.encoding = 'multipart/form-data';
			}
			else
			{
				form.enctype = 'multipart/form-data';
			}
			$(form).submit();
		} catch(e) 
		{
			jQuery.handleError(s, xml, null, e);
		}
		if(window.attachEvent){
			document.getElementById(frameId).attachEvent('onload', uploadCallback);
		}
		else{
			document.getElementById(frameId).addEventListener('load', uploadCallback, false);
		}
		return {abort: function (){}};
	},
	uploadHttpData: function( r, type ){
		var data = !type;
		data = type == "xml" || data ? r.responseXML : r.responseText;
		// If the type is "script", eval it in global context
		if( type == "script" )
			jQuery.globalEval( data );
		// Get the JavaScript object, if JSON is used.
		if( type == "json" )
			eval( "data = " + data );
		// evaluate scripts within html
		if( type == "html" )
			jQuery("<div>").html(data).evalScripts();
			//alert($('param', data).each(function(){alert($(this).attr('value'));}));
		return data;
	}
});

//* ------------------------- toast.attach ------------------------*//
var ATTACH_IDX = 0;
function submit_attach(id, type, options){
	var id_name = "#toast_attach"+id;
	var file_element = "toast_file"+id;
	var add_element  = "camp_team_url"+id; 

	if(typeof type == "function"){
		options = type;
		type = undefined;
	}
	else
	if(type){
		id_name += "_" + type; 
		file_element += "_" + type;
		add_element  += "_" + type; 
	}
	
	if($("#"+add_element).val() == "") $("#"+add_element).val(TEAM_URL);
	
	var attach_thumb = "";
	if($(id_name).find("input[name='toast_attach_thumb']").val() != undefined)		attach_thumb = $(id_name).find("input[name='toast_attach_thumb']").val();
	if(attach_thumb.toUpperCase() == "Y"){
		var fname = $(id_name).find("input[name='toast_file']").val();
		if(fname.match(new RegExp(".(png|jpe?g|gif|bmp)$", "i")) == null){
			alert(MESSAGES["thumb file"]);
			return;
		}
	}
	
	var loading_elem = "<img id='toast_loading' src='/images/transfer.gif' border='0' align='absmiddle' />";
	$(id_name+">label").after(loading_elem);
	$(id_name+">label").toggle();
	
	// by gy7uj 
	var add_elements = [add_element];
	if ( $('#upload_cate_id').length ) {
		add_elements.push('upload_cate_id');
	}
	
	$.ajaxFileUpload
	(
		{
			url  : "/user/toast_upload",
			secureuri:false,
			fileElementId: file_element,
			addElementIds: add_elements,
			dataType: "json",
			success: function (data)
			{
				if(data.status == JSON_SUCCESS){
					if(data.name == 'unknown' && parseInt(data.size,10) == 0){
						// 아무 처리 안 해줌
						$(id_name+">label").next("img#toast_loading").remove();
					}else{
						if(typeof options == "function")
							options(id, type, data);
						else
							view_attach_file(id, type, data);
					}
				}
				else {
					$(id_name+">label").next("img#toast_loading").remove();
					$(id_name+">label").show();
					if(data.status == JSON_USER_DEFINED){
						if(data.msg_cd && data.msg_cd=="UT04"){
							$.toast.pop_layer.set_layers({ 
								"layer_bill_upload": { 
									type: 'poptype_z',
									pop_top_l: '<p class="alert">'+I18n.t("layer.bill_upload.alert")+'</p>',
									pop_bottom_r: '<a class="pop_add_space" href="/'+TEAM_URL+'/team/membershipinfo" target="_bill">'+I18n.t("layer.bill_upload.addition")+'</a><a class="pop_ok">'+I18n.t("layer.confirm")+'</a>',
									pop_content: '<div class="message">' +
													'<p class="normal_comment">'+I18n.t("layer.bill_upload.comment.normal", { "usable": data.usable_size, "max": data.max_size })+'</p>' +
													'<p class="secial_commnet">'+I18n.t("layer.bill_upload.comment.special", { "start": data.sdt, "end": data.edt })+'</p>' +
												'</div>'}
							});
							$.toast.pop_layer.show("layer_bill_upload", {left:'20%', top:'50%'});
						}
						else{
							alert(data.message);
						}
					}
					else {
						toast_error_handle(data);
					}
				}
			},
			error: function (data, e)
			{
				$(id_name+">label").next("img#toast_loading").remove();
				$(id_name+">label").show();
				alert(MESSAGES["upload error"]);
			}
		}
	)
	return false;
};

function view_attach_file(id, type, data){
	
	var id_name = "#toast_attach"+id;
	if(type) 
		id_name += "_" + type; 

	var attach_form = $(id_name).find("input[name='toast_attach_form']").val();
	if(attach_form == undefined || attach_form.length==0) 
		attach_form = id_name;	
	else attach_form = "#" + attach_form;

	var attach_count = 0;
	if($(id_name).find("input[name='toast_attach_count']").val())
		attach_count = parseInt($(id_name).find("input[name='toast_attach_count']").val(), 10);

	ATTACH_IDX++;

	var ext_name = data.name.match(new RegExp(".(ace|alz|asf|doc|fla|gz|html?|hwp|lzh|mdb|mp3|pds|ppt|rar|swf|tar|xls|zip|z|png|jpe?g|gif|bmp|txt|docx|pptx|xlsx|gul|pdf|vsd)$", "i"));

	if(ext_name == null) ext_name = "unknown";
	else ext_name = ext_name[1].toLowerCase();

	var file_list = "<div class='file'>"+
		"<img border='0' align='absmidde' src='/images/file/ext_"+ext_name+".gif' /> " +
		data.name+"("+data.size+") "+
		"<a href=javascript:attach_delete("+ATTACH_IDX+")>"+
		"<img src='/images/cmt_btn01.gif' align='absmiddle' border='0' alt='"+MESSAGES["delete"]+"'></a></div>";

	$(id_name+">label").next("img#toast_loading").remove();
	$(id_name+">label").before(file_list).toggle();
	if(attach_count > 0 && attach_count <= ATTACH_IDX)
		$(id_name+">label").hide();

	var attach_elem = "<input type='hidden' "+ 
	 	"id='toast_hidden_file"+ATTACH_IDX+"' name='attachfile["+ATTACH_IDX+"]";

	$(attach_form).append(attach_elem+"[file_path]' value='"+data.path+ "'/>");
	$(attach_form).append(attach_elem+"[file_name]' value='"+data.name+ "'/>");
	$(attach_form).append(attach_elem+"[file_size]' value='"+data.size+ "'/>");
	
};

function attach_delete(f_idx){
	var file_index = "a[href*=attach_delete("+f_idx+")]";
	var loc = $("div.filewrap").find("a").filter(file_index);
	if(loc.length > 0){
		loc.parents("div").children("label.cabinet:hidden").show();

		loc.parent().remove();
		$("input[type='hidden']").filter("#toast_hidden_file"+f_idx).remove();
	}
};

function uploadfile_delete(file_id, id, type){
	var id_name = "#toast_attach"+id;
	if(type) 
		id_name += "_" + type; 

	var attach_form = $(id_name).find("input[name='toast_attach_form']").val();
	if(attach_form == undefined || attach_form.length==0) 
		attach_form = id_name;	
	else attach_form = "#" + attach_form;

	var file_index = "a[href*=uploadfile_delete("+file_id+"]";
	var loc = $("div.filewrap").find("a").filter(file_index);
	if(loc.length > 0){
		loc.parents("div").children("label.cabinet:hidden").show();
		loc.parent().remove();

		$(attach_form).append("<input type='hidden' id='toast_delete_file"+file_id+"' name='deletefile["+file_id+"]'  value="+file_id+" />");
	}
};

function uploadfile_delete_for_edit(file_id, id, type){
	var id_name = "#toast_attach"+id;
	if(type) 
		id_name += "_" + type; 

	var attach_form = $(id_name).find("input[name='toast_attach_form']").val();
	if(attach_form == undefined || attach_form.length==0) 
		attach_form = id_name;	
	else attach_form = "#" + attach_form;

	var file_index = "a[href*=uploadfile_delete_for_edit("+file_id+"]";
	var loc = $("div.file_update").find("a").filter(file_index);
	if(loc.length > 0){
		loc.parent().hide();
		loc.parent().remove();

		$(attach_form).append("<input type='hidden' id='toast_delete_file"+file_id+"' name='deletefile["+file_id+"]'  value="+file_id+" />");
	}
};

/* ---------------------------- extend  --------------------------------- */
lunarMonthTable = [
	[2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1],
	[2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1],
	[2, 2, 1, 5, 2, 1, 1, 2, 1, 2, 1, 2],   /* 2001 */
	[2, 2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1],
	[2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2],
	[1, 5, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2],
	[1, 2, 1, 2, 1, 2, 2, 1, 2, 1, 2, 1],
	[2, 1, 2, 1, 2, 1, 5, 2, 2, 1, 2, 2],
	[1, 1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2],
	[2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2],
	[2, 2, 1, 1, 5, 1, 2, 1, 2, 1, 2, 2],
	[2, 1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2],
	[2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 1],   /* 2011 */
	[2, 1, 2, 5, 2, 2, 1, 1, 2, 1, 2, 1],
	[2, 1, 2, 2, 1, 2, 1, 2, 1, 2, 1, 2],
	[1, 2, 1, 2, 1, 2, 1, 2, 5, 2, 1, 2],
	[1, 2, 1, 1, 2, 1, 2, 2, 2, 1, 2, 1],
	[2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2],
	[1, 2, 1, 2, 1, 4, 1, 2, 1, 2, 2, 2],
	[1, 2, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2],
	[2, 1, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2],
	[2, 1, 2, 5, 2, 1, 1, 2, 1, 2, 1, 2]];

// for korea
memorialDayTable = {
	solar_0101: "신정", 
	solar_0301: "삼일절", 
	solar_0501: "근로자의날",
	solar_0505: "어린이날",
	solar_0606: "현충일",
	solar_0815: "광복절",
	solar_1003: "개천절",
	solar_1225: "성탄절",
	lunar_1230: "", lunar_0101: "설날", lunar_0102: "",
	lunar_0408: "석가탄신일",
	lunar_0814: "", lunar_0815: "추석", lunar_0816: ""
}
	
holidayTable = {
	solar_0405: "식목일", 
	solar_0508: "어버이날", 
	solar_0515: "스승의날", 
	solar_0717: "제헌절", 
	solar_1009: "한글날", 
	lunar_0115: "정월대보름"
}

$.extend(Date.prototype, {
	today: TOAST_NOW,

	clone: function(){
		return new Date( this.getTime() );
	},	
	
	is_today: function(){
		return this.equal_yy_mm_dd(TOAST_NOW);
	},
	is_memorial: function(){
		return this.memorial_name()!=undefined;
	},
	is_holiday: function(){
		return this.holiday_name()!=undefined;
	},

	beginning_of_month: function(){
		this.setDate(1);
		return this;
	},
	end_of_month: function(){
		//this.setDate
	},
	week_kor: function() {
		if ( TOAST_NOW.beginning_of_week()<=this && this <= TOAST_NOW.end_of_week()) {
			return "이번주";
		} else if (this < TOAST_NOW.beginning_of_week()) {
			return "지난주";
		} else if ( TOAST_NOW.end_of_week()<this ) {
			return I18n.t("time.next week", {"hday":""});
		}
	},
	day_kor: function(){
		if (this.equal_yy_mm_dd(TOAST_NOW)) {
			return I18n.t("time.today"); 
		} else if (this.equal_yy_mm_dd(TOAST_NOW.prev_day(1))) {
			return "어제";
		} else if (this.equal_yy_mm_dd(TOAST_NOW.prev_day(2))) {
			return "그저께";
		} else if (this.equal_yy_mm_dd(TOAST_NOW.next_day(1))) {
			return I18n.t("time.tomorrow"); 
		} else if (this.equal_yy_mm_dd(TOAST_NOW.next_day(2))) {
			return I18n.t("time.day after tomorrow"); 
		} else {			
			return this.wday_kor();
		}	
	},
	date_kor: function(){
		if( this.equal_yy_mm_dd(TOAST_NOW) || this.equal_yy_mm_dd(TOAST_NOW.next_day(1))){
			return this.day_kor();
		}
		else{
			return (( TOAST_NOW.beginning_of_week() <= this && this <= TOAST_NOW.end_of_week() ) ? "" : this.week_kor()) + " " + this.wday_kor('0');
		}
	}, 
	wday: function(){
		return this.getDay();
	},
	wday_kor: function(c){
		var s = "";
		if ( c==undefined )
			s = I18n.t("date.day_names")[this.getDay()];
		else
		if ( c=='0' )
			s = I18n.t("date.abbr_day_names")[this.getDay()];
		return s;
	},
	yday: function(){
		var _date = this;
		var value = 0;
		for( var i = 0 ; i < _date.getMonth(); i++ ) {
			var temp = new Date(_date.getFullYear(), i+1, 1).prev_day();
			value += temp.getDate();
		}
		value += _date.getDate();
		
		return value;
	}, 
	yweek: function(){
		var _date = this.clone();
		_date.setDate(_date.getDate()-((0 == _date.getDay()) ? 7 : _date.getDay())+1);
		var yday = _date.yday();
		return parseInt((yday/7), 10)+((0<yday%7) ? 1 : 0);
	}, 
	beginning_of_week_by_wday: function(wday){
		var d = this.clone().beginning_of_week();
		d.setDate(d.getDate()+wday-1);
		return d;
	},
	date_by_wday_and_times: function(times, wday){	//X째주 일요일
		var d = new Date(this.getFullYear(), this.getMonth(), 1);
		var begin_date = d.beginning_of_week_by_wday(wday);
		if (begin_date.getMonth()!=d.getMonth()) begin_date = begin_date.next_week();
		begin_date.setDate( begin_date.getDate()+((times-1)*7) );		//매월 X째주 일요일
		return begin_date;
	},
	/*-----------
	wday_to_date: function(wday){
		var d = this.clone().beginning_of_week();
		d.setDate(d.getDate()+wday-1);
		return d;
	},
	wday_times_to_date: function(times, wday){
		var d = new Date(this.getFullYear(), this.getMonth(), 1);
		var begin_date = d.wday_to_date(wday);
		if (begin_date.getMonth()!=d.getMonth()) begin_date = begin_date.next_week();
		begin_date.setDate( begin_date.getDate()+((times-1)*7) );		//매월 X째주 일요일
		return begin_date;
	},
	-------------------*/
	prev_month: function(){	
		var d = this.clone();
		d.setMonth( d.getMonth()-1 );
		return d;
	}, 
	next_month: function(){
		var d = this.clone().beginning_of_month();
		d.setMonth( d.getMonth()+1 );
		return d;
	},
	beginning_of_week: function(){
		var d = this.clone();
		d.setDate(d.getDate()-d.wday()+1);
		return d;
	},
	end_of_week: function(){
		var d = this.clone();
		d.setDate( d.getDate()+(7-d.wday()) );
		return d;
	},
	prev_week: function(){
		this.setDate(this.getDate()-7);
		return this;
	},
	next_week: function(){		
		this.setDate(this.getDate()+7);
		return this;
	},
	prev_day: function(i){
		if (i==0) return this;
		var d = this.clone();
		d.setDate( d.getDate()-(i||1) );
		return d;
	},
	next_day: function(i){
		if (i==0) return this;
		var d = this.clone();
		d.setDate( d.getDate()+(i||1) );
		return d;
	},
	since_day: function(i){
		if (i==0) return this;
		var d = this.clone();
		d.setDate( d.getDate()+(i||1) );
		return d;
	},
	getStrMonth: function(){	
		return (this.getMonth()+1).append_zero_str();
	},
	getStrDate: function(){	
		return this.getDate().append_zero_str();
	},
	getStrHours: function(){
		return this.getHours().append_zero_str();
	},
	getStrMinutes: function(){
		return this.getMinutes().append_zero_str();
	},
	getStrSeconds: function(){
		return this.getSeconds().append_zero_str();
	},
	hh_mm: function(){
		return this.getStrHours()+this.getStrMinutes();
	},
	hh_mm_ss: function(){
		return this.getStrHours()+this.getStrMinutes()+this.getStrSeconds();
	},
	hms1: function(){
		return this.getStrHours()+I18n.t("date.prompts.hour")+" "+this.getStrMinutes()+I18n.t("date.prompts.minute")+" "+this.getStrSeconds()+I18n.t("date.prompts.sec");
	},
	hh_mm_ss_colon: function(){
		return this.getStrHours()+":"+this.getStrMinutes()+":"+this.getStrSeconds();
	},
	mm_dd: function(){
		return this.getStrMonth()+this.getStrDate();
	},
	yy_mm: function(){
		return this.getFullYear()+this.getStrMonth();
	},
	yy_mm_dd: function(){
		return this.getFullYear()+this.mm_dd();
	},
	yy_mm_dd_kor: function(){
		return this.getFullYear()+I18n.t("date.prompts.year")+" "+(this.getMonth()+1).toString().append_zero()+I18n.t("date.prompts.month")+" "+this.getDate().toString().append_zero()+I18n.t("date.prompts.day");
	},
	yy_mm_dd_slash: function(){
		return this.getFullYear()+"/"+(this.getMonth()+1)+"/"+this.getDate();
	},
	yy_mm_dd_dot: function(){
		return this.getFullYear()+"."+this.getStrMonth()+"."+this.getStrDate();
	},
	yy_mm_dd_dash: function(){
		return this.getFullYear() + "-" + this.getStrMonth().toString().append_zero() + "-" + this.getStrDate().toString().append_zero();
	}, 
	mm_dd_slash: function(){
		return (this.getMonth()+1).toString().append_zero() +"/"+this.getDate().toString().append_zero();
	},
	hh_mm_colon: function(){
		return this.getHours() + ":" + this.getStrMinutes();
	}, 
	am_pm: function(c){
		var s = this.getHours()<12 ? 'am' : 'pm';
		if (c!='e') s = {'am': I18n.t("time.am"), 'pm': I18n.t("time.pm")}[s];
		return s;
	},
	am_pm_kor: function(){
		var h = this.getHours();
		var m = this.getStrMinutes() > 0 ? this.getStrMinutes()+ I18n.t("time.min") : "";
		if ( this.getHours()==0 ) h = 12;
		else if( this.getHours() > 12 ) h = this.getHours()-12;		
		return this.am_pm()+" "+h+I18n.t("time.hour")+" "+m;
	},
	am_pm_colon: function(c){
		return this.am_pm(c)+" " +(this.getHours()>12 ? (this.getHours()-12):this.getHours())+":"+this.getStrMinutes();
	},
	set_hours: function(m){
		this.setHours(m);
		return this;
	},
	set_minutes: function(m){
		this.setMinutes(m);
		return this;
	},
	equal_year: function(s){
		return this.getFullYear()==s.getFullYear();
	},
	equal_month: function(s){
		return this.getMonth()==s.getMonth();
	},
	equal_date: function(s){
		return this.getDate()==s.getDate();
	},
	equal_yy_mm_dd: function(s){
		//this.getFullYear()==d.getFullYear() && ...
		return this.equal_year(s) && this.equal_month(s) && this.equal_date(s)
	},
	diff_day: function(d){
		return this.diff(d);
		//return Math.floor((this.getTime()-d.getTime())/(1000*60*60*24));
	},	
	diff_hour: function(d){
		return this.diff(d, 'h');
	},	
	diff_minute: function(d){
		return this.diff(d, 'm');
	},	
	diff: function(d, c){
		var _time = this.getTime()-d.getTime();
		switch (c) {
			case "m":
				return _time/(1000*60);
			case "h":
				return _time/(1000*60*60);
			default:
				return Math.floor(_time/(1000*60*60*24));
		}	
	},
	solar_key: function(){
		return "solar_"+this.mm_dd();
	},
	lunar_key: function(){
		var lunar = this.get_lunar();
		return "lunar_"+lunar.month.append_zero_str()+lunar.day.append_zero_str();
	},
	lunar_length: function(){
		return lunarMonthTable[this.getFullYear()-1-1999][11];
	},
	memorial_name: function(){
		if (this.lunar_length()==1) {
			memorialDayTable["lunar_1229"] = "";
			memorialDayTable["lunar_1230"] = undefined;
		}
		var lunar_key = this.lunar_key();
		var solar_key = this.solar_key();
		return memorialDayTable[memorialDayTable[lunar_key]==undefined ? solar_key : lunar_key];
	},
	holiday_name: function(){
		var lunar_key = this.lunar_key();
		var solar_key = this.solar_key();
		return holidayTable[holidayTable[lunar_key]==undefined ? solar_key : lunar_key];
	},
	lunar_month: function(){
		return this.get_lunar().month;
	},
	lunar_day: function(){
		return this.get_lunar().day;
	},
	get_lunar: function(){
		var year = this.getFullYear();
		var month = this.getMonth()+1;
		var day = this.getDate();

 		var solYear, solMonth, solDay;
 		var lunYear, lunMonth, lunDay;
 		var lunLeapMonth, lunMonthDay; 
 		var i, lunIndex;

 		var solMonthDay = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

 		if (year >= 2000) {
  			solYear = 2000; solMonth = 1; solDay = 1;
			lunYear = 1999; lunMonth = 11; lunDay = 25; lunLeapMonth = 0;

			solMonthDay[1] = 29; lunMonthDay = 30; 
		}
 		lunIndex = lunYear - 1999;

 		while (true) {
  			if (year == solYear && month == solMonth && day == solDay){
				return {month: lunMonth, day: lunDay};
				//return new toast_day(lunMonth, lunDay, 2);
				}

			if (solMonth == 12 && solDay == 31) {
				solYear++;
				solMonth = 1;
				solDay = 1;

				if (solYear % 400 == 0) solMonthDay[1] = 29;
				else if (solYear % 100 == 0) solMonthDay[1] = 28;
				else if (solYear % 4 == 0) solMonthDay[1] = 29;
				else solMonthDay[1] = 28;
			}
			else if (solMonthDay[solMonth - 1] == solDay) {
				solMonth++; solDay = 1; 
			}
			else
				solDay++;

			if (lunMonth == 12 &&
				((lunarMonthTable[lunIndex][lunMonth - 1]==1 && lunDay ==29) ||
				(lunarMonthTable[lunIndex][lunMonth - 1]==2 && lunDay == 30))) {
				lunYear++; lunMonth = 1; lunDay = 1;

				lunIndex = lunYear - 1999;

			if (lunarMonthTable[lunIndex][lunMonth - 1] == 1)
				lunMonthDay = 29;
			else if (lunarMonthTable[lunIndex][lunMonth - 1] == 2)
				lunMonthDay = 30;
			}
			else if (lunDay == lunMonthDay) {
				if (lunarMonthTable[lunIndex][lunMonth - 1] >= 3 && 
					lunLeapMonth == 0) {
					lunDay = 1;
					lunLeapMonth = 1;
				}
				else {
					lunMonth++;
					lunDay = 1;
					lunLeapMonth = 0;
				}

				if (lunarMonthTable[lunIndex][lunMonth - 1] == 1)
					lunMonthDay = 29;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 2)
					lunMonthDay = 30;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 3)
					lunMonthDay = 29;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 4 && 
					lunLeapMonth == 0)
					lunMonthDay = 29;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 4 &&
					 lunLeapMonth == 1)
					lunMonthDay = 30;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 5 &&
				 	lunLeapMonth == 0)
					lunMonthDay = 30;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 5 &&
				 	lunLeapMonth == 1)
				 	lunMonthDay = 29;
				else if (lunarMonthTable[lunIndex][lunMonth - 1] == 6)
					lunMonthDay = 30;
			}
  			else lunDay++;
 		}
	}	//end of get_lunar
});


$.extend(String.prototype, {
	to_date: function(){
		if (this.length < 8) return false;
		if (this.length==8){
			return new Date(this.substr(0,4).to_i(), 
											this.substr(4,2).to_i()-1, 
											this.substr(6,2).to_i());		
		}
		if (this.length < 12) return false;
		return new Date(this.substr(0,4).to_i(), 
										this.substr(4,2).to_i()-1, 
										this.substr(6,2).to_i(),
										this.substr(8,2).to_i(),
										this.substr(10,2).to_i(), 
										(14 == this.length ) ? this.substr(12, 2).to_i() : 0);
	},
	to_minutes: function(){
		return (this.to_date().getHours()*60) + this.to_date().getMinutes();
	},
	append_zero: function(){
		return this.length==1 ? "0"+this : this;
	},
	strip_zero: function(){
		return this.replace(/^0/, "");
	},	
	yy_mm_dd_slash: function(){
		return this.year()+"/"+this.month()+"/"+this.date();
	},
	year: function(){
		if (this.length < 8) return false;
		return this.substr(0,4);
	},
	month: function(){
		if (this.length < 8) return false;
		return this.substr(4,2);
	},
	date: function(){
		if (this.length < 8) return false;
		return this.substr(6,2);
	},
	mm_dd: function(){
		if (this.length < 8) return false;
		return this.month() + this.date();
	},
	hh_mm: function(){
		if (this.length < 12) return false;
		return this.substr(8,2)+this.substr(10,2);
	},
	hh_mm_colon: function(){
		if (this.length < 12) return false;
		return this.substr(8,2).strip_zero()+":"+this.substr(10,2);
	},
	html_escape: function(){
		return this.replace(/&/g, "&amp;").replace(/\"/g, "&quot;").replace(/>/g, "&gt;").replace(/</g, "&lt;");
	},
	html_unescape: function(){
		if(this==null||this==""){return "";};
	    var temp = document.createElement("div");
	    temp.innerHTML = this;
	    var result = temp.childNodes[0].nodeValue;
    	temp.removeChild(temp.firstChild);
	    return result;
	},
	to_i: function(){
		return parseInt(this, 10);
	},
	truncate: function(len){
		return this.length>len ? this.substr(0,len) : this;
	}
});

$.extend(Number.prototype, {
	append_zero_str: function(){
		return this.toString().append_zero();
	}
});

$.extend(Array.prototype, {
	
});

/* -------------------------- selectOption ------------------------------ */
$.fn.selectOptions = function(value, clear)
{
	var v = value;
	var vT = typeof(value);
	var c = clear || false;
   	// has to be a string or regular expression (object in IE, function in Firefox)
	if(vT != "string" && vT != "function" && vT != "object") return this;
	this.each(
		function()
		{
			if(this.nodeName.toLowerCase() != "select") return this;
			// get options
			var o = this.options;
			// get number of options
			var oL = o.length;
			for(var i = 0; i<oL; i++)
			{
				if(v.constructor == RegExp)
				{
					if(o[i].value.match(v))
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
				else
				{
					if(o[i].value == v)
					{
						o[i].selected = true;
					}
					else if(c)
					{
						o[i].selected = false;
					}
				}
			}
		}
	);
	return this;
};

//* ---------------------------- toastValidate -----------------------------*//

function toast_validate_form_return(obj){
	if(typeof obj == "string")
		obj = document.getElementById(obj);

	var form_idx = $.inArray(obj, TOAST_FORM_ARR);
	if(form_idx != -1) TOAST_FORM_ARR[form_idx] = "";
};

function toast_validate_form(obj, options){
	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);
	if(typeof obj == "string")
		obj = document.getElementById(obj);

	options.form_id = obj;

	for(var i = 0, element; element = obj.elements[i]; i++)
		if(!toast_validate(element, options))
			return false;

	if($(obj).find("img#toast_loading").attr("src") != undefined){
		alert(MESSAGES["uploading file"]);
		return false;
	}

	if($.inArray(obj, TOAST_FORM_ARR) != -1)  {
		alert(MESSAGES["double submit"]);
		return false;
	}
	else {
		TOAST_FORM_ARR[TOAST_FORM_ARR.length] = obj;
		return true;
	}
};

function toast_validate(elem, options){

	var hint = jQuery.trim($(elem).attr("toast_guide"));
	if(hint && hint == $(elem).val()) 
		$(elem).val("");

	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

	var attr = jQuery.trim($(elem).attr("toast"));
	if(attr){

		var arr = "{" + attr + "}";
		eval("arr = " + arr);
		var rules = [];

		jQuery.each(arr, function(elem, val){
			rules[rules.length] = { method:elem, params:val }
		});

		return(toast_blur_validate($(elem), rules, options));
	}
	return true;
}

jQuery.fn.toastValidate = function(options){

	options = jQuery.extend({}, jQuery.fn.toastValidate.defaults, options);

	this.each(function(){
		var elem = $(this);
		var attr = elem.attr("toast");

		if(attr){
			var arr = "{" + attr + "}";
			eval("arr = " + arr);

			var rules = [];
			jQuery.each(arr, function(elem, val){
				rules[rules.length] = { method:elem, params:val }
			});

			elem.keyup(function(){  
				if(!elem.val()) return;
				for(var i = 0; i < rules.length; i++){
					m = rules[i].method; p = rules[i].params;
					switch(m){
					case 'maxLength':
						if(p < getLength(elem.val())){
							/* -- strange 
							elem.val(makeSubstr(elem.val(), p));
							return toast_invalid(elem, MESSAGES["max length"]);
							*/
							toast_invalid(elem, MESSAGES["max length"]);
							elem.val(makeSubstr(elem.val(), p));
						}
						break;
					case 'maxNumber':
						if(p && (!/^\d+$/.test(elem.val()) || elem.val()>p)){	
							elem.val(elem.val().substr(0,elem.val().length-1)); 
							return toast_invalid(elem, I18n.t("invalid.maxNumber", { "number" : p}));
						}
						break;
					case 'minNumber':
						if(p && (!/^\d+$/.test(elem.val()) || elem.val()<p)){
							elem.val(p);
							return toast_invalid(elem, I18n.t("invalid.minNumber", { "number": p }));
						}
						break;
					case 'hour':
						if(p && (!/^\d+$/.test(elem.val()) || elem.val()>23)){
							elem.val(elem.val().substr(0,elem.val().length-1)); 
							return toast_invalid(elem,MESSAGES["hour invalid"]);
						}
						break;
					case 'minute':
						if(p && (!/^\d+$/.test(elem.val()) || elem.val()>59)){
							elem.val(elem.val().substr(0,elem.val().length-1)); 
							return toast_invalid(elem,MESSAGES["minute invalid"]);
						}
						break;
					case 'special':
						if(!p && /[~!@\#$%<>^&*\()\-=+_\']/gi.test(elem.val())){
							elem.val(elem.val().substr(0,elem.val().length-1));
					  		return toast_invalid(elem, MESSAGES["special invalid"], options);
						}
						break;
					case 'ip':
//						if(p && !/^\d+$/.test(elem.val()) ){
						if(p && !/^[0-9.]+$/.test(elem.val())){
							elem.val(elem.val().substr(0, elem.val().length-1));
							return toast_invalid(elem, MESSAGES['number invalid']);
						}
						break;
					}
				}
				//if(options.label_id && $(options.label_id).length)
					//$(options.label_id).html("");
			})
			/*
			elem.blur(function(){  

				if(!elem.val()) return;
				toast_blur_validate(elem, rules, options);
			})
			*/
		}
		//if(elem.attr("toast_guide")) $(this).toastGuide(); 
		$(this).toastGuide(true); 

	});
}

function toast_blur_validate(elem, rules, options){
	for(var i = 0; i < rules.length; i++){
		m = rules[i].method; p = rules[i].params;
		switch(m){
			case 'need': 
				if(options.form_id){
					if(p && getLength(elem.val().replace(/\s+/g,"")) == 0) 
						return toast_invalid(elem,MESSAGES["need"],options);
				}
				break;

			case 'required': 
				if(options.form_id){
/*---- gy7uj insert ----*/
					var stop = false;

					if( typeof(p) == 'string' ){
						
						if( $("#"+p+":checked").length )
							p = true;
						else	{
							p = false;
							if( /radio|checkbox/.test(elem.attr('type')) ) 
								elem.attr('checked', false);
							else
								elem.val('');
						}
					}
					if( /radio|checkbox/.test(elem.attr('type')) && !$('input[name="'+elem.attr('name')+'"]:checked').length )
						stop = true;
					else
					if( /select/.test(elem.attr('tagName')) && elem.val() == '' )
						stop = true;
					else
					if( !/radio|checkbox/.test(elem.attr('type')) && getLength(elem.val().replace(/\s+/g, "")) == 0 )
						stop = true;

					if( p && stop )	
						return toast_invalid(elem,MESSAGES["required"], options);
/*---- gy7uj end ----*/
/*
					if( p && getLength(elem.val().replace(/\s+/g,"")) == 0 ) 
						return toast_invalid(elem,MESSAGES["required"],options);
*/
				}
				break;
/*
			case 'number':
				if(elem.val() != "" && !/[^0-9]+$/.test(elem.val()))
					return toast_invalid(elem, MESSAGES["number invalid"], options);
				break;
*/
			case 'email': 
				if(elem.val() != "" &&
					p && !/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/i.test($.trim(elem.val()))) 
					return toast_invalid(elem, MESSAGES["email invalid"], options);
				break;
			case 'equal':
				if(elem.val() != jQuery(p).val()) 
					return toast_invalid(elem, MESSAGES["equal invalid"], options);
				break;
			case 'alphanum':
				if(elem.val() != "" && p && !/^[A-Za-z0-9]+$/.test(elem.val()))
					return toast_invalid(elem, MESSAGES["alphanum invalid"], options);
				break;
			case 'rangeLength':
				var length = getLength(elem.val());
				if(elem.val() != "" && (length < p[0] || length > p[1])) 
					return toast_invalid(elem, MESSAGES["rangeLength invalid"], options);
				break;
			case 'phonenum':
				if(elem.val() != "" && p && !/^[0-9\-\r\n]*$/.test(elem.val()))
					return toast_invalid(elem, MESSAGES["number invalid"], options);
				break;
			case 'mobilenum':
				if(elem.val() != "" && p){
					var e = elem.val().split("\r\n");
					e = elem.val().split("\n");
					for(var i = 0; i < e.length; i++){
						if(e[i].length > 0 && !/^01[016789][-]?[0-9]{3,4}[-]?[0-9]{4}[\r\n]?$/.test(e[i]))
							return toast_invalid(elem, MESSAGES["mobile invalid"], options);
					}
				}
				break;
/*---- gy7uj insert ----*/
			case 'maxCount':
				if( $('input[name="'+elem.attr('name')+'"]:checked').length > parseInt(p, 10) )
					return toast_invalid(elem, I18n.t("invalid.maxCount", { "count": p }), options);
				break;
/*
			case 'ip':
				if(elem.val() != "" && elem.val().match(/([1]\d\d|[2]([0-4][0-9]|5[0-5])|[1-9][0-9]|[0-9]){1}(\.([1]\d\d|[2]([0-4][0-9]|5[0-5])|[1-9][0-9]|[0-9])){3}/gi) != elem.val() )
					return toast_invalid(elem, MESSAGES['number invalid']);
				break;
*/
/*---- gy7uj insert ----*/
		}
	}

	//if(options.label_id && $(options.label_id).length) 
		//$(options.label_id).html("");

	return true;
}

function toast_invalid(obj, msg, options){
	var message = obj.attr("title")  || msg;
	 
	if( options && options.message ){
		if( typeof options.message == 'string' ){
			message = options.message;
		}
		else
		if( typeof options.message == 'function' ){
			message = options.message(obj);
		}
	}
	if(options && options.label_id && $(options.label_id).length){
		$(options.label_id).html(message);
		if(typeof options.callback == "function") options.callback();
	}
	else alert(message);
/*---- gy7uj insert ----*/
	if( obj.attr('tagName').toLowerCase() == 'div' )
		obj.find('input[type=checkbox], input[type=radio]').eq(0).focus();
	else
		obj.focus();
/*-------------------*/
//	obj.focus();
	return false;
}

jQuery.extend(jQuery.fn.toastValidate, {
	defaults : {
		form_id  : this.form_id,
		label_id : this.lable_id,
		callback : this.callback
	}
});

//* ------------------------- toastGuide  -------------------------------*//

jQuery.fn.toastGuide = function(isValidate){
	return this.each(function(){
		var elem = $(this);
		var hint = elem.attr("toast_guide");

		if(isValidate && hint == undefined) hint = "";
		if(hint || isValidate){
			elem.focus(function(){
				if (hint.length) {
					if (elem.val() == hint) 
						elem.val("").removeClass("guide_text").addClass("input_focus");
					else {
						if(!elem.hasClass("input_focus")) 
							elem.addClass("input_focus");
						if(elem.hasClass("guide_text")) 
							elem.removeClass("guide_text");
					}	
				}
				else  {
					//if (elem.val().length) 
						elem.removeClass("guide_text").addClass("input_focus");
				}
			})
			elem.blur(function(){
				elem.removeClass("input_focus");
				if(elem.val() == "")
					elem.val(hint).addClass("guide_text");
			});
			if(elem.val() == "") 
				elem.val(hint).addClass("guide_text");
		}
	});
}

//* ------------------------- toastTagging  -------------------------------*//
jQuery.fn.toastTagging = function(){
	var tag_elem = "<input type='text' class='text input_focus' toast_tag='true' />"
					+"<img src='/images/btn_save_tag.gif' align='middle' " 
					+ "style='cursor:pointer' toast_tag='true' /> ";
	
	return this.each(function(){

		var elem = $(this);
		var tag = elem.attr("toast_tag");

		if(tag && tag == "true"){
			var child_elem = $(this).children();

			elem.click(function(){
				if(this.tagName == "IMG"){
					submit_update_tag(elem);

					elem.nextAll().show();
					elem.prev().remove();
					elem.remove();
				}
			});

			child_elem.click(function(){

				var tags = $(elem).find("p").text();
				$(elem).children().hide();
				$(elem).find("p").removeClass("empty");


				if(tags == MESSAGES["tag notfound"]) tags = "";
				$(tag_elem).prependTo(elem);
				$(elem).children("input[type=text]").val(tags);
				$(elem).children(":visible").toastTagging();
			});

			elem.keyup(function(ev){
				if(ev.keyCode == 13 && $(elem).siblings("p").length){
					submit_update_tag(elem);
					elem.nextAll().show();
					elem.next().remove();
				 	elem.remove();
				}
				
			});
		}		
	});

	function submit_update_tag(elem){
		var before_tags = $(elem).siblings("p").text();
		var new_tags = $(elem).parent().find("input").val();

		if(before_tags != new_tags){

			var tag_id = $(elem).parent().attr("id").split("_");
			var queryString = "id="+tag_id[3]+"&tagable="+tag_id[2]
							+ "&taglist="+encodeURIComponent(new_tags);

			var tag_el = $(elem).siblings("p");
			$.ajax({
				type : "POST",
				url  : "/" + TEAM_URL+ "/tag/update_tag",
				data : queryString,
				dataType : "json",
				async : false,
				success : function(data){
					if(data.status == JSON_SUCCESS){
						if(data.html.length)
							$(tag_el).text(data.html);
						else {
							$(tag_el).text(MESSAGES["tag notfound"]);
							$(tag_el).addClass("empty");
						}
					} else
						toast_error_handle(data);
					},
				error : function(data, e){
					alert('[tag update]:'+e);
				}
			});
		}
		return;
	}
}

//* ------------------------- Recent Updates ------------------------------*//
var HISTORIES_MESSAGES = {
	"title open": I18n.t("tooltip.detail open"),
	"title close":  I18n.t("tooltip.detail close"),
	"text open": I18n.t("history.more"),
	"text close": I18n.t("history.less")
};
$.fn.box_update_event = function(){
	$(this).children("a:first").bind('click', function(){
		var $box_update = $('div.box_update:first');
		var status = "close";

		if ( $(this).hasClass('open_box') )
			get_histories('1');
		else {
			status = "open";
			$box_update.find("tr:gt(4)").remove();
			$box_update.find("tr:last").addClass("last");
			$('div.list_option', $box_update).remove();
		}

		$(this).attr({
			'class': status+"_box",
			'title': HISTORIES_MESSAGES["title "+status] 
		}).text(HISTORIES_MESSAGES["text "+status]);
	});
}

function get_histories(page){
	var my_id = MY_ID[2] || "dashboard"; 
	$.ajax({
		type: 'post', 
		url: '/'+TEAM_URL+'/'+my_id+'/get_histories', 
		data: '&page='+page, 
		dataType: 'json', 
		async: false, 
		success: function(data) {
			if ( data.status == JSON_SUCCESS) {
				var $box_update = $('div.box_update:first');

				$box_update.html(data.histories);
				$box_update.box_update_event();

				$("a:first", $box_update).attr({
					'class': "close_box",
					'title': HISTORIES_MESSAGES["title close"] 
				}).text(HISTORIES_MESSAGES["text close"]);

				if ( page != '0' && data.total_entries > data.per_page ) {
					$('div.list_nav:first', $box_update).paginate({
						page: page,
						total_entries: data.total_entries,
						per_page: data.per_page,
						onclick: "get_histories(\'#PAGE#\')"
					}).parent().show();
				}
				else 
					$('div.list_nav:first', $box_update).html('').parent().hide();
			}
			else 
					toast_error_handle(data);
		}, 
		error: function(res, e) {
			toast_ajax_error(res, '[get_histories:'+my_id+'] : '+e);
		}, 
		complete: function(res, e) {
		}
	});
}

//* ---------------------------- toast.message -------------------*//

MESSAGES = {
	"delete" : I18n.t("word.delete"),
	"delete done" : I18n.t("message.delete done"),
	"delete confirm" : I18n.t("alert.delete confirm"),
	"required" : I18n.t("alert.required"),
	"need" : I18n.t("alert.need"),
	"max length" : I18n.t("alert.max length"),
	"comment edit" : I18n.t("camp.comment.message.deny modify"),
	"comment delete" : I18n.t("camp.comment.message.deny delete"),
	"comment write" : I18n.t("camp.comment.message.deny write to deleted reply"),
	"comment all delete" : I18n.t("camp.comment.message.confirm delete"),
	"memo delete" : I18n.t("alert.memo delete"),
	"memo all delete" : I18n.t("alert.memo all delete"),
	"waiting file" : I18n.t("alert.waiting file"),
	"uploading file" : I18n.t("alert.uploading file"),
	"thumb file" : I18n.t("alert.thumb file"),
	"private" : I18n.t("word.private"), 
	"year" : I18n.t("date.prompts.year"), 
	"month" : I18n.t("date.prompts.month"),
	"sun": I18n.t("date.abbr_day_names")[0], 
	"mon": I18n.t("date.abbr_day_names")[1], 
	"tue": I18n.t("date.abbr_day_names")[2], 
	"wed": I18n.t("date.abbr_day_names")[3], 
	"thu": I18n.t("date.abbr_day_names")[4],
	"fri": I18n.t("date.abbr_day_names")[5], 
	"sat": I18n.t("date.abbr_day_names")[6],
	"pre month" : I18n.t("time.previous month"),
	"next month" : I18n.t("time.next month"),
	"today" : I18n.t("time.today"),
	"hour invalid" :I18n.t("invalid.hour"),
	"minute invalid" : I18n.t("invalid.minute"),
	"email invalid" : I18n.t("invalid.email"),
	"main email invalid" : I18n.t("invalid.main email"), 
	"rangeLength invalid" : I18n.t("invalid.rangeLength"),
	"equal invalid": I18n.t("invalid.equal"),
	"alphanum invalid": I18n.t("invalid.alphanum"),
	"special invalid" : I18n.t("invalid.special"),
	"number invalid" : I18n.t("invalid.number"),
	"mobile invalid" : I18n.t("invalid.mobile"),
	"tag notfound" : I18n.t("alert.tag notfound"),
	"close" : I18n.t("layer.close"),
//	"note" : "처음 등록된 파일입니다.",
//	"note notfound" : "등록된 노트가 없습니다.",
	"have no power" : I18n.t("message.auth invalied"),
	"download have no power" : I18n.t("alert.download have no power"), 
	"file required" : I18n.t("alert.file required"),
	"data required" : I18n.t("alert.data required"),
	"404" : I18n.t("alert.404"),
	"500" : I18n.t("alert.500"),
	"503" : I18n.t("alert.503"),
	"double submit" : I18n.t("alert.double submit"),
	"not yet" : "error handle~~(not yet)",
	"copy" : I18n.t("alert.copy done"),
	"copy only IE" : I18n.t("alert.copy only ie"),
	"maxCount": I18n.t("invalid.maxCount", { "count" : ""}), 
	"maxNumber invalid": I18n.t("invalid.maxNumber", { "number": ""}),
	"minNumber invalid": I18n.t("invalid.minNumber", { "number" : "" }), 
	"select member" : I18n.t("alert.select member"),
	"select file": I18n.t("alert.select file"), 
	"upload error" : I18n.t("alert.upload error"), 
	"send noti" : I18n.t("alert.send noti"),
	"retry send noti": I18n.t("alert.retry send noti"), 
	"page_notice message": I18n.t("front.main title")
};

//* ------------------------- toastSearch  -------------------------------*//
function search_page(page){	//longdal1
	var url = document.location.href.replace(/&page=\w+/, '');
	document.location.href = url + "&page="+page;
}

//* ---------------------------- document.ready ------------------*//
var SEARCH_URL = '/'+TEAM_URL+'/'+MY_ID[2]+'/search';
var SEARCH_ALL_URL = '/'+TEAM_URL+'/search/all';

$(function(){
	if(jQuery.browser.msie){
		$("a").each(function(){ this.hideFocus=true; }); 
	}
	
	if($('meta[name="ctime"]').length)
		TOAST_NOW = new Date($('meta[name="ctime"]').attr('content'));
	else
		TOAST_NOW = new Date();
		
	TOAST_TODAY = TOAST_NOW.getFullYear().toString();
	TOAST_TODAY += (TOAST_NOW.getMonth()+1).toString().length == 1 ? 
				"0"+(TOAST_NOW.getMonth()+1).toString() : 
				(TOAST_NOW.getMonth()+1).toString() ;
	TOAST_TODAY += TOAST_NOW.getDate().toString().length == 1 ? 
				"0"+ TOAST_NOW.getDate().toString() : 
				TOAST_NOW.getDate().toString() ;

	$("#side_calendar").calendar(TOAST_TODAY);

	/*-- search : longdal1 --*/
	$("#toast_search_svc_form").submit(function(){
		//if(!toast_validate_form(this)) return false;
		document.location.href = SEARCH_URL+"?"+$("#query").serialize();
		return false;
	});
	
	$('#toast_search_svc_form>a.action').bind('click', function(){
		$(this).parent().submit();
	});

	$("#toast_search_all_form").submit(function(){
		//if(!toast_validate_form(this)) return false;	
		var queryString = "?" + $("#a_query").serialize();
		document.location.href = SEARCH_ALL_URL + queryString;
		return false;
	});
	
	$("#toast_search_form").submit(function(){
		//if(!toast_validate_form(this)) return false;	
		var queryString = "?" + $("#query").serialize();
		var search_checked = $("#toast_search_form").find(".check").attr('checked');	
		if(search_checked)
			queryString += "&"+$("#r_query").serialize();

		if(MY_ID[3]=='all')
			document.location.href = SEARCH_ALL_URL + queryString;
		else
			document.location.href = SEARCH_URL + queryString;

		return false;
	});

	if( $("div#page_notice").length ) {
		$(this).find("div#page_notice").append("<p style='top:5px;height:50px;left:5px;color:#636363;';>"+MESSAGES['page_notice message']+"</p>");
		setTimeout("toast_scroll_notice()", 3000);
		/*--
		$("#page_notice").load("/view/notice.html", function(){
			toast_scroll_up("#page_notice", "div#page_notice>p");
		});
		--*/
	}else{
		try{
			NOTICE_DIV=$(".page_top").find("div.page_notice");
			if(NOTICE_DIV.size()>0){
				//NOTICE_DIV.append("<p style='top:5px;height:50px;left:5px;color:#636363;'>"+MESSAGES['page_notice message']+"</p>");
				NOTICE_DIV.append("<p style='top:5px;left:5px;color:#636363;'>"+MESSAGES['page_notice message']+"</p>");
				setTimeout("toast_scroll_notice()", 3000);
			}
		}catch(e){NOTICE_DIV=null;}
	}

	$('p.permalink>a').bind('click', function(){
		toast_clip($(this).parent().children('a.url').text());
	});
	
	$('a.action_option', 'span.global_search').bind('click', function(){
		$(this).parent().parent().parent().children('ul.layer_option').slideDown();
	});
	
	$('a', 'ul.layer_option').bind('click', function(){
		$('a', 'ul.layer_option').removeClass('on');
		$(this).addClass('on');
		if( !$(this).parent().prevAll('li').length )
			$('input:text', '#toast_gnb_search_form').attr('name', 'a_query');
		else
			$('input:text', '#toast_gnb_search_form').attr('name', 'query');

		$('ul.layer_option').slideUp();
		$('input[type=text]', '#toast_gnb_search_form').focus();
	});
	
	$('#toast_gnb_search_form').submit(function(){
		if ($.trim($('input[type=text]', this).val()) == '') {
			alert(MESSAGES['required']);
			$('input[type=text]', this).focus();
			return false;
		}
		
		var controller = $('a.on', 'ul.layer_option').attr('id');
		//var query = $('input[type=text]', this).val();
		if( controller == 'all' )
			document.location.href = SEARCH_ALL_URL + '?' + $(this).serialize();
		else
			document.location.href = '/'+TEAM_URL+'/'+ controller + '/search?' + $(this).serialize();

		return false;
	});
	
	$('a.action_search', 'span.global_search').bind('click', function(){
		$('#toast_gnb_search_form').submit();
	});
	
	// SWFUpload start
	if ($('span.swfspan').length > 0)
	{
		if (MY_ID[2] != "file")
		{
			$('span.swfspan').each(function(){
				$(this).toastUpload();
			});
		}
	}
	// SWFUpload end
});

function changeUrlPattern(elem){
	if( elem.childNodes.length && elem.nodeName.toLowerCase() !== 'a' ){
		for( var i = 0 ; i < elem.childNodes.length; i++ ){
			if( elem.childNodes[i].nodeType == 1 )
				changeUrlPattern(elem.childNodes[i]);
			else
			if( elem.childNodes[i].nodeType == 3 ){
				var text = ( $.browser.msie ) ? elem.childNodes[i].toString() : elem.childNodes[i].nodeValue;
				var pattern = "((http|mailto|ftp):(//)?)?[a-zA-Z0-9-_]*(\.)?[a-zA-Z0-9]+(\.)(com|co\.kr|net|org|go\.kr|or\.kr|pe\.kr|kr)[a-zA-Z0-9:\/]*[\\s]*";
				if( text.match(new RegExp(pattern, "ig")) !== null &&  checkUrlPattern(text.match(new RegExp(pattern, "ig"))).length != 0 ){
					var matches = checkUrlPattern(text.match(new RegExp(pattern, "ig")));
					for( var i = 0 ; i < matches.length; i++ ){
							var protocol = ( matches[i].match(new RegExp("((http|mailto|ftp):(//)?)", "ig")) !== null ) ? matches[i].match(new RegExp("((http|mailto|ftp):(//)?)", "ig")).toString() : "http://";
							protocol = ( protocol.match(new RegExp("mailto://", "ig"), "mailto:") !== null ) ? protocol.match(new RegExp("mailto://", "ig"), "mailto:").toString() : protocol;
							var url = matches[i].replace(new RegExp("((http|mailto|ftp):(//)?)", "ig"), "");
							elem.innerHTML = elem.innerHTML.replace(new RegExp(matches[i], "ig"), '<a href="' + protocol + url + '" title="' + url + '" target="_blank">'+matches[i]+'</a>');
					}
				}
			}
		}
	}
}

function checkUrlPattern(arr){
	var arrRet = new Array();

	for( var i = 0 ; i < arr.length ; i++ ){
		if( arr[i].indexOf(".") != -1 )
			arrRet[arrRet.length] = arr[i];
	}

	return arrRet;
}

//* ---------------- Resize a imagefile which is attached ------------------*//
function resize_photo(album_img, w)
{
	if(typeof(album_img)!="undefined"){
		var img_width = 500;
		if(typeof(w)!="undefined") img_width = w ;

		if(album_img.width>img_width){
			album_img.height = Math.ceil((album_img.height*img_width)/album_img.width);
			album_img.width  = img_width;

		}
	}
}


function view_photo(id)
{
	var style_var = "toolbar=no,location=no,directories=no,status=no,menubar=no";
	style_var+= ",scrollbars=yes,resizable=yes,left=300,top=0, width=600, height=450";

	win_pop = window.open("/"+TEAM_URL+"/file/viewPhoto/"+id, "img_viewr", style_var);
	win_pop.focus();

}

/*-------------------------lib:cookie-------------------------------------*/

jQuery.cookie = function(name, value, options){
	if(typeof value != 'undefined'){ // name and value given, set cookie
		options = options || {};
		if(value === null){
			value = '';
			options.expires = -1;
		}
		var expires = '';
 		if(options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)){
			var date;
			if(typeof options.expires == 'number'){
				date = TOAST_NOW.clone();
				date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
		}
		var path = options.path ? '; path=' + options.path : '';
		var domain = options.domain ? '; domain=' + options.domain : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if(document.cookie && document.cookie != ''){
			var cookies = document.cookie.split(';');
			for(var i = 0; i < cookies.length; i++){
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if(cookie.substring(0, name.length + 1) == (name + '=')){
					cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};

//* --------------------------- paginate (for history) ----------------------*//

$.fn.paginate = function(opts){
	var defaults = { 
		previous_label: '&nbsp;', 
		next_label: '&nbsp;', 
		separator: '&nbsp;', 
		param_name: 'page', 
		inner_window: 4, 
		outer_window: 1, 
		current_class: 'current', 
		per_page: 5
	};
	
	var options = $.extend(defaults, opts);
	options.inner_window = parseInt(options.inner_window, 10);
	options.outer_window = parseInt(options.outer_window, 10);
	options.per_page = parseInt(options.per_page, 10);
	options.page = parseInt(options.page, 10);

	var html = [];
	var action = '';
	var pages = [];
	var last_page = parseInt(options.total_entries / options.per_page) + (( options.total_entries % options.per_page == 0 ) ? 0 : 1);
	$(this).html('');
	
	if (last_page > 1) {
		if (options.onclick) {
			action = "onclick=\"" + options.onclick + ";\"";
		}
		else {
			var params = [];
			var searches = location.search.substr(1).split('&');
			for (var i = 0; i < searches.length; i++) 
				if (searches[i].split('=')[0] !== "page" && searches[i] !== "?" && searches[i] !== "") {
					params.push(searches[i]);
				}
			
			params.push(options.param_name + '=#PAGE#');
			action = "href=\"" + location.pathname + "?" + params.join("&") + "\"";
		}
		
		for (var i = (options.page - options.inner_window < 1) ? 1 : (last_page < options.page + options.inner_window) ? Math.max(1, last_page - options.inner_window * 2 + 1) : options.page - options.inner_window; i <= last_page && pages.length <= (( last_page < (options.inner_window * 2) ) ? last_page-1 : ( options.inner_window * 2)); i++) {
			pages.push(i);
		}
		
		pages = pages.concat([1, Number(options.page), Number(last_page)]);
		for (var i = 1; i <= options.outer_window; i++) {
			pages.push(1 + i);
			pages.push(last_page - i);
		}
		
		pages = array_unique(pages.sort(function(a, b){
			return a - b
		}));
		
		if (options.page == 1) 
			html.push('<span class="disabled prev_page" title="'+I18n.t("tooltip.paginate.disable prev page")+'">' + options.previous_label + '</span>');
		else 
			html.push('<a class="prev_page" title="'+I18n.t("tooltip.paginate.prev page")+'" ' + action.replace('#PAGE#', options.page - 1) + '>' + options.previous_label + '</a>');
		
		for (var i = 0; i < pages.length; i++) {
			if (i > 0 && pages[i - 1] + 2 < pages[i]) {
				html.push('<span class="gap">...</span>')
			}
			else
			if ( i > 0 && pages[i - 1] + 2 == pages[i] ) {
				var temp_page = pages[i - 1] + 1;
				html.push('<a ' + action.replace('#PAGE#', temp_page) + ' title="'+temp_page+'">' + temp_page + '</a>');
			}
			
			if (options.page == pages[i]) 
				html.push('<span class="' + options.current_class + '">' + pages[i] + '</span>');
			else 
				html.push('<a ' + action.replace('#PAGE#', pages[i]) + '>' + pages[i] + '</a>');
		}
		
		if (options.page == last_page) 
			html.push('<span class="disabled next_page" title="'+I18n.t("tooltip.paginate.disable next page")+'">' + options.next_label + '</span>');
		else 
			html.push('<a class="next_page" title="'+I18n.t("tooltip.paginate.next page")+'" ' + action.replace('#PAGE#', options.page + 1) + '>' + options.next_label + '</a>');
		
		return $(this).html(html.join(options.separator));
	}
	else{
		return this;
	}
};

/*------------------------ reader ----------------------*/
$.fn.get_reader = function(options) {
	var defaults = {
		type: '', 
		id: '', 
		callback: function(data) {
			return true;
		}
	};
	
	var opts = $.extend(defaults, options);
	var $this = $(this);
	opts.top = opts.top || $this.offset().top;
	opts.left = opts.left || $this.offset().left;
	
	if( opts.type && opts.id ) {
		var layer_id = 'layer_download_info';
		var $layer = $('#'+layer_id);
		
		if ( $layer.length && opts.type+'_'+opts.id == $layer.data('id')) {
			if ( $layer.is(':visible') ) {
				$('body').unbind('click.get_reader');
				$.toast.pop_layer.hide(layer_id);
			}
			else {
				$.toast.pop_layer.show(layer_id, { left: opts.left, top: opts.top });
				$('body').bind('click.get_reader', function(event) {
					if ( !$(event.target).parents('#'+layer_id).length && event.target != $this.get(0) ) {
						$.toast.pop_layer.hide(layer_id);
						$('body').unbind('click.get_reader');
					}
				});
			}
		}
		else {
			if ( $layer.length ) {
				$('body').unbind('click.get_reader');
				$.toast.pop_layer.hide(layer_id);
			}
			else {
				$.toast.pop_layer.add_layer({
					layer_download_info : {
						class_name: 'layer_view', 
						boxtop_title: '<h4 class=\"layer_title\">'+I18n.t("layer."+(opts.type == "CampFile" ? "download" : "read")+"_info.title")+'</h4>', 
						boxbody_content: '<dl class=\"download_info\"></dl>', 
						version: 2, 
						draggable: true
					}
				});
				
				$('a.box_x', $layer).bind('click', function() {
					$('body').unbind('click.get_reader');
				});
				$layer = $('#'+layer_id);
			}
			
			$.post('/'+TEAM_URL+'/team/get_reader', { readable_type: opts.type, readable_id: opts.id }, function(data) {
				var readers = [];
				$.each(data.readers, function(idx, reader) {
					readers.push('<dt>'+reader.read_at+'</dt><dd'+((reader.guest)?' class=\"guest\"':'')+'>'+$.trim(reader.name+' '+reader.position)+'</dd>');
				});
				
				if ( readers.length ) {
					$('dl.download_info', $layer).html(readers.join(''));
					$.toast.pop_layer.show(layer_id, { left: opts.left, top: opts.top });
					$layer.data('id', opts.type+'_'+opts.id);
					$('body').bind('click.get_reader', function(event) {
						if ( !$(event.target).parents('#'+layer_id).length && event.target != $this.get(0) ) {
							$.toast.pop_layer.hide(layer_id);
							$('body').unbind('click.get_reader');
						}
					});
				}
			}, 'json');
		}
	}
};
/*-- Personal Memo Start ----------------------------------*/
function reset_pm_count(){
	var $personal_memo = $('div.personal_memo:first');
	$personal_memo.parent().parent().prev().children('a:last').children('strong').text($personal_memo.children('ul.p_memo').children('li.ing').length);
	
	if ( $personal_memo.children('ul.p_memo').children('li').length ){
		var $null_data = $personal_memo.children('p.null_data');
		if( $null_data.length && $null_data.is(':visible') ){
			$null_data.hide();
		}
	}
	else{
		var $null_data = $personal_memo.children('p.null_data');
		if ( !$null_data.length ){
			$personal_memo.prepend("<p class=\"null_data\">"+I18n.t("camp.personal_memo.no data")+"</p>");
			$null_data = $personal_memo.children('p.null_data');
		}
		$null_data.show();
		if ($null_data.next("ul.p_memo").length)
			$null_data.next("ul.p_memo").remove();
	}
};

function reset_pm_height(){
	var $personal_memo = $('div.personal_memo:first');
	var height = 0;
	$personal_memo.children('ul.p_memo').children('li').each(function(idx){
		if( idx < 10 ){
			height += $(this).height();
			height += 5;
		}
	});
	
	height = ( height == 0 ) ? 0 : Math.max(100, height);
	$personal_memo.children('ul.p_memo').height(height+'px');
};

$.fn.pm_event_bind = function(){
	var self = this;
	$('a', self).unbind('click').bind('click', function(){
		var $a = $(this);

		if( $(this).hasClass('check_action') && $(self).hasClass('ing') ){
			if( $(self).data('ajax_call') ){
				alert(MESSAGES['double submit']);
				return;
			}
			else{
				$(self).data('ajax_call', true);
			}
			
			var id = $(this).parent().attr("id").split('_').pop();
			$.ajax({
				type: "POST", 
				url: "/"+TEAM_URL+"/user/done_memo", 
				data: "&id="+id, 
				dataType: "json", 
				success: function(data){
					if (data.status == JSON_SUCCESS) {
						var $ul = $(self).parent();
						var $li = $(self).clone(true);
						if ($ul.children('li.done:first').length) {
							$ul.children('li.done:first').before(self);
						}
						else {
							$ul.append(self);
						}
						$a.parent().removeClass('ing').addClass('done');
						$a.attr('title', I18n.t("camp.personal_memo.done"));
						reset_pm_count();
					}
					else{
						toast_error_handle(data);
					}
				}, 
				error: function(res, e){
					toast_ajax_error(res, '[user done_memo] : ' +e);
				}, 
				complete: function(res, e){
					$(self).removeData('ajax_call');
				}
			});
		}
		else
		if( $(this).hasClass('btn_i_delete_s') ){
			if( $(self).data('ajax_call') ){
				alert(MESSAGES['double submit']);
				return;
			}
			else{
				$(self).data('ajax_call', true);
			}
			
			if (!confirm(MESSAGES['delete confirm'])) {
				$(self).removeData('ajax_call');
				return;
			}
			
			var id = $(this).parent().attr('id').split('_').pop();
			$.ajax({
				type: "POST", 
				url: "/"+TEAM_URL+"/user/destroy_memo", 
				data: "&id="+id, 
				dataType: "json", 
				success: function(data){
					if (data.status == JSON_SUCCESS) {
						$(self).remove();
						reset_pm_count();
//						reset_pm_height();
					}
					else {
						toast_error_handle(data);
					}
				}, 
				error: function(res, e){
					toast_ajax_error(res, '[user destroy_memo] : '+e);
				}, 
				complete: function(res,e){
					$(self).removeData('ajax_call');
				}
			});
		}
	});
};

function array_sort(arr, options){
	options.key = options.key || 'count';
	options.stand = options.stand || "asc";
	var align = ( options.stand == "asc" ) ? 1 : -1;
	//if( $.browser.safari ) align = -1 * align;
	
	return arr.sort(function(a, b){
		var keyA = a[options.key];
		var keyB = b[options.key];
		
		if (keyA < keyB) return -1 * align;
		else
		if (keyB < keyA) return 1 * align;
		else
		if ($.browser.safari) return -1 * align;
		//if ($.browser.safari && keyA == keyB) return 1;
		else
			return 0;
	});
}

function get_datas_by_ids(ids, kind){
	var select_datas = [];
	kind = kind || 'charge';
	var datas = $('body').data(( kind == 'charge' ) ? 'members' : kind.split('_').shift()+'_categories');
	
	for(var i = 0 ; i < datas.length; i++ ){
		var data = datas[i];
		if( $.inArray(data[((kind == 'charge' ) ? 'id' : 'tag')], ids) > -1 )
			select_datas.push(data);
	}
	
	return array_sort(select_datas, {
		key: ((kind == 'charge') ? 'grade' : 'idx')
	});
}

function tag_sort(tags){
	return tags.sort(function(a, b){
		if( a.master && !b.master ) return -1;
		if( !a.master && b.master ) return 1;
		if( a.id != '' && b.id != '' && a.p_count > b.p_count ) return -1;
		if( a.id != '' && b.id != '' && a.p_count < b.p_count ) return 1;
		if( a.id != '' && b.id != '' && a.f_count > b.f_count ) return -1;
		if( a.id != '' && b.id != '' && a.f_count < b.f_count ) return 1;
		if( a.id != '' && b.id != '' && a.count > b.count ) return -1;
		if( a.id != '' && b.id != '' && a.count < b.count ) return 1;
		if( a.id != '' && ( b.id == '' || a.tag < b.tag )) return -1;
		if( b.id != '' && ( a.id == '' || a.tag > b.tag )) return 1;
		return 0;
	});
}

$(function(){
	var $personal_memo = $('div.personal_memo:first');
	if ($personal_memo.length) {
		$('input[toast]', $personal_memo).toastValidate();
		
//		reset_pm_height();
		$('a.btn_normal_s', $personal_memo).bind('click', function(){
			$(this).parent().submit();
		});
		
		$('#toast_user_memo_form', $personal_memo).submit(function(){
			var $form = $(this);
			
			if (!toast_validate_form($form.attr('id'))) 
				return false;
			
			$.ajax({
				type: "POST",
				url: "/" + TEAM_URL + "/user/create_memo",
				data: $form.serialize(),
				dataType: "json",
				success: function(data){
					if (data.status == JSON_SUCCESS) {
						var html = "<li class=\"ing\" id=\"personal_memo_" + data.memo.id + "\">" +
											"<a class=\"check_action\" title=\""+I18n.t("camp.personal_memo.ing")+"\"></a> " +
											"<span class=\"memo\">" +$.trim($('input:text', $form).val().toHtml())+"</span> " +
											"<a class=\"btn_i_delete_s\" title=\""+I18n.t("camp.personal_memo.delete")+"\"></a>" +
										"</li>";
						var $ul = $('ul.p_memo:first', $personal_memo);
						if (!$ul.length) {
							$('p.null_data', $personal_memo).after("<ul class='p_memo'></ul>");
							$ul = $('ul.p_memo:first', $personal_memo);
						}
						$ul.prepend(html);
						$ul.children('li.ing:first').pm_event_bind();
						$('input:text', $form).val('');
						reset_pm_count();
//						reset_pm_height();
					}
					else {
						toast_error_handle(data);
					}
				},
				error: function(res, e){
					toast_ajax_error(res, '[user create_memo] : ' + e);
				},
				complete: function(res, e){
					toast_validate_form_return($form.attr('id'));
				}
			});
			
			return false;
		});
		
		$('ul.p_memo>li', $personal_memo).each(function(){
			$(this).pm_event_bind();
		});
	}

	$("a", "ul.to_global").bind('click', function(){
		set_language($(this).attr("href").replace("/",""));
	});
});

// for subdomain 
function domain_css(filename){
	var f =document.createElement("link")
	f.setAttribute("rel", "stylesheet")
	f.setAttribute("type", "text/css")
	f.setAttribute("href", "/stylesheets/"+filename+".css")
	
	if (typeof f != "undefined")
		document.getElementsByTagName("head")[0].appendChild(f)
};

function set_language(type){
	$.cookie("t_language", type, {path:"/", expires:30});
};
/*
 * Start Hash History 
 * by gy7uj
 * 2010.05.06
 */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('2.M({d:l,c:l,B:l,q:2.j.N&&(2.j.O<8||r.P<8),Q:m(C,s){2.c=C;4(s)2.B=s;5 6=7.3.e(/\\?.*$/,\'\');2.d=6;4(2.q){4(2.d==\'\'){2.d=\'#\'}2("R").S(\'<9 T="t" U="V: W;"\'+\' s="X:x;"></9>\');5 g=2("#t")[0];5 9=g.y.r;9.D();9.E();9.7.3=6}f 4(2.j.u){2.a=[];2.a.b=k.b;2.v=[];2.n=k.b;2.o=w}4(6)2.c(6.e(/^#/,\'\'));Y(2.F,Z)},G:m(3){2.a.H(3);2.v.b=0;I.o=w},F:m(){4(2.q){5 g=2("#t")[0];5 9=g.10||g.y.r;5 6=9.7.3.e(/\\?.*$/,\'\');4(6!=2.d){7.3=6;2.d=6;2.c(6.e(/^#/,\'\'))}}f 4(2.j.u){4(2.n==k.b&&2.a.b>2.n){2.a.J()}4(!2.z){5 p=k.b-2.a.b;2.n=k.b;4(p){2.o=x;4(p<0){K(5 i=0;i<11.12(p);i++)2.v.13(2.a.14())}f{K(5 i=0;i<p;i++)2.a.H(2.v.J())}5 A=2.a[2.a.b-1];4(A!=l){2.d=7.3.e(/\\?.*$/,\'\');2.c(A)}}f 4(2.a[2.a.b-1]==l&&!2.o){4(7.3){5 6=7.3;2.c(7.3.e(/^#/,\'\'))}f{5 6=\'\';2.c(\'\')}2.o=w}}}f{5 6=7.3.e(/\\?.*$/,\'\');4(6!=2.d){2.d=6;2.c(6.e(/^#/,\'\'))}}},15:m(3){5 h;3=16(3.e(/\\?.*$/,\'\'));4(2.j.u){h=3}f{h=\'#\'+3;7.3=h}2.d=h;4(2.q){5 g=2("#t")[0];5 9=g.y.r;9.D();9.E();9.7.3=h;2.n=k.b;2.c(3)}f 4(2.j.u){2.z=w;I.G(3);5 L=m(){2.z=x};17.18(L,19);2.c(3);7.3=h}f{2.c(3)}}});',62,72,'||jQuery|hash|if|var|current_hash|location||iframe|historyBackStack|length|historyCallback|historyCurrentHash|replace|else|ihistory|newhash||browser|history|undefined|function|lastHistoryLength|isFirst|historyDelta|historyNeedIframe|document|src|jQuery_history|safari|historyForwardStack|true|false|contentWindow|dontCheck|cachedHash|historyIframeSrc|callback|open|close|historyCheck|historyAddHistory|push|this|shift|for|fn|extend|msie|version|documentMode|historyInit|body|prepend|id|style|display|none|javascript|setInterval|100|contentDocument|Math|abs|unshift|pop|historyLoad|decodeURIComponent|window|setTimeout|200'.split('|'),0,{}))
jQuery.extend({
	hashHistoryCallback: undefined, 
	hashHistoryInit: function(callback){
		if ( document.location.hash == "" ){
			document.location.hash = "#"+Number(new Date()).toString();
		}
		if ( typeof callback == "function" ) {
			$.hashHistoryCallback = callback;
			$.historyInit(function(hash){
				hash = hash.replace(/[^0-9]*/, "");
				var param = "";
				if ( $.cookie(hash) ){
					param = $.cookie(hash);
					param += "&hash="+hash;
				}
				else{
					param = "&hash="+document.location.hash.replace(/[^0-9]*/, "");
				}
				$.hashHistoryCallback(param);
			}, "");
		}
	}, 
	hashHistoryLoad: function(hash){
		$.historyLoad(hash);
	}, 
	hashHistorySave: function(params){
		var hash = Number(new Date()).toString();
		var txt = "";
		$.each(params, function(key, val){
			if( "hash" != key ) {
				txt += "&"+key+"="+val;
			}
		});
		txt += "&hash="+hash;
		$.cookie(hash, txt, { expires: 0 });
		$.hashHistoryLoad(hash);
	}, 
	hashHistoryData: function(){
		var hash = document.location.hash.replace(/[^0-9]*/, "");
		var params = {};
		if ( hash != "" && $.cookie(hash) ){
			var querys = $.cookie(hash).split("&");
			for( var i = 0 ; i < querys.length ; i++ ){
				var data = querys[i].split("=");
				params[data[0]] = data[1];
			}
			
		}
		return params;
	}, 
	hashHistoryUpdate: function(opts){
		var params = $.hashHistoryData();
		$.each(opts, function(key, val){
			params[key] = val;
		});
		
		$.hashHistorySave(params);
	}
});
/*
 * End Hash History
 */
