﻿
/// <reference path="jquery-1.3.2-vsdoc.js" />

/// <reference path="json2.js" />

var Consts = {
	Disabled: "disabled",
	Checked: "checked",
	ReadOnly: jQuery.props.readonly,
	Post: "post",
	Json: "json",
	Html: "html",
	selectedIndex: "selectedIndex",
	ExtraSize: ""
};
var CSS = {
	Display: "display"
};

var Paging = {
	setPage: function(page) {
		$("#this_page").val(page);
	},		
	reset: function() {
		this.setPage(1);
	}
}

var dialog = {
	alert: function(msg) {
		$("#default_dialog").text(msg).dialog({
			modal: true,
			bgiframe: true,
			autoOpen: false,
			dialogClass: 'alert',
			title: "お知らせ",
			resizable: false,
			buttons: {
				"確認": function() {
					$(this).dialog('close');
				}
			}
		}).dialog('open');
	},
	error: function(msg) {
		$("#default_dialog").text(msg).dialog({
			modal: true,
			bgiframe: true,
			autoOpen: false,
			dialogClass: 'error',
			title: "エラー",
			resizable: false,
			buttons: {
				"確認": function() {
					$(this).dialog('close');
				}
			}
		}).dialog('open');
	},
	confirm: function(msg, result_callback) {
		$("#default_dialog").text(msg).dialog({
			modal: true,
			bgiframe: true,
			autoOpen: false,
			dialogClass: 'error',
			title: "確認",
			resizable: false,
			buttons: {
				"取り消し": function() {
					$(this).dialog('close');
					result_callback(false);
				},
				"確認": function() {
					$(this).dialog('close');
					result_callback(true);
				}
			}
		}).dialog('open');
	},
	address: function(dong_name, success) {
		var dlg = $("#address_dialog");
		this._address_success = success;
		dlg.dialog({
			bgiframe: true,
			modal: true,
			autoOpen: false,
			resizable: false,
			width: 500,
			height: 400,
			buttons: {
				"CLOSE": function() {
					$(this).dialog('close');
				}
			},
			open: function() {
				$("#dong_name", dlg).val("");
				$("#address_list", dlg).empty();
			}
		}).dialog('open');
	},
	addressEntry: function() {
		var dlg = $("#address_entry");
		dlg.dialog({
			bgiframe: true,
			autoOpen: false,
			resizable: false,
			width: 705,
			height: 400
		}).dialog('open');
	},
	addedwork: function(price_callback) {
		var dlg = $("#addedwork-content");
		dlg.dialog({
			title: "オフッション加工",
			bgiframe: true,
			draggable: false,
			modal: true,
			autoOpen: false,
			resizable: true,
			width: 380,
			height: 500,
			position: 'right',
			buttons: {
				"確認": function() {
					if (!price_callback()) { return false; };
					$(this).dialog('close');
				},
				"価格リスト": function() {
					price_callback();
				}
			}
		}).dialog('open');
	},
	memberFind: function(success) {
		var dlg = $("#member_find_dialog");
		this.success_callback = success;
		dlg.dialog({
			bgiframe: true,
			draggable: false,
			modal: true,
			autoOpen: false,
			resizable: true,
			width: 600,
			height: 400,
			buttons: {
				"CLOSE": function() {
					$(this).dialog('close');
				}
			}
		}).dialog('open');
		$("#searchText").focus();
	},
	memberFindedList: function(success) {
		var dlg = $("#member_findedlist_dialog");
		this.success_callback = success;
		dlg.dialog({
			bgiframe: true,
			draggable: false,
			modal: true,
			autoOpen: false,
			resizable: true,
			width: 750,
			height: 400,
			buttons: {
				"CLOSE": function() {
					$(this).dialog('close');
				}
			}
		}).dialog('open');
	},
	cancel: function(success) {
		var dlg = $("#cancel_dialog");
		this.success_callback = success;
		dlg.dialog({
			bgiframe: true,
			draggable: false,
			modal: true,
			autoOpen: false,
			resizable: false,
			width: 380,
			height: 250,
			buttons: {			
				"取り消し": function() {
					$(this).dialog('close');
				},
				"確認": function() {
					var reason = $.trim($("#cancel_reason").val());
					if (reason == "") {
						alert("取り消しの理由を入力してください。");
						$("#cancel_reason").focus();
						return false;
					}
					$(this).dialog('close');
					success(reason);
				}
			}
		}).dialog('open');
	}
}


var ZimmerUI = {		
	unfoldAll: function() {
		$(".folding").removeClass("folded").addClass("unfolded");
		$(".folding").parent().parent().css({'background-color':'#584502','color':'#f3bd00'});
		$(".folding").parent().parent().next().css({'background-color':'#d9d2ba','color':'black'});
		$(".foldRow").show();
	},
		
	foldAll: function() {
		$(".folding").removeClass("unfolded").addClass("folded");
		$(".folding").parent().parent().css({'background-color':'#ffc','color':'black'});
		$(".foldRow").hide();
	},
	
	foldToggle: function(foldingIconElement) {
		$(foldingIconElement).toggleClass("folded").toggleClass("unfolded");
		var foldingRow = $(foldingIconElement).parent().parent();
		if ($(foldingIconElement).hasClass("unfolded")) {
		    foldingRow.css({'background-color':'#584502','color':'#f3bd00'});
		    foldingRow.next().css({'background-color':'#d9d2ba','color':'black'});
		} else {
		    foldingRow.css({'background-color':'#ffc','color':'black'});
		}
		foldingRow.next().visible($(foldingIconElement).hasClass("unfolded"));
	},
		
	getKey: function(using) {
		return "[" + using + "]" + location.pathname;
	},
		
	reloadPage: function() {
		$.cookie(this.getKey("scroll"), $(document).scrollTop());
		location.reload(true);
//		location.href='about:blank';
	},
	
	restoreScroll: function() {
		var value = $.cookie(this.getKey("scroll"));
		if (!value)
			return;
			
		$(document).scrollTop(value);
		$.cookie(this.getKey("scroll"), "");
	},
	
	getUnfoldedList: function() {
		return $.map( $(".unfolded").not("#foldAll").get(), function(value) {
			return $(value).parent().parent().id();
		});
	},
	
	restoreUnfoldedItems: function() {
		var value = $.cookie(this.getKey("folding"));
		if (!value || $.trim(value) == ",")
			return;
			
		var unfoldedList = value.split(",");
		for (var i in unfoldedList) {
			this.foldToggle($(".folding", $("#"+unfoldedList[i])));
		}
	},
	
	saveUnfoldedItem: function() {
		$.cookie(this.getKey("folding"), this.getUnfoldedList().join(","), {expires:1,path:"/"});
	}			
}


function popup(url, windowName, top, left, width, height, location, menubar, status, resizable, scrollbars, modal) {
	
	function makeFeature(top, left, width, height, location, menubar, status, resizable, scrollbars) {
		function YesNo(value) {
			return value ? "yes" : "no";
		};

		return "top=" + top
			+ ",left=" + left
			+ ",width=" + width
			+ ",height=" + height
			+ ",location=" + YesNo(location)
			+ ",menubar=" + YesNo(menubar)
			+ ",status=" + YesNo(status)
			+ ",resizable=" + YesNo(resizable)
			+ ",scrollbars=" + YesNo(scrollbars);
	}
	
	
	var newWindow = window.open(url, windowName, 
		makeFeature(top, left, width, height, location, menubar, status, resizable, scrollbars), true);

	newWindow.acti
	return newWindow;
	
}

function showErrorMessage(err) {
	alert('Error: ' + err.status + ' ' + err.statusText);
}

function simpleAjax(fields, url, data_type, success, complete, error) {
	jQuery.ajax({
		url: url,
		type: Consts.Post,
		data: fields,
		dataType: data_type,
		timeout: 500000,
		error: error || showErrorMessage,
		success: success,
		complete: complete
	});
}


function restoreSubmit() {
	$("submit").enabled(true);
}

function isExtraSize(sizeID) {
	return sizeID == Consts.ExtraSize;
}


function GetCode(codeList, id) {
	for (var i in codeList) {
	//alert(codeList[i].ID + " : " + id);
		if (codeList[i].ID == id)
			return codeList[i];
	}
}

function GetCipher(width, height, baseX, baseY) {
	var x = Math.ceil(width / baseX);
	var y = Math.ceil(height / baseY);
	var result = x * y;
	
	x = Math.ceil(width / baseY);
	y = Math.ceil(height / baseX);
	var rotationResult = x * y;
	
	return Math.min(result, rotationResult);
}

function LeftZipCode(zipcode_string) {
	return zipcode_string.substr(0, 3);
}
function RightZipCode(zipcode_string) {
	return zipcode_string.substr(3, 4);
}
function SplitNumber(number_string) {
	var split_number = [];
	split_number = number_string.split("-");
	if (split_number.length < 3) {
		split_number[0] = "";
		split_number[1] = "";
		split_number[2] = "";
	};
	
	return split_number;
}
function FormatZipCode(zipcode) {
	return $.trim("[" + zipcode.ZipCode + "] " + zipcode.Sido + " " + 
			zipcode.Gugun + " " + zipcode.Dong + " " + (zipcode.Bunji || ""));
}
function FormatAddress(zipcode) {
	return zipcode.Sido + " " + zipcode.Gugun + " " + zipcode.Dong;
}

function IsAscKeyCode(keyCode) {	
	return (keyCode >= 32 && keyCode <= 47) || (keyCode >= 58);
}

function elementStatusChangeForEmpty(element) {
    element.css("background-color", "yellow");
    return false;
}

function checkEmailFormat(email, prefix) {
	var mailAddress = $.trim(email);
	var result = true;
	if (mailAddress == "")
	{
		alert(prefix + "Eメールを入力してください。");
		result = false;
	}
	else if(mailAddress != "") 
	{
		var reg = new RegExp("^[\\w\\-]+(\\.[\\w\\-_]+)*@[\\w\\-]+(\\.[\\w\\-]+)*(\\.[a-zA-Z]{2,7})$", "gi");
		if (!reg.test(mailAddress))
		{
			alert(prefix + "正しいメール形式ではありません。");
	//		alert("無効なEメール形式です。");
			result = false;
		}
	}
	return result;
}

if (!String.prototype.Money) {
	String.prototype.Money = function() {		
		return parseInt($.trim(this.replace(",", "").replace("円","")));
	}
}
if (!Number.prototype.Won) {
	Number.prototype.Won = function() {		
	
		x = this.toFixed(0);
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x)) {
			x = x.replace(rgx, '$1' + ',' + '$2');
		}
		return x + "円";
	}
}
if (!Number.prototype.Yen) {
	Number.prototype.Yen = function() {		
	
		x = this.toFixed(0);
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x)) {
			x = x.replace(rgx, '$1' + ',' + '$2');
		}
		return x + "円";
	}
}
if (!Number.prototype.num) {
	Number.prototype.num = function() {
	
		x = this.toFixed(0);
		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x)) {
			x = x.replace(rgx, '$1' + ',' + '$2');
		}
		return x;
	}
}
if (!Number.prototype.percent) {
	Number.prototype.percent = function() {
		return this * 100;
	}
}
if (!Number.prototype.rate) {
	Number.prototype.rate = function() {
		return this / 100;
	}
}
if (!Array.prototype.Get) {
	Array.prototype.Get = function(id) {
		return GetCode(this, id);
	}
}
if (!String.prototype.contains) {
	String.prototype.contains = function(text) {
		return this.indexOf(text) != -1;
	}
}
if (!String.prototype.left) {
	String.prototype.left = function(count) {
		return this.substr(0, count);
	}
}
if (!String.prototype.right) {
	String.prototype.right = function(count) {
		return this.substr(this.length - count, count);
	}
}


;(function($) {

	$.fn.id = function() {
		return this.attr("id");
	}
	
	$.fn.selectedText = function() {
		return this.children("option[selected]").text();
	}

	$.fn.selectedVal = function() {
		return this.children("option[selected]").val();
	}	

	$.fn.intVal = function() {
		var result = parseInt(this.val());
		if (isNaN(result))
			result = 0;
		return result;
	}

	$.fn.selectedIndex = function(index) {
		if (index == null)
			return this.attr(Consts.selectedIndex);
		else {
			this.attr(Consts.selectedIndex, index);
			return this;
		}
	}
	
	$.fn.inArea = function(x, y, xMargin, yMargin) {	
		return x > this.offset().left - xMargin && x < this.offset().left + this.width() + (xMargin*2) && 
				y > this.offset().top - yMargin && y < this.offset().top + this.height() + (yMargin*2);
	}
	$.fn.inDialog = function(x, y) {	
		return x > this.offset().left && x < this.offset().left + this.dialog('option','width') && 
				y > this.offset().top && y < this.offset().top + this.dialog('option','height');
	}
	
	$.fn.popup = function(sender, ev, width, height) {
//		ev.stopPropagation();

		var panel = this;
		var sender = $(sender);

		if (panel.visible()) 
			panel.hide();
			
		function documentMouseMove(ev) {
			if( !(panel.inArea(ev.pageX, ev.pageY, 6, 10) || sender.inArea(ev.pageX, ev.pageY, 10, 10)) ) 
			{
				panel.hide();
				$(document).unbind('mousemove', documentMouseMove);
			}
		}
		
		$(document).mousemove(documentMouseMove);

		var senderOffset = sender.offset();
		panel.css('position', 'absolute');
		panel.width(width);
		panel.height(height);
		panel.css('z-index', '100001');
		panel.css('padding', '8px 0 0 6px');
		panel.css('border', 'solid 1px #ccc');
		panel.css('top', senderOffset.top + 20);
		
		var docWidth = $(document).width();
		
		if ((senderOffset.left + width) > docWidth) {
			senderOffset.left = docWidth - width - 40;
		}
		
//		alert(docWidth + " " + senderOffset.left + " " + width);
		
		panel.css('left', senderOffset.left);
		panel.show();
	}
	

	$.fn.readOnly = function(value) {
		if (value == null)
			return this.attr(Consts.ReadOnly);
		else {
			if (value)
				this.attr(Consts.ReadOnly, Consts.ReadOnly);
			else
				this.removeAttr(Consts.ReadOnly);

			return this;
		}
	}

	$.fn.enabled = function(value) {
		if (value == null)
			return !this.attr(Consts.Disabled);
		else {
			if (value)
				this.removeAttr(Consts.Disabled);
			else
				this.attr(Consts.Disabled, Consts.Disabled);

			return this;
		}
	}

	$.fn.checked = function(value) {
		if (value == null)
			return this.attr(Consts.Checked);
		else {
			if (value)
				this.attr(Consts.Checked, Consts.Checked);
			else
				this.removeAttr(Consts.Checked);

			return this;
		}
	}
	
	$.fn.visible = function(value) {
		if (value == null)
			return this.css(CSS.Display) != "none";
		else {
			if (value)
				this.show();
			else
				this.hide();

			return this;
		}
	}

	$.fn.mergeForm = function(form) {
		var $this = this;
		var fields = $(form).serializeArray();
		$.each(fields, function(i, field) {
			$this.append('<input type="hidden" name="' + field.name + '" value="' + field.value + '" class="merge" >');
		});
		return this;
	}
	
	
	$.fn.phoneCheching = function() {
		this.keypress(function(e) {
			if (IsAscKeyCode(e.which))
				return false;
		});
		return this;
	}


})(jQuery);

var datepicker_default = {
	closeText:"閉じる",
	prevText:"前月",
	nextText:"来月",
	currentText:"今日",
	monthNames:["年 1月","年 2月","年 3月","年 4月","年 5月","年 6月","年 7月","年 8月","年 9月","年 10月","年 11月","年 12月"],
	monthNamesShort:["年 1月","年 2月","年 3月","年 4月","年 5月","年 6月","年 7月","年 8月","年 9月","年 10月","年 11月","年 12月"],
	dayNames:["日","月","火","水","木","金","土"],
	dayNamesShort:["日","月","火","水","木","金","土"],
	dayNamesMin:["日","月","火","水","木","金","土"],
	dateFormat:"yy/mm/dd",
	showMonthAfterYear: true,
	firstDay:0,
	isRTL:false,
	showOn: 'button', 
	showAnim: 'slide',
	showOptions: {direction: 'up'},
	minDate: -1825, 
	maxDate: 0,
	duration: 'fast',
	hideIfNoPrevNext: true
//	showAnim: 'blind',
//	showOptions: {direction: 'vertical'}
};

if ($.blockUI) {
	$.blockUI.defaults = {
		// message displayed when blocking (use null for no message)
		message:  'Loading.....',

		// styles for the message when blocking; if you wish to disable
		// these and use an external stylesheet then do this in your code:
		// $.blockUI.defaults.css = {};
		css: {
			paddingLeft:    10,
			paddingRight:   10,
			paddingTop:		4,
			paddingBottom:	4,
			margin:         0,
	//        width:          '30%',
			top:            '50px',
			right:          '0px',
			position:		'fixed',
	//        textAlign:      'center',
			color:          '#000',
			border:         '1px solid #aaa',
			backgroundColor:'#ffc'
		},

		// styles for the overlay
		overlayCSS:  {
			backgroundColor: '#000',
			opacity:         '0.6'
		},

		// styles applied when using $.growlUI
		growlCSS: {
			width:    '350px',
			top:      '50px',
			left:     '',
			right:    '10px',
			border:   'none',
			padding:  '5px',
			opacity:  '0.6',
			cursor:    null,
			color:    '#fff',
			backgroundColor: '#000',
			'-webkit-border-radius': '10px',
			'-moz-border-radius':    '10px'
		},
		
		iframeSrc: 'javascript:false', // 'about:blank' fails on HTTPS

		// z-index for the blocking overlay
		baseZ: 1000,

		// set these to true to have the message automatically centered
		centerX: false, // <-- only effects element blocking (page block controlled via css above)
		centerY: false,

		// allow body element to be stetched in ie6; this makes blocking look better
		// on "short" pages.  disable if you wish to prevent changes to the body height
		allowBodyStretch: true,

		// be default blockUI will supress tab navigation from leaving blocking content;
		constrainTabKey: true,

		// fadeIn time in millis; set to 0 to disable fadeIn on block
		fadeIn:  0,

		// fadeOut time in millis; set to 0 to disable fadeOut on unblock
		fadeOut:  0,

		// time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock
		timeout: 0,

		// disable if you don't want to show the overlay
		showOverlay: false,

		// if true, focus will be placed in the first available input field when
		// page blocking
		focusInput: true,

		// suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity)
		applyPlatformOpacityRules: true,

		// callback method invoked when unblocking has completed; the callback is
		// passed the element that has been unblocked (which is the window object for page
		// blocks) and the options that were passed to the unblock call:
		//     onUnblock(element, options)
		onUnblock: null,

		// don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493
		quirksmodeOffsetHack: 4
	};
	
}

function checkIsZenkaku(el,value) {

    var result = false;
    for (var i = 0; i < value.length; ++i) {
        var c = value.charCodeAt(i);
        if (c < 256 || (c >= 0xff61 && c <= 0xff9f)) {
            continue;
        } else {
			dialog.alert("全角文字は入力できません。");
	        el.val("");
	        el.focus();
            result = true;
            break;
        }
    }
    return result;
}

function findAddressJP(prefix, url) {

	var zip_code = $("#" + prefix + "Zip1").val() + $("#" + prefix + "Zip2").val();

    $.ajax({
	    url: url,
	    dataType: Consts.Json,
	    data: {"zip_code": zip_code},
	    type: Consts.Post,
	    timeout: 3000,
	    error: showErrorMessage,
	    success: function(result) {
//	        callBack(result);
	        if (result.Success){
                var addressJP = result.Result;
                $("#" + prefix + "StateOrProvince").val(addressJP.Kanji1).change();
                $("#" + prefix + "City").val(addressJP.Kanji2).change();
                $("#" + prefix + "Line1").val(addressJP.Kanji3).change();
                return false;
	        }
	        else {
	            alert(result.Message);
	            $("#" + prefix + "Zip1").focus();
                return false;
	        }
	    }
    });
}

jQuery(document).ready(function() {
	jQuery(".date").datepicker(datepicker_default);
	jQuery(".phone, .numberOnly").phoneCheching();
	jQuery("button.button").hover(
		function() { jQuery(this).addClass("hover") },
		function() { jQuery(this).removeClass("hover") }
	);
	
	jQuery("table.table tr:even, table.filter tr:even").addClass("odd");

//	var name = document.getElementById("Title");
//	if (name != null)
//		if ($(name).visible())
//			name.focus();
		
		
//	jQuery("table.simple tr").livequery(function(){
//		jQuery(this).hover(
//			function() {
//			    jQuery(this).addClass("hover");
//		        if($(this).next().css("display") === "none") {
//		            $(this).css('background-color','#f3bd00');
//		        };
//			},
//			function() {
//			    jQuery(this).removeClass("hover");
//			    
//		        if($(this).next().css("display") === "none") {
//		            $(this).css('background-color','#ffc');
//		        };
//			}
//		);
//	}, function() {	
//        $(this)
//            .unbind('mouseover')
//            .unbind('mouseout');
//	});
	
	jQuery("span.addedwork").livequery(function() {
	
            $(this).mouseover(function() {
                $(this).next().show();
            });
            $(this).mouseout(function() {
                $(this).next().hide();
            });
    });	
	
	jQuery(".addedworks_details").livequery(function() {
	
            $(this).mouseover(function() {
                $(this).show();
            });
            $(this).mouseout(function() {
                $(this).hide();
            });
    });	
	
	$("#reloadPage").click(function(){
		ZimmerUI.reloadPage();
	});
	
	$(".folding").click(function() {
		var unfolded = $(this).hasClass("unfolded");
		ZimmerUI.foldToggle(this);
		ZimmerUI.saveUnfoldedItem();
	});
	
	$("#foldAll").click(function() {
		$(this).toggleClass("folded").toggleClass("unfolded");
		if ($(this).hasClass("unfolded")) {
			ZimmerUI.unfoldAll();
		} else {
			ZimmerUI.foldAll();
		}
		ZimmerUI.saveUnfoldedItem();
	});
	
	$(".searchZipCode").click(function() {
		
		window.open("","_blank").location.href = "http://search.post.japanpost.jp/zipcode/";
	});

});


// CALENDAR ********************************************************
// *****************************************************************
	function _getSpringDay(yyyy) {
		
		var str_yyyy = new String(yyyy);
	    var num1 = str_yyyy.substring(2,3);
	    var num2 = str_yyyy.substring(3,4);	  
	    var day;  
		if (num1 % 2 == 0) {	
			switch (num2) {
			case "0":
			case "1":
			case "4":
			case "5":
			case "8":
			case "9":
			 	day = 20;
			 	break;
			case "2":
			case "3":
			case "6":
			case "7": 
				day = 21;
			 	break;
			}								
		} else {			
			switch (num2) {
			case "0":
			case "1":
			case "4":
			case "5":
			case "8":
			case "9":			
			 	day = 21;
			 	break;
			case "2":
			case "3":
			case "6":
			case "7":		 
				day = 20;
			 	break;
			}	 
		}	
		return day;
	}

	function makeCalendar(addedMonth) {

		var monthnames = new Array("January","Februrary","March","April","May","June","July","August","September","October","November","Decemeber");
		var monthdays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
		var holidays = new Array(["1","A"],["11"],["B"],["29"],["3","4","5"],[],["C"],[],["C","23"],["A"],["3","23"],["23"]);
		var holidayTitles = new Array(["元日","成人の日"],["建国記念の日"],["春分の日"],["昭和の日"],["憲法記念日","みどりの日","こどもの日"],[],["海の日"],[],["敬老の日","秋分の日"],["体育の日"],["文化の日","勤労感謝の日"],["天皇誕生日"]);
		var todayDate = new Date();
		
        // 현재 날짜가 31일인 상태에서 다음달로 setMonth()를 하면 추가로 1Month가 더해진다.
        // 따라서 1,2(윤년),3,5,7,8,10,12월의 말일에는 다음달의 달력이 아니라 다다음달의 달력이 표시된다.
		if (addedMonth != 0)
		{ todayDate.setDate(1); }
		todayDate.setMonth(todayDate.getMonth() + addedMonth);
		var thisday=todayDate.getDay();
		var thismonth=todayDate.getMonth();
		thisdate=todayDate.getDate();
		var thisyear=todayDate.getYear();

		thisyear = thisyear % 100;
		thisyear = ((thisyear < 50) ? (2000 + thisyear) : (1900 + thisyear));
		if (((thisyear % 4 == 0) && !(thisyear % 100 == 0)) ||(thisyear % 400 == 0))
			monthdays[1]++;

		// 일본 휴일의 규칙을 알 수 없음.
		// 2012년에 9월의 휴일이 이동됨. 2013년은 후에 확인 할 것.
        if (thisyear == 2012) { holidays[8][1] = 22; }

		var startspaces = thisdate;
		while (startspaces > 7) startspaces-=7;
		startspaces = thisday - startspaces + 1;
		if (startspaces < 0) startspaces+=7;
		document.write("<div class='calendar_month'>");
		document.write("<p class='calendar_month_img' style='background-position: -"+(parseInt(thismonth)*50)+"px 0;'>&nbsp;</p>");
		document.write("</div>");
		document.write("<table class='calendar' cellpadding=0 cellspacing=0 border=0>");
		document.write("<tr>");
		document.write("<td class='week' style='background-position: 0 0;'>日</td>");
		document.write("<td class='week' style='background-position: -24px 0;'>月</td>");
		document.write("<td class='week' style='background-position: -48px 0;'>火</td>");
		document.write("<td class='week' style='background-position: -72px 0;'>水</td>");
		document.write("<td class='week' style='background-position: -96px 0;'>木</td>");
		document.write("<td class='week' style='background-position: -120px 0;'>金</td>");
		document.write("<td class='week' style='background-position: -144px 0;'>土</td>");
		document.write("</tr>");
		document.write("<tr>");
		for (var s=0;s<startspaces;s++) {
			document.write("<td class='empty'> </td>");
		}

		// 해당월의 토,일 배열을 구한다.
		var thisHolidays = holidays[thismonth];
		var realHolidays = new Array();
		var saturdays = new Array();
		var sundays = new Array();
		var saturdayHead = 7-startspaces;
        var sundayHead = 1;
		if (startspaces != 0) { sundayHead = saturdayHead + 1; }
		for (y = 0; y < 5; y++) {
			saturdays.push(saturdayHead + (7 * y));
			sundays.push(sundayHead + (7 * y));
		}

		// 휴일을 구한다.
        var Holiday = 0;
        var firstWeekDayCount = startspaces;
        var intervalDay = 2;    // 기본으로 일요일은 건너뛰고 월요일로 계산하므로.

		if (startspaces != 0) { firstWeekDayCount = 7 - startspaces; }
        if (startspaces != 1) { intervalDay = 9; }

		for (var z = 0; z < thisHolidays.length; z++) {
			Holiday = thisHolidays[z];

			if (Holiday == "A") {   // 2째주 월요일
				realHolidays.push(firstWeekDayCount + intervalDay);
			} else if (Holiday == "B") {
				realHolidays.push(_getSpringDay(thisyear));
			} else if (Holiday == "C") {    // 3째주 월요일
				realHolidays.push(firstWeekDayCount + (intervalDay + 7));
			} else {
				realHolidays.push(Holiday);
			}
		}
                
        var originHolidays = realHolidays.slice(0); // 제날짜에 title을 넣기위해 복사해 둔다.
		var swapDay = 0; // 실제휴일이 토,일과 겹칠경우 월요일로 swap한다.
        var swapedDays = new Array();
		for (var x = 0; x < realHolidays.length; x++) {
			for(var v = 0; v < sundays.length; v++) {
				if (sundays[v] == realHolidays[x]) {
					swapDay = sundays[v] + 1;
					// 5월은 3,4,5가 연휴이므로 중간에 일요일이 겹칠경우 6일로 휴일을 swap한다.
					if ((thismonth == 4) && ((swapDay == 4) || (swapDay == 5))) {
						realHolidays[x] = 6;
					} else {
						realHolidays[x] = swapDay;
					}
                    swapedDays.push(realHolidays[x]);
				}
			}
		}
        
		var count=1;		
		var tagChanged = false; // 휴일일 경우 font,title,swap을 위한 변수
		var titleText = "";
		var className = "";
        var thisMonthHoliday = 0;
		while (count <= monthdays[thismonth]) {
			for (var b = startspaces; b<7; b++) {
				// 휴일의 실제 titleText를 구한다.
                for (var t = 0; t < originHolidays.length; t++) {
                    if (count == originHolidays[t]) {
						titleText = holidayTitles[thismonth][t];
                    }
                }
				// 휴일이 겹쳐서 대체된 휴일일 경우 titleText를 구한다.
                for (t = 0; t < swapedDays.length; t++) {
                    if (count == swapedDays[t]) {
						titleText = "振替休日";
                    }
                }
				if ((count == thisdate) && (addedMonth == 0)) {
					className = "today";
					//이번달 오늘이 휴일일 경우 bold,red를 적용한다.
					for (t = 0; t < realHolidays.length; t++) {
						if (count == realHolidays[t]) {
							className = "strongHoliday";
						}
					}
				} else {
					if (b == 6 || b == 0) {
						className = "holiday";
					}
					if (className != "holiday") {
						for (t = 0; t < realHolidays.length; t++) {
							if (count == realHolidays[t]) {
								className = "holiday";
							}
						}
					}
				}

                // 임시공휴일 지정 귀차니즘 땜빵 ============
			    // count <= 날짜, thismonth <= 0부터 11까지, thisyear <= 그냥 연
				if ((count > 28) && (thismonth == 11) && (thisyear == 2010))
				{
					className = "holiday";
				}
				if ((2 < count) && (count < 5) && (thismonth == 0) && (thisyear == 2011))
				{
					className = "holiday";
                }
                if ((count == 30) && (thismonth == 11) && (thisyear == 2011)) {
	                className = "holiday";
                }
	            if ((count == 3 || count == 4) && (thismonth == 0) && (thisyear == 2012)) {
	                className = "holiday";
                }
				// ============

				if (count <= monthdays[thismonth]) {
					if (count < thisdate) { className = className + " previousdays"; }
					if (titleText != "") {
						document.write("<td class='" + className + "' title='" + titleText + "'>");
					}
					else {
						document.write("<td class='" + className + "'>");
					}
					document.write(count);
				} else {
					document.write("<td class='empty'>");
					document.write(" ");
				}
				document.write("</td>");
				titleText = "";
				className = "";
				count++;
			}
			document.write("</tr>");
			document.write("<tr>");
			startspaces=0;
		}
		document.write("</table></p>");
	}

// CALENDAR ************************************************************************
// *********************************************************************************
