/* Author: yangzeming
 * Date: 2013-12-10
 * Desc: 简单的日历组件
 */
define("component/calendar",function (require, exports, module) { 
    
	var bc = require("./basecalendar");
	
	var calendar = bc.extend({
		initial : function(options){
			var defaultOp = {
				con : "",
			    input : "",
				calTemplate : "",
				titleTemplate:"<div></div>",
				conTemplate : '<div  class="ui-calendar" ><div class="ui-calendar-title" data-role="title"></div><div data-role="calendar" class="ui-calendar-body"></div><div class="ui-calendar-bottom" data-role="bottom"></div></div>',
				startMonday : false,
				calStyle : {
					width : 732//,height:450
				},
				skin : "greencal",
				titleHeight : 40,
				tbheight: 267,
				data :{},
//				data : {
//					"d2014-06" :[
//					     {
//					    	 "name" : "恭城桃花节",
//					    	 "pic"  : "http://webmap1.map.bdimg.com/maps/services/thumbnails?width=80&height=80&quality=95&align=middle,middle&src=http://hiphotos.baidu.com/lvpics/pic/item/6159252dd42a28347b7307c15bb5c9ea14cebf26.jpg",
//					    	 "desc" : "活动简介",
//					    	 "address" : "举办地址",
//					    	 "starttime" : "2014-06-05",
//					    	 "endtime" : "2014-06-10",
//					    	 "xid" : "11231123"
//					    	 
//					     }
//					 ]
//					
//				},
				config:{},
				date : {},
				imageGrid : "green",
				// 格子的template
				gridTemplate : 'calBoxCon',
				//rows : 6,
				currentDate : new Date()
				
			};
			this.options = $.extend(true,{},defaultOp,options);
			this._eventStack = {};
			this.bt = baidu.template;
			this.$input = $(this.options.input);
			this.config = $.extend(true,{},this.config,this.options.config);
			this.date = $.extend(true,{},this.date,this.options.date);
			this.$con = $(this.options.conTemplate);
			if(this.options.skin!="")
			{
				this.$con.addClass(this.options.skin);
			}
			this.$con.css(this.options.calStyle);
			this.gridTemplate = this.options.gridTemplate;
			$(this.options.con).addClass(this.options.skin).append(this.$con);
			this.currentDate = this.options.currentDate;
			this.renderView(this.currentDate);
			
		
		},
		show : function(target,position){
			this.$con.show().position({
					my: "left top",
                    at: "left bottom",
                    of: target||this.$input
				});
		
		},
		hide : function(){
			this.$con.hide();
		
		},
		renderView : function(date){
			date = (date || this.currentDate);
			this.renderTitle(date);
			this.renderCal(date);
			
			this.bindEvent();

		
		},
		bindEvent : function(){
			var self = this;
			this.$con.find('[data-role="pm"]').click(function(){
				self.prevMonth();
			
			});
			
			this.$con.find('[data-role="nm"]').click(function(){
				self.nextMonth();
			
			});
			this.$con.find('[data-role="py"]').click(function(){
				self.prevYear();
			
			});
			this.$con.find('[data-role="ny"]').click(function(){
				self.nextYear();
			
			});
			this.$con.delegate('[data-role="calbox"]',"mouseenter",function(){
				 $(this).addClass("cal-box-hover");
				 $(this).closest("tr").addClass("ui-cal-table-hover");
			
			});
			this.$con.delegate('[data-role="calbox"]',"mouseleave",function(){
				 $(this).removeClass("cal-box-hover");
				  $(this).closest("tr").removeClass("ui-cal-table-hover");
			
			});
			this.$con.delegate('[data-hrole]',"mouseenter",function(){
				 var data = $(this).data("hrole");
				 if(data!="hover"){
					$(this).addClass("cal-padding-hover");
				 }
				 $(this).addClass("cal-all-hover");
				
			
			});
			this.$con.delegate('[data-hrole]',"mouseleave",function(){
				 $(this).removeClass("cal-all-hover");
				 var data = $(this).data("hrole");
				  if(data!="hover"){
					$(this).removeClass("cal-padding-hover");
				 }
			
			});
			this.$con.delegate('[data-role="calMenu"]',"mouseleave",function(){
				  $(this).removeClass("cal-Menu-hover");
				 // $(this).closest("tr").removeClass("ui-cal-table-hover");
			
			});
			this.$con.delegate('[data-role="mgotoday"]',"mouseenter",function(){
				
				 $(this).addClass("cal-today-hover");
				
			
			});
			this.$con.find('[data-role="mgotoday"]').click(function(){
				//self.hideMenu(self.$title,function(){
						self.goToday();
				 // });
			
			});
			this.$con.find('[data-role="todaybtn"]').click(function(){
				
				self.goToday();
			});
			this.$con.delegate('[data-role="mgotoday"]',"mouseleave",function(){
				 $(this).removeClass("cal-today-hover");
			});
		    this.$con.delegate('[data-role="shousuo"]','click',function(){
		    		var type = $(this).data("fold"),
		    		     that = $(this),
		    		    $body = self.$con.find('[data-role="calendar"]');
		    		if(type=="no"){
		    			$body.slideDown(300,function(){
		    				that.html("收缩");
		    			});
		    			
		    			$(this).data("fold","yes");
		    			
		    		}else{
		    			
		    			$body.slideUp(300,function(){
		    				
		    				that.html("展开");
		    			});
		    			$(this).data("fold","no");
		    		}
		    		
		    	
		    	
		    });
			this.$con.find('[data-role="tyear"]').click(function(){
				if($('div[data-role="hyDiv"]').is(":hidden")){
					var spanTop = $(this).position().top+34;
					var spanLeft = $(this).position().left;
					$('div[data-role="hyDiv"]').css("top",spanTop);
					$('div[data-role="hyDiv"]').css("left",spanLeft);
					$('div[data-role="hyDiv"]').slideDown();
				}else{ $('div[data-role="hyDiv"]').slideUp();}
				return false;
			});
			
			this.$con.find('[data-role="tmonth"]').click(function(){
				if($('div[data-role="hmDiv"]').is(":hidden")){
					var spanTop = $(this).position().top+34;
					var spanLeft = $(this).position().left+14;
					$('div[data-role="hmDiv"]').css("top",spanTop);
					$('div[data-role="hmDiv"]').css("left",spanLeft);
					$('div[data-role="hmDiv"]').slideDown();
				}else{ $('div[data-role="hmDiv"]').slideUp();}
				return false;
			});
			
			this.$con.find('[data-role="hyDiv"] ul li').click(function(){
				  var liVal = $(this).text();
				  $('[data-role="tyear"]').html(liVal);
				  self.selectYChangeVal();
				  $('[data-role="hyDiv"]').hide();
			});
			
			this.$con.find('[data-role="hmDiv"] ul li').click(function(){
				  var liVal = $(this).text();
				  $('[data-role="tmonth"]').html(liVal);
				  self.selectMChangeVal();
				  $('[data-role="hmDiv"]').hide();
			});
			
			
			
			/*跳转到有活动的相应页面*/
			this.$con.delegate('[data-role="calbox"]',"click",function(){
				var that = $(this),
					date = that.data("date");
				if(that.hasClass("calendar-before")||that.hasClass("calendar-after")){
					
					var std = self.strToDate("%Y-%m-%d"),
					    sd = std(date);
					self.moveto(self.currShowDate, sd);
					
				}
				self.trigger("clickGrid",that.data("date"),that.data("activeInfo"));//$(this).data("hdid"),$(this).data("hdmc"),$(this).data("hdjj"),$(this).data("hddt"),$(this).data("hdst"),$(this).data("hdet"));
				
		 });


		},
		// 点击其他地方关闭日历
		clickClose : function(type,t){
			var self = this;
			$(document).on("click."+type+"",function(e){
				  var el = e.target || e.srcElement,
					  target  = $(el);
				  // 处理上传视频
				  if(target.closest(t).length == 0&&("#"+target.attr("id"))!=self.options.input){
					   
					 self.hide();
				  }
				
			 }); 
		
		},
		showMenu : function(that,callback){
			var self = this;
			self.$menu.css("top","-100%").show();
			TweenLite.to(self.$menu, .3, {top:"0%",ease:Power1.easeOut,onComplete:function(){callback&&callback();}});
			that.data("show",true);
		},
		hideMenu : function(that,callback){
			var self = this;
			TweenLite.to(self.$menu, .3, {top:"-100%",ease:Power1.easeOut,onComplete:function(){callback&&callback();}});
					that.data("show",false);
		},
		
		goToday : function(){
			var date = new Date();
			date = this.datePart(date);
			this.moveto(this.currShowDate,date);
		
		},
		selectYChangeVal:function(){
			
			var selectCulVal = $('[data-role="tyear"]').html();
			var sbVal = selectCulVal.substring(0,4);
			var cur = this.datePart(this.currShowDate);
			var currShowDate = this.currShowDate;
			var month = currShowDate.getMonth();
			var date = currShowDate.getDate();
			var newDate = new Date(sbVal,month,date);
		    this.moveto(cur,newDate);
		},
		selectMChangeVal:function(){
			var selectCulVal = $('[data-role="tmonth"]').html();
			var sbVal = selectCulVal.substring(0,2);
			var cur = this.datePart(this.currShowDate);
			var currShowDate = this.currShowDate;
			var year = currShowDate.getFullYear();
			var date = currShowDate.getDate();
			var newDate = new Date(year,sbVal-1,date);
		    this.moveto(cur,newDate);
		},
		nextYear: function(){
			var cur = this.datePart(this.currShowDate),
				next = this.add(cur,1,"year");
			this.moveto(cur,next);
		},
		prevYear: function(){
			var cur = this.datePart(this.currShowDate),
				next = this.add(cur,-1,"year");
			this.moveto(cur,next);
		},
		renderTitle : function(){
			//年输入框
			var _inputY = '<div  data-role="tyear" class="yInput" id="yInput" ></div>';
			var _imgYHtml	='';
			//月输入框
			var _inputM = '<div  data-role="tmonth" class="mInput" id="mInput" ></div>';
			var _imgMHtml	='';
			
			//年隐藏div
			var _hyDiv = '<div class="hyDiv" id="hyDiv" data-role="hyDiv"><ul>';
				for(var i=this.currentDate.getFullYear()-30;i<=this.currentDate.getFullYear()+10;i++){
					_hyDiv+='<li>'+i+'</li>';
				}
				_hyDiv+='</ul></div>';
				//月隐藏div
				var _hmDiv = '<div class="hmDiv" id="hmDiv" data-role="hmDiv"><ul>';
					for(var i=1;i<=12;i++){
						if(i<10){
							_hmDiv+='<li>0'+i+'月</li>';
						}else{
							_hmDiv+='<li>'+i+'月</li>';
						}
					}
					_hmDiv+='</ul></div>';
					
			var _html = "";
			_html +='<div class="calendar-btn cal-btn-py" style="display:none;" data-hrole="hover" data-role="py"></div>'
			       + '<div class="calendar-btn cal-btn-pm"  data-role="pm"></div>'
				   + '<div class="calendar-btn cal-btn-ny"  style="display:none;" data-role="ny"></div>'
				   + '<div class="calendar-btn cal-btn-nm"  data-role="nm"></div>'
				   +'<div class="cal-btn-ds"  data-role="ds"><div class="year_month_div">';
		
			_html +=_inputY+_imgYHtml+_inputM+_imgMHtml+'</div><div  data-role="mgotoday" class="cal-gotoday-btn">返回今日</div><div data-role="shousuo" class="cal-shousuo">收缩</div></div>';
			this.$con.find('[data-role="title"]').html(_html).after(_hyDiv).after(_hmDiv);
		
		},
		
		renderCal : function(date){
			this.$titleYear = this.$con.find('[data-role="tyear"]');
			this.$titleMonth = this.$con.find('[data-role="tmonth"]');
			this.$con.find('[data-role="calendar"]').html(this.genericCalendar(date));
			//alert(this.dateToStr("%Y年%m月")(date));
			
			this.$titleYear.html(this.dateToStr("%Y")(date));
			this.$titleMonth.html(this.dateToStr("%m月")(date));
			//alert(this.dateToStr("%m")(date));
		
		},
		// 日历滑动动画
		moveto : function(from,to){
			// 首先要判断下from和to的大小
			this.datePart(from);
			this.datePart(to);
			
			var $body = this.$con.find('[data-role="calendar"]'),
				$t = $body.children("table:first"),
				fromBody = this.genericCalendar(from),
				toBody = this.genericCalendar(to),
				fAnimBody = $('<div></div>').html(fromBody),
				tAnimBody = $('<div></div').html(toBody),
				ml = this.options.calStyle.width,
				mt = this.options.tbheight,
				fop = {
					"position" : "absolute",
					"top" : "0px",
					"width" : "100%"
					//"marginLeft" : "-200px",
					//"left" :"100%"

				},
				top = {
					"position" : "absolute",
					"top" : "0px",
					"width" : "100%"
					//"left" :"100%"

				},
				anim = {};
			var count=0,self = this;
			this.$con.find('[data-role="tyear"]').html(this.dateToStr("%Y")(to));
			this.$con.find('[data-role="tmonth"]').html(this.dateToStr("%m月")(to));
			if(from==to){
				$body.html(toBody);
				self.trigger("changeView",self.datePart(to));
			}else {
				anim = {
					
					ease:Power1.easeOut,onComplete:function(){
					$body.html(toBody);
					self.t1 = null;
				}}
				var dir = "left",
					fy = from.getFullYear(),
					ty = to.getFullYear();
					
				if(from>to){   //marginLeft:"-400px",
					// 还需要判断年限

					fy==ty ?( $.extend(fop,{"marginLeft" : ml+"px","left" : "-100%"}), anim["marginLeft"] = 2*ml+"px", $.extend(top,{"left" : "-100%"}), dir = "right") : ($.extend(fop,{"marginTop" : mt+"px","top" : "-100%"}), anim["marginTop"] = 2*mt+"px", $.extend(top,{"top" : "-100%"}), dir = "down");
					
			
				}else{
					fy==ty ? ($.extend(fop,{"marginLeft" : "-"+ml+"px","left" : "100%"}), anim["marginLeft"] = "-"+2*ml+"px", $.extend(top,{"left" : "100%"}), dir = "left")  :  ($.extend(fop,{"marginTop" : "-"+mt+"px","top" : "100%"}), anim["marginTop"] = "-"+2*mt+"px", $.extend(top,{"top" : "-100%"}),dir = "up");
				
				}
				
				fAnimBody.css(fop);
				tAnimBody.css(top);
				$t.css("visibility","hidden");
			
				
				
				var getOp = function(type){
					var fun = ""
					switch (type)
					{
						case "left" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginLeft").replace("px",""),10))-ml)/ml*100;return {"left":dur+"%"}';break;
						case "right" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginLeft").replace("px",""),10))-ml)/ml*100;return {"left":"-"+dur+"%"}';break;
						case "up" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginTop").replace("px",""),10))-mt)/4;return {"top":dur+"%"}';break;
						case "down" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginTop").replace("px",""),10))-mt)/4;return {"top":"-"+dur+"%"}';break;
					
					}
					return new Function("fAnimBody","ml","mt",fun);
					
				
				};
				var fu = getOp(dir);

				
				if(this.t1&&this.t1!=null){
					$body.append(fAnimBody).append(tAnimBody);
					this.t1.to([fAnimBody],.3,anim);
					return;
				}else{
					$body.append(fAnimBody).append(tAnimBody);
					this.t1 = new TimelineLite({onUpdate:function(){
						var dur = fu(fAnimBody,ml,mt);
						tAnimBody.css(dur);
				
					},onComplete:function(){
						
						self.trigger("changeView",self.datePart(to));
						
					}});
					this.t1.to([fAnimBody],.3,anim);
				}

				
			}
			
		},
		getLunar : function(sd){
			
			var cld_day = new Lunar(sd),
		        lunar = cld_day.day == 1
			? (cld_day.isLeap ? '闰' : '')
					+ cld_day.month
					+ '月'
					+ (monthDays(cld_day.year,
							cld_day.month) == 29
							? '小'
							: '大')
			: cDay(cld_day.day);
			return lunar;
			
		},
		// 绘制日历月视图
		genericCalendar : function(date){
			var md = this.monthStart(new Date(date.valueOf())),
				ed = this.add(md,1,"month"),
				sd = this.weekStart(new Date(md.valueOf())),
				curr = this.datePart(this.currentDate);
			this.currShowDate = md;
			var monthDay = this.dateToStr("%j"),
				dstr = this.dateToStr("%Y-%m-%d");
			var rows=6;//Math.ceil(Math.round((ed.valueOf()-sd.valueOf()) / (60*60*24*1000) ) / 7),
				height = this.options.tbheight/rows,
				width = (1/7)*100+"%",
				ml = this.options.calStyle.width/7+"px",
				_html = "";
			_html +='<div class="calendar-header clearfix" data-role="chead">';
			var titleWeek = "cal-title-week";
			if(this.options.startMonday)
				for(var i=0;i<7;i++){
					_html+='<span  style="height:'+this.options.titleHeight+'px;width:'+ml+';">'+this.date.day_full[i]+'</span>';
				}
			else{
				_html+='<span class="'+titleWeek+'" style="height:'+this.options.titleHeight+'px;width:'+ml+';">'+this.date.day_full[6]+'</span>';
				for(var i=0;i<6;i++){
					_html+='<span class="'+(i==5?titleWeek:"")+'" style="height:'+this.options.titleHeight+'px;width:'+ml+';">'+this.date.day_full[i]+'</span>';
				}
				
			}
			_html +='</div>';
			 _html += '<table>';

			// 获取农历
			 
			 var gt = this.gridTemplate;
			
			for(var i=0;i<rows;i++){
				var _t = '<tr>';
				for(var j=0;j<7;j++){
					var calClass = 'calendar-normal',
						weekClass= '';
					
					// 方案一：会显示每一天的 活动 var re = this.getActiveByDay(sd);
					// 换成方案二的活动加载 ，即格子先画出来，加载活动后去重绘格子
					var lunar = this.getLunar(sd); 
							
					var boxContent = '',
					    boxData = {
							//	active : re,
								lunar : lunar,
								type : 'normal'
							};
					var nday = sd.getDay();
					
					if (nday === 0) {
						nday = 7;
					}
					if(nday==6||nday==7){
						
						weekClass = " cal-week"
					}
					if(sd<md){
						calClass = 'calendar-before '+ weekClass+"_before";
					
					}else if (sd>=ed){
						calClass='calendar-after '+ weekClass+"_after";
					}
					else if (sd.valueOf()===curr.valueOf()){
							calClass='calendar-now '+ weekClass+"_now";
					}else{
						
						calClass += weekClass; 
					}
					
					//calClass+=" "+weekClass;
					boxData["calClass"] =calClass;
					boxData["sdstr"] = monthDay(sd);
					boxData['dstr'] = dstr(sd);
					boxData['sd'] = sd;
					boxData['height'] = height;
					boxData['width'] = width;
					
					
					_t+='<td style="height:'+height+'px;width:'+width+';">';
					_t+='<div  class="calendar-box '+calClass
					+'" data-role="calbox" style="height:'+height+'px;position:relative;width:'+ml+'" data-date="'+dstr(sd)
					+'" >'
					+ '<div class="cal-day-text">'+monthDay(sd)+'</div>'
					+ '<div class="cal-day-lunar">'+lunar+'</div>'
					
					+'</div>';
					
					_t+='</td>';
					sd=this.add(sd,1,"day");
				}
				_t+='</tr>'
				_html+=_t;
			
			}
			_html +='</table>';
			return _html;
				
		},
		addData : function(data){
			 this.options.data = $.extend(true,{},this.options.data,data);
			
		},
		addActiveByMonth : function(data){
			var date = this.datePart(this.currShowDate),
				dstr = this.dateToStr("%Y-%m"),
				monthDay = this.dateToStr("%j"),
				md = this.datePart(new Date(date.valueOf())),
				op = "d"+dstr(md);
			data&&this.addData(data);
			var mdata = this.options.data[op];
			if(mdata&&mdata.length>0){
				for(var i=0,len=mdata.length;i<len;i++){
					var da = mdata[i],
						std = this.strToDate("%Y-%m-%d"),
						sd = std(da.starttime);
						//ed = std(da.endtime);
					// 只显示其实的日期
					var  gcon = this.$con.find('[data-date="'+da.starttime+'"]'),
						_html = "",
						lunar = this.getLunar(sd);
					if(this.options.imageGrid=="green"){
						_html +=  '<div class="cal-day-text">'
							  +monthDay(sd)+'</div>'
						      + '<div class="cal-day-lunar">'+lunar+'</div>'
						      + '<div class="cal-image-grid"><img style="width:100%;height:100%;" src="'+da.pic+'" /></div>';
					}else{
						_html += '<img style="width:100%;height:100%;" src="'+da.pic+'" />'
						 	  +'<div class="cal-day-image">'
						      +da.name+'</div>';
						
						
					}
					var $html = $(_html);
					gcon.data("activeInfo",da);
					gcon.html($html);
					
					
				}
				
			}else{
				
				return false;
			}
			
		},
		getActiveByDay : function(date){
			var dstr = this.dateToStr("%Y-%m");
				md = this.datePart(new Date(date.valueOf())),
				op = "d"+dstr(md),
				data = this.options.data[op];
			if(data&&data.length>0){
				for(var i=0,len=data.length;i<len;i++){
					var da = data[i],
						std = this.strToDate("%Y-%m-%d"),
						sd = std(da.starttime),
						ed = std(da.endtime);
					if(sd.valueOf()<=md.valueOf()&&ed.valueOf()>=md.valueOf()){
						
						return da;
					}
					
					
				}
				
			}else{
				
				return false;
			}
			
		},
		nextMonth : function(){
			var cur = this.datePart(this.currShowDate),
				next = this.add(cur,1,"month");
			//this.renderCal(next);
			this.moveto(cur,next);
		
		},
		prevMonth : function(){
		
			var cur = this.datePart(this.currShowDate),
				prev = this.add(cur,-1,"month");
			//this.renderCal(prev);
			this.moveto(cur,prev);
		}
	
	});
	 module.exports = calendar;
});