/**
 * @author Administrator
 */

(function($) {

	function calendar() {
		this.defaults = {
			monthNames : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
			weekNames : ['日', '一', '二', '三', '四', '五', '六'],
			firstDay : 1,
			currentDate : new Date(),
			monthNamesShort : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
			dayNames : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
			dayNamesShort : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
			dayNamesMin : ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
			dateFormat : 'yy.MM',
			init : false,
			dataSelectEvent:null,
			eventTarget:null
		};
	}


	$.extend(calendar.prototype, {
		init : function(options,it) {
				var config = $.extend(this.defaults, options);
				$.calendar.setting = config;
				if (!config.init) {
					//append Calendar html
					var template = '<div class="danan-calendar-container" style="display:none;"><table class="danan-calendar" > <thead class="danan-calendar-body"> <tr class="monsths"> <th class="danan-calendar-title"><a href="javascript:void(0)" class="pre"><span class="danan-calendar-preMonth"></span></a><a href="javascript:void(0)" class="next"><span class="danan-calendar-nextMonth"></span></a><span class="date"></span></th> </tr> </thead> <tbody> <tr> <td><table class="danan-calendar-conont"><thead></thead><tbody></tbody> </table></td></tr></tbody></table></div>';
					$("body").append(template);
					//bind event
					$("th.danan-calendar-title a.pre,th.danan-calendar-title a.next").bind("click", function() {
						var $this = $(this);
						if ($this.hasClass('pre')) {
							$.calendar.AdustMonth(-1);
						}
						if ($this.hasClass('next')) {
							$.calendar.AdustMonth(1);
						}
					});
				var tb = $("table.danan-calendar-conont");
					//append week name
				var th = $("thead", tb);
				var template = "<tr>"
				for (var i = 0; i < config.weekNames.length; i++) {
					template += "<th>" + config.weekNames[(config.firstDay+i)%7] + "</th>";
				}
				template += "</tr" > th.append(template);
					$.calendar.updateDateView(config.currentDate,true);
					$.calendar.setting.init = true;
					//注册input的click事件
					if(it){
						it.each(function(){
							$(this).bind({'click':$.calendar.show});
						});
						
					}
					//注册点击别的地方，隐藏Calendar
					$(document).find('body').mousedown($.calendar.checkExternalClick);	
				}
			return this;
		},

		updateDateView : function(date,flag) {
			if (flag)$.calendar.setting.relseldate = date;
			var config = $.calendar.setting;
			config.currentDate = date;
			//get calendar days
			var y = config.currentDate.getFullYear();
			var m = config.currentDate.getMonth();
			config.days = $.calendar.getCalendarDays(y, m, config.firstDay);
			//init header
			var tb = $("table.danan-calendar-conont");
			//init body
			template = "<tr>";
			var title='';
			var isselday = false;
			var selday = date ;
			if (!flag) selday = $.calendar.setting.relseldate;
			for (var i = 0; i < config.days.length; i++) {
				if (i != 0 && i % 7 == 0) {
					template += "</tr><tr>";
				}
				var day=config.days[i];
				title=this.formatDate('yy-MM-dd',new Date(day.y,day.m,day.day));
				isselday=(day.y==selday.getFullYear()&&day.m==selday.getMonth()&&day.day==selday.getDate());
				template += "<td" + " class='" + day.disabled +(isselday?" today":"") +"'><a href='javascript:void(0)' title='"+title+"'>" + day.day + "</a></td>";
			}
			template += "</tr>"
			$("tbody", tb).empty().append(template);
			//init current days
			$("th.danan-calendar-title span.date").text($.calendar.formatDate(config.dateFormat, config.currentDate));
			$("td.false  a", tb).bind('click',$.calendar.selectDate);
		},
		selectDate:function(){
			var $this=$(this);
			var dateStr=$this.attr("title");
			var el=$.calendar.setting.eventTarget;
			if(el.attr('nodeName').toLowerCase()=='input'){			    
			el.val(dateStr);
			}
			$.calendar.setting.currentDate=$.calendar.stringToDate(dateStr);
			$.calendar.setting.relseldate = $.calendar.setting.currentDate;
			$.calendar.hide();
			if($.calendar.setting.dataSelectEvent){
			    $.calendar.setting.dataSelectEvent.call();
			}
		},
	stringToDate: function(string) {
        var matches;
        if (matches = string.match(/\d+/g)) {
          return new Date(matches[0], matches[1]-1, matches[2]);
        } else {
         return new Date();
         };
  },
		formatDate : function(format, date, settings) {
			if (!date)
				return '';
			var dayNamesShort = ( settings ? settings.dayNamesShort : null) || this.defaults.dayNamesShort;
			var dayNames = ( settings ? settings.dayNames : null) || this.defaults.dayNames;
			var monthNamesShort = ( settings ? settings.monthNamesShort : null) || this.defaults.monthNamesShort;
			var monthNames = ( settings ? settings.monthNames : null) || this.defaults.monthNames;
			// Check whether a format character is doubled
			var lookAhead = function(match) {
				var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
				if (matches)
					iFormat++;
				return matches;
			};
			// Format a number, with leading zero if necessary
			var formatNumber = function(match, value, len) {
				var num = '' + value;
				if (lookAhead(match))
					while (num.length < len)
					num = '0' + num;
				return num;
			};
			// Format a name, short or long as requested
			var formatName = function(match, value, shortNames, longNames) {
				return (lookAhead(match) ? longNames[value] : shortNames[value]);
			};
			var output = '';
			var literal = false;
			if (date)
				for (var iFormat = 0; iFormat < format.length; iFormat++) {
					if (literal)
						if (format.charAt(iFormat) == "'" && !lookAhead("'"))
							literal = false;
						else
							output += format.charAt(iFormat);
					else
						switch (format.charAt(iFormat)) {
							case 'd':
								output += formatNumber('d', date.getDate(), 2);
								break;
							case 'D':
								output += formatName('D', date.getDay(), dayNamesShort, dayNames);
								break;
							case 'o':
								output += formatNumber('o', Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
								break;
							case 'm':
								output += formatNumber('m', date.getMonth() + 1, 2);
								break;
							case 'M':
								output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
								break;
							case 'y':
								output += (lookAhead('y') ? date.getFullYear() : (date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
								break;
							case '@':
								output += date.getTime();
								break;
							case '!':
								output += date.getTime() * 10000 + this._ticksTo1970;
								break;
							case "'":
								if (lookAhead("'"))
									output += "'";
								else
									literal = true;
								break;
							default:
								output += format.charAt(iFormat);
						}
				}
			return output;
		},

		AdustMonth : function(driction) {
			var date = $.calendar.setting.currentDate;
			var y = date.getFullYear();
			var m = date.getMonth();
			var ad = $.calendar.adjustDate(y, m, driction);
			date = new Date(ad.y, ad.m, 1);
			$.calendar.updateDateView(date,false);
		},


		getCalendarDays : function(y, m, dayOfWeek) {
			var startAndEnd = {
				start : new Date(y, m, 1),
				end : new Date(y, m, $.calendar.getMonthDays(y, m))
			};
			var startDays =$.calendar.changeDayTo(dayOfWeek, startAndEnd.start.getDay(), -1);
			var endDays = $.calendar.changeDayTo((7 - dayOfWeek + 1) % 7, startAndEnd.end.getDay(), 1);

			/*******forwar days*********/

			var preDays = getDays(startDays, y, m, -1);
			var thisMonthNum = this.getMonthDays(y, m);
			for (var i = 0; i < thisMonthNum; ) {
				preDays.push({
					day : ++i,
					disabled : false,
					y:y,
					m:m
				});
			}
			if (preDays.length + endDays != 42) {
				endDays += 7;
			}
			return preDays.concat(getDays(endDays, y, m, 1));

		

			function getDays(days, y, m, driction) {
				var s = [];
				if (days != 0) {
					var ad = $.calendar.adjustDate(y, m, driction);
					var num = 0;
					if (driction == -1) {
						num = $.calendar.getMonthDays(ad.y, ad.m);
					}
					for (var i = 0; i < days; i++) {
						if (driction == -1) {
							s.push({
								day : num - days + i + 1,
								disabled : true,
								y:ad.y,
								m:ad.m
							});
						} else {
							s.push({
								day : i + 1,
								disabled : true,
								y:ad.y,
								m:ad.m
							});
						}
					}
				}
				return s;
			}
		},
			getMonthDays:function(y, m) {
				var monthDays = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
				if (m == 1 && isLeapYear(y)) {
					return 29;
				} else {
					return monthDays[m];
				}
				function isLeapYear(year) {
					return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
				}

},
	changeDayTo :function (dayOfWeek, day, direction) {
				return (Math.abs(day - dayOfWeek - (direction * 7)) % 7);
			},
		adjustDate : function(y, m, driction) {
			driction > 0 ? m++ : (driction < 0 ? m-- : m);
            m > 11 ? (y++,m=0) : (m < 0 ? (y--,m=11):y);
			return {
				y : y,
				m : m
			};
		},
		show:function(event){
			var $this=$(this);		
			var position=$this.offset();
			$.calendar.setting.curIns=true;
			$.calendar.setting.eventTarget=$this;
			$.calendar.updateDateView($.calendar.setting.relseldate,false);
			$("div.danan-calendar-container").show().offset({left:position.left,top:position.top+this.offsetHeight});
		},
		hide:function(){
			$.calendar.setting.curIns=false;
			$("div.danan-calendar-container").hide();
		},
		checkExternalClick:function(event){
			if($.calendar.setting.curIns){				
			var $target=$(event.target);
			if($target.closest("div.danan-calendar-container").length<1){$.calendar.hide();}
			}
		},
		getCurrentDateString:function(format){
            return this.formatDate(format?format:'yy-MM-dd',this.setting.currentDate);
        }	
	});

	$.fn.calendar = function(args) {
		if (!this.length) {
			return this;
		}
		$.calendar.el=this;
		if ($.calendar.init) {
			$.calendar.init(args,this);
		}
		// Method calling logic
		if ( typeof args === 'string') {
			return $.calendar[(args)].apply($.calendar, args);
		} else if ( typeof args === 'object' || !args) {
			return $.calendar.init(args);
		} else {
			$.error('Method ' + method + ' does not exist on jQuery.Calendar');
		}
	}

	$.calendar = new calendar();

})(jQuery);


	$(document).ready(function() {
		$('div#month-view, div#week-view, div#day-view, div#full-view').height($(window).height() - 50);
		$(window).resize(function() {$('div#month-view, div#week-view, div#day-view, div#full-view').height($(window).height() -50);})
		//刷新操作
		$("#refresh").click(function(){
			if(isconnectFlag == 0 || hasTipFlag) return false;
			$(this).removeClass().addClass('refreshing');
			var data = {};
			data.file= [];
			$.post("/Calendar/Refresh",data,function(){})
		});
		//导出到Vcs操作
		$("#ExportToVcs").click(function(){
			var data = {};
			data.CalenderID = [];
			var currentView=$("div.calendar-view:visible")
			cid=currentView.attr("id")
			switch (cid){
					 case 'month-view':
					 case 'week-view':
						$("div.newcheckbox").find("input:checked").parents("div.select").siblings("div.calendar_event").each(function(){
							data.CalenderID.push($(this).attr("Id"))
						})
						break;
						
					case 'day-view':
					case 'full-view':
						var selected=$(":checked",currentView);
						selected.each(function(){
							data.CalenderID.push($(this).attr("id"))
							})
						break;
					 }	
			if (data.CalenderID.length<1){return}	
			$("div#menu").hide('normal');
			$.post("/Calendar/ExportToVcs",data,function(){})
		});
		//删除所有操作
		$("#DeleteAll").click(function(){
			art.dialog({
						title: TransWording['DiagTitle'],
						content:TransWording['DiagContent'],
						okVal: TransWording['DiagOK'],
						cancelVal: TransWording['DiagCancel'],
						icon: "question",
						lock: true,
						background:'#fff',
						opacity: 0.7,
						ok:function(){
							var data = {};
							data.file= [];
							$("div#menu").hide('normal');
							$.post("/Calendar/DeleteAll",data,function(){		
							})
						},
						cancel: true
			})	
		});
		//导出到Outlook操作
		$("#ExportToOutlook").click(function(){
			var data = {};
			data.CalenderID = [];
			var currentView=$("div.calendar-view:visible")
			cid=currentView.attr("id")
			switch (cid){
					case 'month-view':
					case 'week-view':
						$("div.newcheckbox").find("input:checked").parents("div.select").siblings("div.calendar_event").each(function(){
							data.CalenderID.push($(this).attr("Id"))
						})
						break;
					case 'day-view':
					case 'full-view':
						var selected=$(":checked",currentView);
						selected.each(function(){
							data.CalenderID.push($(this).attr("id"))
							})
						break;
			}	
			if (data.CalenderID.length<1){return}		 
			$("div#menu").hide('normal');
			$.post("/Calendar/ExportToOutlook",data,function(){	})
		});
		//从Vcs导入
		$("#ImportFromVcs").click(function(){
			var data = {};
			data.file= [];
			$("div#menu").hide('normal');
			$.post("/Calendar/ImportFromVcs",data,function(){})
		});
		//从Outlook导入
		$("#ImportFromOutlook").click(function(){
			var data = {};
			data.file= [];
			$("div#menu").hide('normal');
			$.post("/Calendar/ImportFromOutlook",data,function(){})
		});
		//添加新建界面保存按钮动作
		$("div.maskWin-buttons a.save").click(function(){	
			var temp ;
			var data={alarmType:[],address:"",subject:"",description:"",startDate:"",endDate:"",isAllDay:"",repeatType:"",operate:"",Id:0,account:"", TimeZone:""}	
			var alarmTime 
			data.operate = NeworEidtFlag;
			if (NeworEidtFlag == "Edit"){
				data.Id = selectobj.Id
				data.account = selectobj.account
				data.TimeZone = selectobj.TimeZone
			}
			else {
				data.Id = 0
				data.account = $("#newaccount").find("option:selected").text()
				data.TimeZone = ""
			}
			data.subject = $("#newsubject").val();
			data.address = $("#newaddress").val();
			data.description = $("#newdescription").val();
									
			startday = $("#newstartDate").val();
			temp = startday.split('-')
			temp[1] = temp[1][0]==0? temp[1]:temp[1]<10? '0'+temp[1]:temp[1];
			startday = temp[0] + '-' + temp[1] + '-' + temp[2]

			starthour = $("#newstarthour").val();
			startminute = $("#newstartminute").val();
			hour = starthour<10?'0'+starthour:starthour;
			minute = startminute<10?'0'+startminute:startminute;
			data.startDate = startday + " " + hour + ":" + minute + ":" + "00"
			
			endday = $("#newendDate").val();
			temp = endday.split('-')
			temp[1] = temp[1][0]==0? temp[1]:temp[1]<10? '0'+temp[1]:temp[1];
			endday = temp[0] + '-' + temp[1] + '-' + temp[2]

			endhour = $("#newendhour").val();
			endminute = $("#newendminute").val();
			hour = endhour<10?'0'+endhour:endhour;
			minute = endminute<10?'0'+endminute:endminute;
			data.endDate = endday + " " + hour + ":" + minute + ":" + "00"
			
			data.isAllDay = $("#AllDay").hasClass('selected')
			data.repeatType = $("#frequency").get(0).selectedIndex

			$("select[name='alarm']").each(function(index){
					alarmTime = $(this).val()
					data.alarmType.push(alarmTime)
			});
			cc.showOrHideForm(false);
			$.post("/Calendar/ModifyCalendar",data,function(){ } )
		
		}); 
		
		 //新建事件
		$("a.new,a.editEvent,div.maskWin-buttons a.cancel").click(function(){
			if($(this).hasClass('new')){   
				NeworEidtFlag = 'Add'
				if(hasTipFlag)return false;
				cc.showOrHideForm(true);
				cc.InitNewData();
			}else if($(this).hasClass('editEvent')){
				 NeworEidtFlag = 'Edit'
				if(!editFlag || hasTipFlag) return false;
				var currentView=$("div.calendar-view:visible"),cid=currentView.attr("id");	
				//保存待编辑的原值
				switch (cid){
					 case 'month-view':
					 case 'week-view':
						checked_input = $("div.newcheckbox",currentView).find("input:checked").parents("div.select").siblings("div.calendar_event")
						break;
					 case 'day-view':
					 case 'full-view':
						checked_input = $("td",currentView).find("input:checked")
						break;
					 }	 
				selectobj = {}
				selectobj.Id = $(checked_input).attr('id')						
				selectobj.repeatType = $(checked_input).attr("repeattype")
				selectobj.account = $(checked_input).attr('account')
				selectobj.alarmType = $(checked_input).attr('alarmtype')
				selectobj.title = $(checked_input).attr('subject')
				selectobj.address = $(checked_input).attr("address")
				selectobj.description = $(checked_input).attr('description')
				selectobj.isAllDay = $(checked_input).attr('isallday')
				selectobj.startTime = $(checked_input).attr("starttime")
				selectobj.endTime = $(checked_input).attr("endtime")	
				selectobj.TimeZone = $(checked_input).attr("TimeZone")

				cc.showOrHideForm(true);
			
				cc.InitNewData(selectobj);
			}else{
			//添加新建界面取消按钮动作
				cc.showOrHideForm(false);
			}
		});	

		$("#AllDay").click(function(){
		//全天事件
			if(!$(this).hasClass('selected')){
				$(this).addClass('selected');
				$("#newendhour").attr("disabled",true);
				$("#newendminute").attr("disabled",true);
				$("#newstarthour").attr("disabled",true);
				$("#newstartminute").attr("disabled",true);
			}
			
			else{
				$(this).removeClass('selected');
				$("#newendhour").attr("disabled",false);
				$("#newendminute").attr("disabled",false);
				$("#newstarthour").attr("disabled",false);
				$("#newstartminute").attr("disabled",false);
			}
		});	
		
		$('a.ops').click(function(){
			if(hasTipFlag)return false;
			window.cc.nextOrPreView($(this).attr('name'));
			 cc.updateTodayTimeView(); //日期变化时更新选择的时间           
		});
	})

function ColonCalenader(setting){
	this.setting = setting;
	this.setting.Data = CalendarDatas;
	this.menuClosing=false;								
	if(typeof this.init !="function"){
		ColonCalenader.prototype.init=function(){
			this.weekHeadInit();
			this.monthInit();
			$("div#tab-container ul.calendar-tab>li a").click(this.updateView); //注册事件
			this.dayViewInit(); //渲染日视图 
			this.updateTodayTimeView(); //更新当前时间显示
			this.addEvent(this.setting.Data,'month-view'); //装载数据
			 //单击表格显示事项
			$("div#month-view td.false div.calendar_event,table.calendar-week div.data_body div").live('click',ColonCalenader.prototype.processNewOrEditEvent);
			//注册tip的取消事件
			$("div.maskWin-neweven a.canel,body").click(function(event){
				var $target=$(event.target);
				if(!$target.hasClass('calendar_event')&&(($target.closest('div#maskWin').length<1/*&&cc.tipInUse*/)||$target.hasClass('close'))){
					cc.hideTipWin();
				}
				else if(!$target.hasClass('calendar_event')&&(($target.closest('div#maskWin').length<1/*&&cc.tipInUse*/)||$target.hasClass('edit'))){
					NeworEidtFlag = 'Edit'
					var currentView=$("div.calendar-view:visible"),
					cid=currentView.attr("id");
					
					switch (cid){	
						case 'month-view':
						case 'week-view':
						var selected=$("div.selected",currentView);
						break;
						}	
					cc.hideTipWin();
					cc.showOrHideForm(true);
					cc.InitNewData(selectobj);								
				}
				else if(!$target.hasClass('calendar_event')&&(($target.closest('div#maskWin').length<1/*&&cc.tipInUse*/)||$target.hasClass('delete'))){
					cc.hideTipWin();
					delFlag = true;
					cc.deleteViewevent();
					delFlag  = false;
				}
			}); 
			//注册新建中提醒项目的添加删除按钮事件
			$("a[name='del_alert']").live('click',this.delAlert);
			$("a[name='add_alert']").live('click',this.addAlert);
			//注册全选按钮的事件
			$("a[name='deleteEvent']").click(this.deleteSelectedEvent);
			//注册下拉菜单事件
			$("a[name='moreOp']").click(function(event){
				if(hasTipFlag)return false;
				var $this=$(this);
				var pos=$this.offset();
				var height=$this.outerHeight();
				pos.top+=height;
				var data = {};
				data.CalenderID = [];
				var currentView=$("div.calendar-view:visible")
				cid=currentView.attr("id")
				switch (cid){
						 case 'month-view':
						 case 'week-view':
							$("div.newcheckbox").find("input:checked").parents("div.select").siblings("div.calendar_event").each(function(){
								data.CalenderID.push($(this).attr("Id"))
							})
							break;
							
						case 'day-view':
						case 'full-view':
							var selected=$(":checked",currentView);
							selected.each(function(){
								data.CalenderID.push($(this).attr("value"))
								})
							break;
				}	
				if (data.CalenderID.length < 1){
					$("#ExportToVcs,#ExportToOutlook").css("color","#c0c0c0")
					$("#ExportToVcs,#ExportToOutlook").hover(function(){
						$(this).css("color","#c0c0c0")
					},function(){
						$(this).css("color","#c0c0c0")
					})
				}else{
					$("#ExportToVcs,#ExportToOutlook").css("color","#000")
					$("#ExportToVcs,#ExportToOutlook").hover(function(){
						$(this).css("color","#fff")
					},function(){
						$(this).css("color","#000")
					})
				}
				$("#menu").show().animate({left:pos.left,top:pos.top},0);
			});
			//注册menu onmouseout事件
			$("div#menu").bind({'mouseleave':function(event){
				cc.menuClosing=true;
				setTimeout('cc.hideMenu()',0);
			},'mouseenter':function(event){
				 cc.menuClosing=false;
			}});
			return this;
		}

		//新建视图中提醒按钮的删除事件
		ColonCalenader.prototype.delAlert=function(){	
			$(this).parent("li").remove()
			count = count - 1;
			if(count == 4)
				$("a[name='add_alert']").show()
		}
		
		//新建视图中提醒按钮的添加事件
		ColonCalenader.prototype.addAlert=function(){
			if(count < 5){
				$("div.alert").append(inSelect);
				count =count + 1;
			}
			if(count == 5)
				$("a[name='add_alert']").hide()	
		}	
		//更新视图
		ColonCalenader.prototype.updateView=function(event,viewName, pid){
			//切换视图之前若发生全选事件，先取消
			if($("div.selectAll a").hasClass('selected')){
				$("div.selectAll a").siblings(':checkbox')[0].checked = false;
				$("div.selectAll a").removeClass('selected');
				$('div.calendar-view:visible .select span').remove()
				$('div.calendar-view:visible .select input').each(function(){
					$(this)[0].checked = false;	
				})	
				normal = false;
				normal = true;
			}
			$('a[name="deleteEvent"]').addClass('disabled')
			$('a[name="editEvent"]').addClass('disabled')
			cc.showOrHideForm(false);
			var $this=viewName?($("ul.calendar-tab li a."+viewName)):($(this)); 											  
			if(viewName=='month-view'||$this.hasClass('month-view')){
				cc.monthInit();
				//追加数据
				cc.addEvent(cc.setting.Data,'month-view');
			}
			if(viewName=='week-view'||$this.hasClass('week-view')){
				cc.weekViewUpdate();
			}
			if(viewName=='day-view'||$this.hasClass('day-view')){
				cc.dayViewInit();
			}
			 if(viewName=='full-view'||$this.hasClass('full-view')){
				cc.fullViewUpdate();
			}
			$("div.calendar-view").hide();
			$("#"+$this.attr('className')).show();	
		}
		
		//对日历进行渲染
		ColonCalenader.prototype.monthInit=function(){
		   var template = "<tr>";
		   var today=new Date();
		   var ty=today.getFullYear();
		   var tm=today.getMonth();
		   var td=today.getDate();

		   for (var i = 0; i < this.setting.days.length; i++) {
				var day=this.setting.days[i];
				if (i != 0 && i % 7 == 0) {
					template += "</tr><tr>";
				}
				var isToday=day.y==ty&&day.m==tm&&day.day==td;
				var m = day.m + 1
				var d = day.day
				if(m<10){m='0'+m}
				if(d<10){d='0'+d}
				var s=""+day.y+"-"+ m +"-"+ d;
					template += "<td class='"+day.disabled+(isToday?" month-today":'')+"'><div class='month_head'>" +day.day+"</div><div class='data_body' title='"+s+"'></div></td>";
			}
			
			$("table.calendar-month tbody").empty().append(template);  
		}
		//对month week head进行设置
		ColonCalenader.prototype.weekHeadInit = function() {
			var nweeks = this.setting.weekNames;
			var thead = $("table.calendar-month thead");
			var template = "";
			for (var i = 0; i < nweeks.length; i++) {
				template += "<th class='weekviewhead'>" + weekDayNames[(i+this.setting.firstDay)%7] + "<div class='weekMonthName'></div></th>";	
				if (i == nweeks.length - 1) {
					template += "</tr>";
				}
			}
			thead.append("<tr>"+template);			
			//对24小时进行设置
			var weekHeader=$("table.calendar-week thead")
			weekHeader.append("<tr><th></th>"+template);
			var tb=$("div#week-view table.calendar-week tbody");
			var template='';
			for(var i=0;i<24;i++){
				var data=i<10?'0'+i:i;
				template+="<tr><td class='weekviewfirst' time='"+data+"'><span class='bigTime'>"+data+"</span>:00</td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td><td class='weekviewhead'><div class='data_body'></div></td></tr>"
			}
			tb.append(template);
		}
		
		ColonCalenader.prototype.weekViewUpdate=function(date){
			if(!date){date=this.setting.currentDate;}
			var y=date.getFullYear();//年份
			var m=date.getMonth();//月份
			var weekDay=date.getDay();//日期几
			var day=date.getDate();//月天
			var preDays=$.calendar.changeDayTo(this.setting.firstDay,weekDay,-1);
			var nextDays=$.calendar.changeDayTo((7 - this.setting.firstDay + 1) % 7,weekDay,1);
			var monthDays=$.calendar.getMonthDays(y,m);
			var days={start:{y:y,m:m,d:day-preDays,max:monthDays},end:{y:y,m:m}};
			if(day-preDays<0){
				var ad=$.calendar.adjustDate(y,m,-1);
				var pdays=$.calendar.getMonthDays(ad.y,ad.m);
				days.start={y:ad.y,m:ad.m,d:pdays-preDays+day,max:pdays};
				day.end={y:y,m:m};                            
			}
			else if(day+nextDays>monthDays){
				var ad=$.calendar.adjustDate(y,m,1);
				days.end={y:ad.y,m:ad.m};
			}
		  //渲染周的月份
			var today=new Date();
			var ty=today.getFullYear();
			var tm=today.getMonth();
			var td=today.getDate();
			tm += 1;
			if(tm<10)tm = '0'+ tm
			if(td<10)td = '0'+ td
			temp = ty + '-' + tm + '-' + td
				  
			var start=days.start;
			var end=days.end;
			var next=1;
			var dayArrays=[];//保存week title						  
			$("div#week-view table.calendar-week div.weekMonthName").each(function(i,item){							
				var s=null;						  
				if(start.d+i<=start.max){
					s=new Date(start.y,(start.m),start.d+i);                             
				}else{
					s=new Date(end.y,(end.m),next++);
				}						  
				item.innerHTML=$.calendar.formatDate('mm-dd',s);
				item.title=$.calendar.formatDate('yy-mm-dd',s);
				dayArrays.push(item.title);
	
				if(item.title == temp){
					$(item).parent('th').attr('id','weekoftoday')
				}
				else{
					$(item).parent('th').attr('id','ss')
				}
			});  

		  //装载数据,注意数据的格式
			var tb=$("div#week-view td div.data_body");
			tb.empty();
			datas = CalendarDatas[currentTreeView.pid]
			for(var i=0;i<datas.length;i++){
				var data=datas[i];						  
				var day=data.startTime.substring(0,10);		  
			  
				var time=new Number(data.startTime.substring(11,13));
				var index=$.inArray(day,dayArrays);		
				if (index!=-1){
					if (data.title){showinfo = data.title.substring(0,6)
						if(data.title.length>6)showinfo+="..."
					}
					else if(data.address){showinfo = data.address.substring(0,6)
						if(data.address.length>6)showinfo+="..."
					}
					else if(data.description){showinfo = data.description.substring(0,6)
						if(data.description.length>6)showinfo+="..."
					}
					else if(data.startTime){showinfo = data.startTime.substring(0,10)}
					else if(data.endTime){showinfo = data.endTime.substring(0,10)}
					else{showinfo = ""}
					subcontent = "<div class='newcheckbox'><span class='newbox'><div class='calendar_event' subject='"+data.title+"' startTime='"+data.startTime+"' endTime='"+data.endTime+"' address='"+data.address+"' description='"+data.description+"' Id='"+data.Id+"' alarmType='"+data.alarmType+"' isAllDay='"+data.isAllDay+"' repeatType='"+data.repeatType+"' status='"+data.status+"' account='"+data.account+"' TimeZone='"+data.TimeZone+"'>"+showinfo+"</div></span></div>"
					
					tb.eq((time)%24*7+index).append(subcontent);							
			    }		  
		    }
			addSelect();                      
		}

		//日视图初始化
	   ColonCalenader.prototype.dayViewInit=function(){				   
			var tb=$("div#day-view table.calendar-day");
			var daytext = $.calendar.formatDate('yy-MM-dd',this.setting.currentDate);
			var y=this.setting.currentDate.getFullYear();//年份
			var m=this.setting.currentDate.getMonth()+1;//月份
			var day=this.setting.currentDate.getDate();//月天							
			$("span.todayDate",tb).text(daytext);
		   //对于日视图不做24小时修饰
			var tbody=$("tbody",tb);
			tbody.empty();
						
			var ds = CalendarDatas[currentTreeView.pid]						
			for(var i=0;i<ds.length;i++){
			
				var starty = new Number(ds[i].startTime.substring(0,4))
				var startm = new Number(ds[i].startTime.substring(5,7))
				var startday = new Number(ds[i].startTime.substring(8,10))
				
				var endy = new Number(ds[i].endTime.substring(0,4))
				var endm = new Number(ds[i].endTime.substring(5,7))
				var endday = new Number(ds[i].endTime.substring(8,10))
										
				if ((y==starty&&m==startm&&day==startday)){
					if(ds[i].isAllDay==1)isallday = TransWording["AllDay"]
					else isallday = TransWording["NotAllDay"]

					 //初始化设置频率目录项的内容
					Frequency(ds[i].startTime.substring(0,10))
					switch(ds[i].repeatType){
						case 0:
							repeat = $("option#onlyone").text()
							break;
						case 1:
							repeat = $("option#everyday").text()
							break;
						case 2:
							repeat = $("option#everyworkday").text()
							break;	
						case 3:
							repeat = $("option#everyweek").text()
							break;	
						case 4:
							repeat = $("option#everymonth1").text()
							break;	
						case 5:
							repeat = $("option#everymonth2").text()
							break;
						case 6:
							repeat = $("option#everyyear").text()
							break;	
						default:
							break;
					}
				    tbody.append("<tr"+(i%2==0?" class='odd'":"")+"><td><input type='checkbox' name='id' id='"+ds[i].Id+"' repeattype='"+ds[i].repeatType+"' starttime='"+ds[i].startTime+"' endtime='"+ds[i].endTime+"' subject='"+ds[i].title+"' address='"+ds[i].address+"' description='"+ds[i].description+"' isallday='"+ds[i].isAllDay+"' account='"+ds[i].account+"' alarmtype='"+ds[i].alarmType+"' TimeZone='"+ds[i].TimeZone+"'></input></td><td>"+ds[i].startTime+"</td><td>"+ds[i].endTime+"</td><td>"+ds[i].title+"</td><td>"+ds[i].address+"</td><td>"+ds[i].description+"</td><td>"+isallday+"</td><td>"+ds[i].account+"</td><td>"+ds[i].alarmType+"</td><td>"+repeat+"</td>");    
				} 
		    }
	    } 
	   
	    //全视图的更新数据
	    ColonCalenader.prototype.fullViewUpdate=function(){
			var tb=$("div#full-view table.calendar-day");
			var tbody=$("tbody",tb);
		    tbody.empty();
		    var ds = CalendarDatas[currentTreeView.pid]		
		   
		    for(var i=0;i<ds.length;i++){
				if(ds[i].isAllDay==1)isallday = TransWording["AllDay"]
				else isallday = TransWording["NotAllDay"]
				 
				//初始化设置频率目录项的内容
				Frequency(ds[i].startTime.substring(0,10))
				switch(ds[i].repeatType){
					case 0:
						repeat = $("option#onlyone").text()
						break;
					case 1:
						repeat = $("option#everyday").text()
						break;
					case 2:
						repeat = $("option#everyworkday").text()
						break;	
					case 3:
						repeat = $("option#everyweek").text()
						break;	
					case 4:
						repeat = $("option#everymonth1").text()
						break;	
					case 5:
						repeat = $("option#everymonth2").text()
						break;
					case 6:
						repeat = $("option#everyyear").text()
						break;	
					default:
						break;
				}
			    tbody.append("<tr"+(i%2==0?" class='odd'":"")+"><td><input type='checkbox' name='id' id='"+ds[i].Id+"' repeattype='"+ds[i].repeatType+"'  starttime='"+ds[i].startTime+"' endtime='"+ds[i].endTime+"' subject='"+ds[i].title+"' address='"+ds[i].address+"' description='"+ds[i].description+"' isallday='"+ds[i].isAllDay+"' account='"+ds[i].account+"' alarmtype='"+ds[i].alarmType+"' TimeZone='"+ds[i].TimeZone+"'></input></td><td>"+ds[i].startTime+"</td><td>"+ds[i].endTime+"</td><td>"+ds[i].title+"</td><td>"+ds[i].address+"</td><td>"+ds[i].description+"</td><td>"+isallday+"</td><td>"+ds[i].account+"</td><td>"+ds[i].alarmType+"</td><td>"+repeat+"</td>"); 
		    }
	    }
	   
	    //日历的上一天或者下一天，上一周或者下一周，上一月或者下一月
	    ColonCalenader.prototype.nextOrPreView=function(op){
			//切换页面之前若发生全选事件，先取消
			if($("div.selectAll a").hasClass('selected')){
				$("div.selectAll a").siblings(':checkbox')[0].checked = false;
				$("div.selectAll a").removeClass('selected');
				$('div.calendar-view:visible .select span').remove()
				$('div.calendar-view:visible .select span').each(function(){
					$(this)[0].checked = false;
				})
				normal = false;
				//selectedAllEvent();
				normal = true;
			}
			$('a[name="deleteEvent"]').addClass('disabled')
			$('a[name="editEvent"]').addClass('disabled')

			var current=$("div.calendar-view:visible");
			var type=current.attr("id");
			var date=$.calendar.setting.relseldate;
			var y=date.getFullYear();
			var m=date.getMonth();                      
			var d=date.getDate();
			if(type=='month-view'){					  
				if(op=='today'){
					$.calendar.updateDateView(new Date(),true);
				}else{                              
					var ad = getAdjustDate(y,m,d,op=='today'?0:op=='previous'?-1:1);
					$.calendar.updateDateView(new Date(ad.y,ad.m,ad.d),true);
				}
				this.monthInit();
				this.addEvent(this.setting.Data,'month-view');
			} 
			if(type=='week-view'){
				if(op=='today'){
					date=new Date();
				}else{
					date.setTime(date.getTime()+((op=='previous'?-1:1)*7*24*3600*1000));
				}
				$.calendar.updateDateView(date,true);
				this.weekViewUpdate();
			}
			if(type=='day-view'){
				if(op=='today'){
					date=new Date();
				}else{
					date.setTime(date.getTime()+((op=='previous'?-1:1)*24*3600*1000));
				}       
				$.calendar.updateDateView(date,true);						  
				this.dayViewInit(); 
			}
			function getAdjustDate(y, m, d, driction){
				driction > 0 ? m++ : (driction < 0 ? m-- : m);
				m > 11 ? (y++,m=0) : (m < 0 ? (y--,m=11):y);
				max_days = $.calendar.getMonthDays(y,m)
				d = max_days < d ? max_days : d ;
				return {
					y : y,
					m : m,
					d : d
				};
			}
	    }
	   
		ColonCalenader.prototype.updateTodayTimeView=function(){
			//修改today的日期
			$("div.new-iiiicon>a#currentDay").html($.calendar.getCurrentDateString('yy-MM-dd'));    
			return this;                    
		}
		//追加数据事项到日历上,数据必须在当前的日期范围内
		ColonCalenader.prototype.addEvent=function(CalendarDatas,type){
			data = CalendarDatas[currentTreeView.pid]
			if(type=='month-view'){
				var mv=$("div#month-view");
				var st=$("td.false div.data_body",mv);
				st.empty();						    
				var y=this.setting.currentDate.getFullYear();//年份
				var m=this.setting.currentDate.getMonth()+1;//月份
				var day=this.setting.currentDate.getDate();//月天	
				for(var i=0;i<data.length;i++){
					var starty = new Number(data[i].startTime.substring(0,4))
					var startm = new Number(data[i].startTime.substring(5,7))
					var startday = new Number(data[i].startTime.substring(8,10))	
					if (y==starty&&m==startm){
						if (data[i].title){showinfo = data[i].title.substring(0,6)
							if(data[i].title.length>6)showinfo+="..."
						}
						else if(data[i].address){showinfo = data[i].address.substring(0,6)
							if(data[i].address.length>6)showinfo+="..."
						}
						else if(data[i].description){showinfo = data[i].description.substring(0,6)
							if(data[i].description.length>6)showinfo+="..."
						}
						else if(data[i].startTime){showinfo = data[i].startTime.substring(0,10)}
						else if(data[i].endTime){showinfo = data[i].endTime.substring(0,10)}
						else(showinfo = "")

						var t=st.eq(startday-1);
						subcontent = "<div class='newcheckbox'><span class='newbox'><div class='calendar_event' subject='"+data[i].title+"' startTime='"+data[i].startTime+"' endTime='"+data[i].endTime+"' address='"+data[i].address+"' description='"+data[i].description+"' Id='"+data[i].Id+"' alarmType='"+data[i].alarmType+"' isAllDay='"+data[i].isAllDay+"' repeatType='"+data[i].repeatType+"' status='"+data[i].status+"' account='"+data[i].account+"' TimeZone='"+data[i].TimeZone+"'>"+showinfo+"</div></span></div>"
														
						t.append(subcontent);}
				}
				addSelect();	
			}						
		}

		//日历上面追加tip组件。
		ColonCalenader.prototype.processNewOrEditEvent=function(event){
			$("div#tab-container").fadeTo("fast",0.4)
			hasTipFlag = true;
			var $target=$(event.target),pos=$target.offset(),targetW=$target.outerWidth(true),targetH=$target.outerHeight(false);
			//首先判断是否是选中状态要求删除的
			if($target.hasClass('selected')){
				$target.removeClass('selected');
				return;
			}						
			var currentView=$("div.calendar-view:visible"),cid=currentView.attr("id");
			switch (cid){
				 case 'month-view':
				 case 'week-view':
				 var selected=$("div.selected",currentView);
				 break;
			}
			var account = $(this).attr("account")
			var title = $(this).attr("subject")
			var startTime = $(this).attr("startTime")
			var endTime = $(this).attr("endTime")
			var address = $(this).attr("address")
			var description = $(this).attr("description")
			 
			selectobj.title = title
			selectobj.startTime = startTime
			selectobj.endTime = endTime
			selectobj.address = address
			selectobj.description = description
			selectobj.Id = $(this).attr("Id")
			selectobj.alarmType = $(this).attr("alarmType")
			selectobj.isAllDay = $(this).attr("isAllDay")
			selectobj.repeatType = $(this).attr("repeatType")
			selectobj.status = $(this).attr("status")
			selectobj.account = $(this).attr("account")
			selectobj.TimeZone = $(this).attr("TimeZone")

			if($target.hasClass('calendar_event')){	
				if(account!=""){$("#account").text(TransWording['Account']+" : "+account)}
				else($("#account").text(""))
				if (title!=""){$("#title").text(TransWording['Subject']+" : "+title)}
				else{$("#title").text("")}
				if (startTime!=""){$("#startTime").text(TransWording['StartTime']+" : "+startTime)}
				else{$("#startTime").text("")}
				if (endTime!=""){$("#endTime").text(TransWording['EndTime']+" : "+endTime)}
				else{$("#endTime").text("")}
				if (address!=""){$("#address").text(TransWording['Location']+" : "+address)}
				else{$("#address").text("")}
				if (description!=""){$("#description").text(TransWording['Description']+" : "+description)}
				else{$("#description").text("")}
				cc.showMaskWin(340,pos,targetW,targetH);
			}else{
				cc.showMaskWin(340,pos,targetW,targetH);
			}
		}
		
		ColonCalenader.prototype.showMaskWin=function(w,pos,targetW,targetH){
			var d=$(document);
			var mw=$("#maskWin");
			mw.width(w);
			mw.show();
			var h=mw.outerHeight(true);  						
			var rps=position(pos,targetW,targetH,mw.outerWidth(true),h);						
			mw.animate({top:rps[0].top,left:rps[0].left},300);
			var da=$("div#arrow");
			da.get(0).className=(rps[1].lor=='left'?'arrowLeft':'arrowRight');
			da.animate({top:rps[1].top,left:rps[1].left},0);
			function position(pos,targetW,targetH,w,h){
				var displayBlock=$("div#calendar"),dbh=displayBlock.outerHeight(true),dbp=displayBlock.offset();
				var minTop=0,maxTop=dbh-h,$document=$(document),documentW=$document.width(),lor=pos.left-dbp.left>documentW-pos.left-targetW;
				
				var targetPos={},rightDiv=$("div#right"),scrollTop=rightDiv.scrollTop();
				var arrowPos={};
				//计算是在左边显示还是在右边                     	   
				if(lor){
					//targetPos.left=pos.left-w-dbp.left;
					targetPos.left=pos.left-w-dbp.left;
					
					arrowPos.left=w-2;//去掉2像素的边框
					arrowPos.lor='right';
				}else{
					//targetPos.left=pos.left+targetW-dbp.left;
					targetPos.left=pos.left-dbp.left+targetW;
					arrowPos.left=-12;
					arrowPos.lor='left';
				}
				//求的在Y上的位置
				var tempH=targetPos.top=pos.top+targetH/2-h/2-dbp.top;
				arrowPos.top=h/2-8;
				if(tempH<minTop){
					targetPos.top=minTop;
					arrowPos.top-=Math.abs(tempH);
				}
				if(tempH>maxTop){
					targetPos.top=maxTop;
					arrowPos.top+=Math.abs(tempH);
				}
				arrowPos.top-=1;
				return [targetPos,arrowPos];
			}
		}
		 
		//隐藏tip win
		ColonCalenader.prototype.hideTipWin=function(){                         
			var mw=$("#maskWin");mw.fadeOut('fast');
			$(".eventSelected").removeClass('eventSelected');
			hasTipFlag = false;
			$("div#tab-container").fadeTo("fast",1)
		}
		 
		//返回或者新建
		ColonCalenader.prototype.showOrHideForm=function(flag){
			moreyear = moremonth = moreday = moreminute = 0
			morehour = 1
			direction = 'normal'
			var $form=$("div#new-event-form");
			if($form.is(":hidden")&&flag){                            
			  $form.show(); 
			  $("div#calendar").hide();
			}
			if(!flag&&$form.is(":visible")){
				$form.hide(); 
			  $("div#calendar").show(); 
			}   
		}
		
		//打开新建界面时，初始化界面数据
		ColonCalenader.prototype.InitNewData=function(data){
			//编辑时
			if (data){
				$("#newaccount").attr("disabled",false);
				$("#newaccount").val(data.account);
				$("#newaccount").attr("disabled",true);
				$("#newaddress").val(data.address);
				$("#newdescription").val(data.description);
				$("#newsubject").val(data.title);
				$("#newstartDate").val(data.startTime.substring(0,10));
				$("#newstarthour").val(data.startTime[11]=='0'?data.startTime[12]:data.startTime.substring(11,13));
				$("#newstartminute").val(data.startTime[14]=='0'?data.startTime[15]:data.startTime.substring(14,16));
				$("#newendDate").val(data.endTime.substring(0,10));
				$("#newendhour").val(data.endTime[11]=='0'?data.endTime[12]:data.endTime.substring(11,13));
				$("#newendminute").val(data.endTime[14]=='0'?data.endTime[15]:data.endTime.substring(14,16));
				$("select#frequency option").eq(data.repeatType).attr("selected","selected");
			
				//根据保存值设置提醒时间的个数及值
				$("a[name=del_alert]").trigger('click')
				var alarmTime = []
				if (data.alarmType.length>0)alarmTime = data.alarmType.split(',')
				for(i=0; i<alarmTime.length; i++){
					$("a[name=add_alert]").trigger('click')
					temp = $("select[name='alarm']").get(i)
					$("option",temp).each(function(){
						if ($(this).val() == alarmTime[i])
							$(this).attr("selected","selected");
					})
				}

				if (data.isAllDay==1){
					document.getElementById("AllDay").checked = true;
					$("#AllDay").addClass('selected');
					$("#newendhour").attr("disabled",true);
					$("#newendminute").attr("disabled",true);
					$("#newstarthour").attr("disabled",true);
					$("#newstartminute").attr("disabled",true);
				}else{
					document.getElementById("AllDay").checked = false;
					$("#AllDay").removeClass('selected');
					$("#newendhour").attr("disabled",false);
					$("#newendminute").attr("disabled",false);
					$("#newstarthour").attr("disabled",false);
					$("#newstartminute").attr("disabled",false);
				}
				
				//设置频率项的内容及选项
				var d = new Date();
				datestart = $("#newstartDate").val().split('-')
				year0 = datestart[0]
				month0 = datestart[1]
				month_t = month0 - 1
				day0 = datestart[2]
				d.setDate(day0)
				d.setMonth(month_t)
				d.setFullYear(year0)
				week2 = d.getDay()					
				day2 = d.getDate()				
				month2 = d.getMonth()
				num2 = whichWeek(year0,month_t,day2)
				if(week2 == 0 || week2 == 6){
					$('option#everyworkday').hide()	
				}else{
					$('option#everyworkday').show()
				}
				setFrequency(week2,day2,month2,num2);	
				$("select.frequency option[value=data.repeatType]").attr("selected","selected")
				//根据初始值计算开始/结束时间的差距
				lenOfdate($("#newstartDate").val(),$("#newendDate").val())
				lenOftime($("#newstarthour").val(),$("#newstartminute").val(),$("#newendhour").val(),$("#newendminute").val())
			}
			//新建时
			else{
				$("#newaccount").attr("disabled",false);
				$("#newaccount").get(0).selectedIndex = 0
				var d = new Date(); 	
				
				date = $.calendar.formatDate('yy-mm-dd',d)
				hour = d.getHours(); //获取当前小时数(0-23) 
				minute = d.getMinutes(); //获取当前分钟数(0-59) 
				
				$("#newsubject").val("");
				$("#newaddress").val("");
				$("#newdescription").val("");
				$("#newstartDate").val(date);
				$("#newstarthour").get(0).selectedIndex=hour;//设置Select索引值为hour的项选中 
				$("#newstartminute").get(0).selectedIndex=minute;
				
				if ((hour+1) == 24){
					var temp_day;
					temp_day = addDate(date,1)
					$("#newendDate").val(temp_day)
					$("#newendhour").get(0).selectedIndex=0;
					$("#newendminute").get(0).selectedIndex=minute;	
				}
				else{
					$("#newendhour").get(0).selectedIndex=(hour+1);//设置Select索引值为1的项选中 
					$("#newendminute").get(0).selectedIndex=minute;
					$("#newendDate").val(date);
				}

				document.getElementById("AllDay").checked = false;
				$("#newendhour").attr("disabled",false);
				$("#newendminute").attr("disabled",false);
				$("#newstarthour").attr("disabled",false);
				$("#newstartminute").attr("disabled",false);
				
				//初始化时先触发所有删除按钮的点击删除所有项目，再添加一个
				$("a[name='del_alert']").each(function(){
					$(this).trigger("click")	
				});
				$("a[name='add_alert']").trigger("click")
				$("#frequency").get(0).selectedIndex = 0
				
				//初始化设置频率目录项的内容
				week1 = d.getDay()
				day1 = d.getDate()
				month1 = d.getMonth()
				num1 = whichWeek(d.getFullYear(),month1,day1)
				if(week1 == 0 || week1 == 6){
					$('option#everyworkday').hide()	
				}else{
					$('option#everyworkday').show()
				}
				setFrequency(week1,day1,month1,num1);
			}

			$("#newendhour,#newendminute").change(function(){
				end_date = $("#newendDate").val()
				start_date = $("#newstartDate").val()
				end_minute = parseInt($("#newendminute").val())
				end_hour = parseInt($("#newendhour").val())
				start_minute = parseInt($("#newstartminute").val())
				start_hour = parseInt($("#newstarthour").val())
				if(start_date==end_date){
					if(((start_hour==end_hour)&&(end_minute<start_minute)) || (end_hour<start_hour)){	
						direction = 'add'
						newenddate = adjustDay(start_date,0,0,0)
						$("#newendDate").val(newenddate)
					}
				}
				lenOftime(parseInt($("#newstarthour").val()),parseInt($("#newstartminute").val()),parseInt($("#newendhour").val()),parseInt($("#newendminute").val()))
				lenOfdate($("#newstartDate").val(),$("#newendDate").val())
			})
		
			oldstarthour = $("#newstarthour").val()
			$("#newstarthour,#newstartminute").change(function(){
				adjustTime(parseInt($("#newstarthour").val()),parseInt($("#newstartminute").val()),morehour,moreminute)
				$("#newendhour").get(0).selectedIndex = EndHour
				$("#newendminute").get(0).selectedIndex = EndMinute	
				newenddate = adjustDay($("#newstartDate").val(),moreyear,moremonth,moreday)
				$("#newendDate").val(newenddate)
			})	
		}
		//通过tip删除按钮删除
		ColonCalenader.prototype.deleteViewevent=function(){
			if(!delFlag) return false; 
			art.dialog({
				title: TransWording['DiagTitle'],
				content:TransWording['DiagContent'],
				okVal: TransWording['DiagOK'],
				cancelVal: TransWording['DiagCancel'],
				icon: "question",
				lock: true,
				background:'#fff',
				opacity: 0.7,
				ok:function(){
						var data = {"CalenderID":[],"RepeatDealType":[],"account":[]};
						data.account.push(selectobj.account)
						data.CalenderID.push(selectobj.Id)
						data.RepeatDealType.push((selectobj.repeatType==0)? "selected":"all");
						$.post("/Calendar/DelCalendar",data,function(){})
					},
				cancel: true
			})
		}
		
		//删除掉选择的事项//通过复选框删除
		ColonCalenader.prototype.deleteSelectedEvent=function(){
			if(!delFlag || hasTipFlag) return false; 
			//首先判断视图类型,是月视图，周视图，还是天视图，还是全视图。
			var calenderID
			var data = {"CalenderID":[],"RepeatDealType":[], "account":[]}
			var currentView=$("div.calendar-view:visible"),cid=currentView.attr("id");
			switch (cid){
				case 'month-view':
				case 'week-view':
					art.dialog({
						title: TransWording['DiagTitle'],
						content:TransWording['DiagContent'],
						okVal: TransWording['DiagOK'],
						cancelVal: TransWording['DiagCancel'],
						icon: "question",
						lock: true,
						background:'#fff',
						opacity: 0.7,
						ok:function(){
							$("div.newcheckbox").find("input:checked").parents("div.select").siblings("div.calendar_event").each(function(){
								data.CalenderID.push($(this).attr("Id"))
								data.account.push($(this).attr("account"))
								if($(this).attr("repeatType") == 0){data.RepeatDealType.push('selected')}										
								else {data.RepeatDealType.push("all")}
							})
							$.post("/Calendar/DelCalendar",data,function(){})
						},
						cancel: true
					})		
					break;
				case 'day-view':
				case 'full-view':
					var selected=$(":checked",currentView);
					art.dialog({
						title: TransWording['DiagTitle'],
						content:TransWording['DiagContent'],
						okVal: TransWording['DiagOK'],
						cancelVal: TransWording['DiagCancel'],
						icon: "question",
						lock: true,
						background:'#fff',
						opacity: 0.7,
						ok:function(){
							selected.each(function(){
									data.CalenderID.push($(this).attr("id"))
									data.account.push($(this).attr("account"))
									if($(this).attr("repeattype") == 0){data.RepeatDealType.push('selected')}
									else {data.RepeatDealType.push("all")}
							})
							$.post("/Calendar/DelCalendar",data,function(){})
						},
						cancel: true
					})
					break;
			}
		}

		ColonCalenader.prototype.hideMaskWin=function(){$("#maskWin").hide();}
		//隐藏menu菜单
		ColonCalenader.prototype.hideMenu=function(){
			if(this.menuClosing){$("div#menu").hide('normal');}
		}
		//显示一个提示信息
		ColonCalenader.prototype.alertMsg=function(text){
			var msg=$("#msg");
			$("span",msg).html(text);
			$("#msg").slideDown(600,function(){
				setTimeout('$("#msg").slideUp("fast")',1500);
			});
		}                    
	}
}


	function selectedAllEvent(){
		var currentView=$("div.calendar-view:visible"),cid=currentView.attr("id"),$this=$(this);
		switch (cid){
			case   'month-view':
			case   'week-view':                              
				//月视图中我们对于事项，加样式表示选择
				var selecteds=$("div.calendar_event",currentView);
				if(!$this.data(cid)){ 
					$this.data(cid,true);
					cc.alertMsg("选中视图中的"+selecteds.length+"条记录。");
					$('.newcheckbox').find('div.calendar_event').after(inCheckbox);
					$('.select span').addClass('selected111')
				}else{
					if(normal) cc.alertMsg("取消视图中的"+selecteds.length+"条记录。");
					$this.data(cid,false);
					$('div.newcheckbox').find('.select').remove()
				}
				break;
			case 'day-view':
			case 'full-view':
				var selecteds=$(":checkbox",currentView);
				if(!$this.data(cid)){
					selecteds.attr("checked",true);
					$this.data(cid,true);
					cc.alertMsg("选中视图中的"+selecteds.length+"条记录。");
				}else{
				   selecteds.attr("checked",false);  
					$this.data(cid,false);
					 if(normal) cc.alertMsg("取消视图中的"+selecteds.length+"条记录。");
				}
				break;
		}
	}

	function selectTreeNode(zTreeObj,pid,subid){
		var parentNode = zTreeObj.getNodeByParam("pid",pid,null);
		var subnode = zTreeObj.getNodeByParam("id",subid,parentNode);
		zTreeObj.expandNode(parentNode,true,true,true,false);
		zTreeObj.selectNode(subnode,false); 
		if (currentTreeView.subid == "0"){view = "month-view"}
		else if (currentTreeView.subid == "1"){view = "week-view"}
		else if (currentTreeView.subid == "2"){view = "day-view"}
		else if (currentTreeView.subid == "3"){view = "full-view"}
		cc.updateView(null, view, pid);
	}
				
	function zTreePackage(){
		this.setting = "";
		if(typeof this.init !="function"){
			zTreePackage.prototype.init=function(){
				this.zTreeObj = $.fn.zTree.init($("#left-panel-tree"), {callback:{onClick:this.OnTreeSelected}},zNodes);
				if(zNodes.length > 0){
					selectTreeNode(this.zTreeObj, currentTreeView.pid, currentTreeView.subid);
				}
				return this;
			}
			zTreePackage.prototype.OnTreeSelected=function(event,treeId,treeNode,clickFlag){
				if (!treeNode.isParent){
					var node = treeNode.getParentNode();
					currentTreeView.pid = node.pid
					currentTreeView.subid = treeNode.id
					cc.updateView(event,treeNode.viewName,node.pid);
					var data = {};
					data.pid = [];
					data.subid = [];
					data.pid.push(node.pid)
					data.subid.push(treeNode.id)
					$.post("/Calendar/OnTreeSelected",data,function(){ } )
				}		            
			}
		
			zTreePackage.prototype.addNodes=function(zNodes){
				for(i=0;i<zNodes.length;i++) 
					this.zTreeObj.addNodes(null,zNodes[i],false);
			}
			zTreePackage.prototype.clearNodes=function(){
				nodes = this.zTreeObj.getNodes()
				while(nodes.length > 0){
					if (nodes[0].isParent){
						this.zTreeObj.removeNode(nodes[0],false);
					}
				}
			}
			zTreePackage.prototype.deleteNodes=function(ids){
				for(i=0;i<ids.length;i++){
					var treeNode = this.zTreeObj.getNodeByParam("pid",ids[i],null)
					this.zTreeObj.removeNode(treeNode,false);
				}
			}
			zTreePackage.prototype.updateNodes=function(treeNodes){
				for(i=0;i<treeNodes.length;i++)
					this.zTreeObj.updateNode(treeNodes[i],false);	
			}					
		}
	}

	//动态增加复选框
	function addSelect(){
		$('div.newcheckbox').hover(
			function(){
				if($(this).find('input').length == 0){ //判断是否已经存在div.select
				$(this).find('div.calendar_event').after(inCheckbox);
			}
			$('.select span').hover(function(){
				$(this).addClass('hover');	
			}, function(){
				$(this).removeClass('hover');
			})
		},	function(){
			var len = $(this).parents('div.calendar-view:visible table.calendar-month,div.calendar-view:visible table.calendar-week ').find("input:checked").length;	
			if(len == 0){
				$(this).parents('div.calendar-view:visible table.calendar-month,div.calendar-view:visible table.calendar-week ').find('div.newcheckbox').find('.select').remove();
			}		
		}
		)
		$('.select span').live('click',function(){	
			if($(this).hasClass('selected111')){
				$(this).removeClass('selected111')
				$(this).siblings('input')[0].checked = false;
				var len = $(this).parents('div.calendar-view:visible table.calendar-month,div.calendar-view:visible table.calendar-week ').find('input:checked').length	
				if(len == 0 ){				
					$(this).parents('div.calendar-view:visible table.calendar-month,div.calendar-view:visible table.calendar-week ').find('.select').remove()
					delFlag = false;
					editFlag = false;
				}
			}
			else{
				$(this).addClass('selected111')
							
				$(this).siblings('input')[0].checked = true;
				$('div.calendar-view:visible table.calendar-month,div.calendar-view:visible table.calendar-week ').find('div.newcheckbox').each(function(index){
						 if($(this).find('input').length == 0){//判断是否已经存在div.select
							$(this).find('div.calendar_event').after(inCheckbox);	
						}
					})
			}
			var selectall = $(".select input:checked").length;
			delFlag = selectall > 0 ? true : false
			editFlag = selectall==1 ? true : false
			if(delFlag){
				$('a[name="deleteEvent"]').removeClass('disabled')
			}else{
				$('a[name="deleteEvent"]').addClass('disabled')
			}
			
			if(editFlag){
				$('a[name="editEvent"]').removeClass('disabled')
			}else{
				$('a[name="editEvent"]').addClass('disabled')
			}

			var len = $("div.calendar-view:visible .calendar_event").length
			if(len == selectall){
				$('.selectAll a').addClass('selected')
				$('.selectAll a').siblings(':checkbox')[0].checked = true;
			}else{
				$('.selectAll a').removeClass('selected')
				$('.selectAll a').siblings(':checkbox')[0].checked = false;
			}
			stopPropagation()
		})
	}
	
//定义日视图和全视图中复选框按钮按下的动作
	function checkboxclick(){
		$("input[name='id']").live('click',function(){
			if($(this)[0].checked == true){
				delFlag = true;	
			}else{
				if($("div.calendar-view:visible input:checked").length == 0){delFlag = false;}	
			}
			var selectall = $("div.calendar-view:visible input:checked").length;
			delFlag = selectall > 0 ? true : false
			editFlag = selectall==1? true: false
			if(delFlag){$('a[name="deleteEvent"]').removeClass('disabled')}
			else{$('a[name="deleteEvent"]').addClass('disabled')}
			
			if(editFlag){$('a[name="editEvent"]').removeClass('disabled')}
			else{$('a[name="editEvent"]').addClass('disabled')}
			
			var len = $("div.calendar-view:visible input").length
			if(len == selectall){
				$('.selectAll a').addClass('selected')
				$('.selectAll a').siblings(':checkbox')[0].checked = true;			
			}else{
				$('.selectAll a').removeClass('selected')
				$('.selectAll a').siblings(':checkbox')[0].checked = false;
			}
		})
	}

	

	function whichWeek(year,month,day){
		var num;
		if(day <= 7)
			num = 1;
		else if(day <= 14)
			num = 2;
		else if(day <= 21)
			num = 3;
		else if(day <= 28)
			num = 4;
		else 
			num = 5;								
		//根据年月判断是否属于本月最后一周
		temp_day = $.calendar.getMonthDays(year,month)
		if(((temp_day==31)&&(25<=day)) || ((temp_day==30)&&(24<=day)) || ((temp_day==29)&&(23<=day)) || ((temp_day==28)&&(22<=day)))
			lastWeek = true;
		else
			lastWeek = false;
		return num
	}
												
	//根据日期值设置频率项的内容							
	function Frequency(date){
		var d = new Date();
		datestart = date.split('-')
		year0 = datestart[0]
		month0 = datestart[1]
		month_t = month0 - 1
		day0 = datestart[2]
		d.setDate(day0)
		d.setMonth(month_t)
		d.setFullYear(year0)
		week2 = d.getDay()					
		day2 = d.getDate()					
		month2 = d.getMonth()
		num2 = whichWeek(year0,month_t,day2)
		setFrequency(week2,day2,month2,num2);
	}	
	
	//屏蔽backspace按键
	function KeyDownFunction(){
		if (typeof window.event != 'undefined') {  
		    document.onkeydown = function() {  
				var type = event.srcElement.type;  
				var code = event.keyCode;  
				var id = event.srcElement.id;
				return ((code != 8 && code != 13) ||  
					 (type == 'text' && code != 13 && id != "newstartDate" && id != "newendDate") ||  
					 (type == 'textarea') ||  
					 (type == 'submit' && code == 13))  
		    }  
		} else { // FireFox/Others  
		   document.onkeypress = function(e) {  
				var type = e.target.localName.toLowerCase();  
				var code = e.keyCode;  
				if ((code != 8 && code != 13) ||  
					(type == 'input' && code != 13) ||  
					(type == 'textarea') ||  
					(type == 'submit' && code == 13)) {  
					return true;  
				} else {  
					return false ;  
				}  
		    }  
		} 
	}
	function adjustTime(hour,minute,moreH,moreM){
		minute+=moreM
		if(minute<0){
			minute+=60
			hour-=1
		}
		else if(minute>59){
			minute-=60
			hour+=1
		}
		hour+=moreH
		if(hour<0){
			hour+=24
			direction = "sub";
		}
		else if(hour>23){
			hour-=24
			direction = "add";
		}
		else
			direction = "normal";
		EndHour = hour
		EndMinute = minute
		return
	}
	function addDate(date,num){
		var temp = date.split('-')
		if(temp[2][0]=='0')temp[2]=temp[2][1]
		day = parseInt(temp[2])
		if(temp[1][0]=='0')temp[1]=temp[1][1]
		month = parseInt(temp[1])
		year = parseInt(temp[0])
		var dayOfmonth = $.calendar.getMonthDays(year,month-1)
		if ((day+num) > dayOfmonth){
			day = day + num - dayOfmonth
			month+=1
			if (month == 13){
				year+=1
				month = 1
			}
		}
		else{day+= num}
		var temp_month = month
		var temp_day = day
		if (month<10){temp_month = '0'+ month}
		if (day<10){temp_day = '0' + day}
		date = year + '-' + temp_month + '-' + temp_day
		return date
	}
	function dataTranslate(date){
		var s = date.split('-')
		if(s[1][0] == '0')
			s[1] = s[1][1]
		if(s[2][0] == '0')
			s[2] = s[2][1]
		s[1] -= 1
		var d = new Date;
		d.setFullYear(s[0],s[1],s[2])
		return d
	}

/****JL******/

