/* Author: yangzeming
 * Date: 2013-12-10
 * Desc: 简单的日历组件
 */
define("component/datepick",["component/basecalendar"],function (require, exports, module) { 
    
	var bc = require("./basecalendar");
	var datepick = bc.extend({
		initial : function(options){
			var defaultOp = {
				con : "body",
			    input : "",
				calTemplate : "",
				titleTemplate:"<div></div>",
				conTemplate : '<div  class="ui-cal-date" style="display:none;position:absolute"><div class="ui-cal-title" data-role="title"></div><div data-role="calendar" class="ui-cal-body"></div></div>',
				startMonday : 1,
				config:{},
				date : {},
				rows : 6,
				currentDate : new Date()
				
			};
			this.options = $.extend(true,{},defaultOp,options);
			this._eventStack = {};
			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);
			$(this.options.con).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.renderMenu();
			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="calbox"]',"click",function(){
				var that = $(this),
					date = that.data("date");
				/*if(self.$input){
					self.$input.val(date);
					self.hide();
				}*/
				self.trigger("onclickday",that,date);
			
			});
			this.$con.delegate('[data-role="calMenu"]',"click",function(){
				  var that = $(this),
					  month = that.data("month"),
					  date = self.currShowDate,
					  next = new Date(date.valueOf());
					  next.setMonth(month);

				 self.hideMenu(self.$title,function(){
						self.moveto(date,next);
					
				  });
				 //self.$title.data("show",false);
				 // $(this).closest("tr").removeClass("ui-cal-table-hover");
			
			});
			this.$con.delegate('[data-role="calMenu"]',"mouseenter",function(){
				 
				 $(this).addClass("cal-Menu-hover");
			});
			// 传输进来的input
			if(this.$input){
				var time = null;
				this.$input.click(function(event){

					self.show();
					self.clickClose("first",self.$con);
					event.stopPropagation();
				});
				
			}
			/*"blind
"bounce"
"clip"
"drop"
"explode"
fade
"fold"
"highlight"
"puff"
"pulsate"
"scale"
"shake"
"size"
"slide"
"transfer"*/
			this.$title.click(function(){
				//self.$menu.effect("slide", { "mode": "show" }, 500, function () {
                        //self.trigger("clickMenu", $target);
                
                //});
				var that = $(this),
					s = that.data("show");
				if(s==true){
					//self.$menu.css("top","-100%").show();
					self.hideMenu(that);
					
				}else{
					self.menuInit();
					self.showMenu(that);
				}
			});
		
		},
		// 点击其他地方关闭日历
		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);
		},
		menuInit : function(){
			var $input = this.$menu.find('[data-role="ytext"]'),
				date = this.currShowDate,
				year = date.getFullYear(),
				month = date.getMonth();
			$input.val(year);
			this.$menu.find('[data-month]').removeClass("cal-Menu-select").filter('[data-month="'+month+'"]').addClass("cal-Menu-select");
		
		},
		goToday : function(){
			var date = new Date();
			date = this.datePart(date);
			this.moveto(this.currShowDate,date);
		
		},
		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 _html = "";
			/*_html +='<div class="cal-btn cal-btn-py" data-hrole="hover" data-role="py"></div>'
			       + '<div class="cal-btn cal-btn-pm" data-hrole="hover" data-role="pm"></div>'
				   + '<div class="cal-btn cal-btn-ny" data-hrole="hover" data-role="ny"></div>'
				   + '<div class="cal-btn cal-btn-nm" data-hrole="hover" data-role="nm"></div>'
				   + '<div class="cal-btn-ds"  data-role="ds"><div class="cal-ds" data-hrole="calds" unselectable="on" data-role="titleDate"></div></div>';
			*/_html += '<div class="cal-header" data-role="chead">';
			var width = (1 / 7) * 100 + "%";
			for(var i=0;i<7;i++){
				_html+='<span class="inline-b" style="width:'+width+';">'+this.date.day_short[i]+'</span>';
			}
			_html +='</div>';
			this.$con.find('[data-role="title"]').html(_html);
		
		},
		renderBottom:function(){
			
		
		},
		renderMenu : function(){
			/*this.$menu = this.$con.find('[data-role="menu"]');
			var _html = '<div class="ui-cal-incon"><input data-role="ytext" type="text" size=6 /></div><div class="cal-go-today" ><div data-role="mgotoday" class="cal-today-text">返回今天</div></div><p class="cal-menu-line">&nbsp;</p>';
			_html+='<div class="cal-menu-month">'
			for(var i=0;i<12;i++){
				_html+='<div data-month="'+i+'" data-role="calMenu"  class="ui-cal-menu">'+this.date.month_full[i]+'</div>';
				
			}
			_html+='</div>'
			this.$menu.html(_html);*/
		
		},
		renderCal : function(date){
			this.$title = this.$con.find('[data-role="titleDate"]');
			this.$con.find('[data-role="calendar"]').html(this.genericCalendar(date));
			this.$title.html(this.dateToStr("%Y年%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),
				fop = {
								"position" : "absolute",
								"top" : "5px",
								"width" : "100%"
								//"marginLeft" : "-200px",
								//"left" :"100%"
			
							},
				top = {
								"position" : "absolute",
								"top" : "5px",
								"width" : "100%"
								//"left" :"100%"
			
							},
				anim = {};
			var count=0,self = this;
			this.$con.find('[data-role="titleDate"]').html(this.dateToStr("%Y年%m月")(to));
			if(from==to){
				$body.html(toBody);
			}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" : "200px","left" : "-100%"}), anim["marginLeft"] = "400px", $.extend(top,{"left" : "-100%"}), dir = "right") : ($.extend(fop,{"marginTop" : "137px","top" : "-100%"}), anim["marginTop"] = "274px", $.extend(top,{"top" : "-100%"}), dir = "down");
					
			
				}else{
					fy==ty ? ($.extend(fop,{"marginLeft" : "-200px","left" : "100%"}), anim["marginLeft"] = "-400px", $.extend(top,{"left" : "100%"}), dir = "left")  :  ($.extend(fop,{"marginTop" : "-137px","top" : "100%"}), anim["marginTop"] = "-274px", $.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))-200)/2;return {"left":dur+"%"}';break;
						case "right" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginLeft").replace("px",""),10))-200)/2;return {"left":"-"+dur+"%"}';break;
						case "up" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginTop").replace("px",""),10))-137)/137*100;return {"top":dur+"%"}';break;
						case "down" : 
							fun = 'var dur = 100-(Math.abs(parseInt(fAnimBody.css("marginTop").replace("px",""),10))-137)/137*100;return {"top":"-"+dur+"%"}';break;
					
					}
					return new Function("fAnimBody",fun);
					
				
				};
				var fu = getOp(dir);
				
				this.menuInit();
				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);
						tAnimBody.css(dur);
				
					}});
					this.t1.to([fAnimBody],.3,anim);
				}

				
			}
			
		},
		// 绘制日历月视图
		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("%d"),
				dstr = this.dateToStr("%Y-%m-%d"),
                mstr = this.dateToStr("%Y年%m月");
			var rows=this.options.rows||Math.ceil(Math.round((ed.valueOf()-sd.valueOf()) / (60*60*24*1000) ) / 7);
			var _html = '<div style="color:#C5816A;text-align:left;height:4rem;line-height:4rem;">' + mstr(date) + '</div><table>';

			/*for(var j=0;j<7;j++){
				_html+='<th>'+this.date.day_short[j]+'</th>';
			}
			_html+='</tr></thead>';*/
			var dd = this.add(curr, -7, "day"),
                cm = curr.getMonth();
               
			for(var i=0;i<rows;i++){
				var _t = '<tr>';
				for(var j=0;j<7;j++){
				    var calClass = 'cal-valid' ;//'cal-normal';
				    var nm = sd.getMonth(),
                        cday = sd.getDay();
				    if (curr.valueOf() >= sd.valueOf() && sd.valueOf() >= dd.valueOf() && cm == nm) {
				        if (cday == 6 || cday == 0) {
				            calClass = 'cal-validweek';
				        } else {
				            calClass = 'cal-valid';
				        }
				    } else {
				        calClass = 'cal-invalid'
				    }
					/*if(sd<md){
						calClass = 'cal-before'
					
					}else if (sd>=ed)
						calClass='cal-after';
					else if (sd.valueOf()===curr.valueOf()){
					    calClass = 'cal-now';
					}*/
				
					_t+='<td ><div  class="cal-box '+calClass+'" data-role="calbox" data-date="'+dstr(sd)+'">'+monthDay(sd)+'</div></td>';
					sd=this.add(sd,1,"day");
				}
				_+='</tr>'
				_html+=_t;
			
			}
			_html +='</table>'
			return _html;
				
		},
		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 = datepick;
});