function calendar(options) {
    options = (options) ? options: {};
    this.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    var today = new Date();
    this.year = (options.year) ? options.year: today.getFullYear();
    this.month = (options.month) ? options.month: (today.getMonth() + 1);
    this.selected_day = (options.selected_day) ? options.selected_day: null;
    this.target = (options.target) ? options.target: null;
    this.startDate = (options.startDate) ? options.startDate: [];
    this.priceInfo = (options.priceInfo) ? options.priceInfo: [];
    this.callback = (options.callback) ? options.callback: false;
    this.outdays = (options.outdays) ? options.outdays: 0;
    this.showEveryDay=(options.showEveryDay)?options.showEveryDay:false;
    this.afterdayes=(options.afterdayes) ? options.afterdayes: 3; //默认可以订购当前日期3天后的
    this.showDetail = (options.showDetail) ? options.showDetail: true;
    this.currentDate = {};
    this.getCurrentDate();
    this.getStartDate(this.priceInfo);
    this.queryTime = this.currentDate.time;
    this.calendarCount = (options.calendarCount) ? options.calendarCount: 1;
    this.defaultPriceIndex=this.arr_find("", this.startDate);
    if (this.calendarCount == 2) {
        this.renderTwoCalendar();
    } else {
        this.renderOneCalendar();
    }
}
calendar.prototype = {
    arr_find:function(str, arr) {
	    if (str == undefined) {
	        return false
	    } else {
	        for (var i = 0; i < arr.length; i++) {
	            if (str == arr[i]) {
	                return i;
	            }
	        }
	        return false;
	    }
    },
    intDate:function(last_date){
    	var ld=last_date.split("-");
    	var ddate = new Date(ld[0], Number(ld[1])-1, ld[2]);
    	return ddate.getTime();
    },
    formatDate:function(year,month,day) {
	    if (parseInt(month)<10) {
	        month = "0"+month;
	    }
	    if (parseInt(day)<10) {
	        day = "0"+day;
	    } 
	    return year+'-'+month+'-'+day;
    },
    getStartDate:function(arr) {
    	var startDate = new Array();
	    for (var i = 0; i < arr.length; i++) {
	        startDate.push(arr[i][0]);
	    }
	    this.startDate= startDate;
    },
    getCnWeek:function(strdate) {
       var arys = strdate.split('-');   
       var week = new Date(arys[0],Number(arys[1])-1,Number(arys[2])).getDay();
       switch (week)
	   {
	   case 1:
	     return "周一";
	     break;
	   case 2:
	     return "周二";
	     break;
	   case 3:
	     return "周三";
	     break;
	   case 4:
	     return "周四";
	     break;
	   case 5:
	     return "周五";
	     break;
	   case 6:
	     return "周六";
	     break;
	   case 0:
	     return "周日";
	     break;
	   }
    },
    getNextDay:function(year,month,day,outdays)
	{
		var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31,30, 31, 30, 31);
		if (2 == month)
			days = ((0 == year % 4) && (0 != (year % 100))) ||(0 == year % 400) ? 29 : 28;
		else
			days =  daysInMonth[month-1];

		day = day+outdays-1 ;
		if((day) > days)
		{
			day = day - days ;
			month += 1 ;
			if(month > 12)
			{
				month -= 12 ;
				year += 1 ;
			}
		}
		return this.formatDate(year,month,day);
	},
    getDays: function(year, month) {
        if (1 == month) {
            return ((0 == year % 4) && (0 != (year % 100))) || (0 == year % 400) ? 29 : 28;
        } else {
            return this.daysInMonth[month];
        }
    },
    getCurrentDate: function() {
        var cal = this;
        var now = new Date();
        cal.currentDate.year = now.getFullYear();
        cal.currentDate.month = now.getMonth() + 1;
        cal.currentDate.day = now.getDate();
        cal.currentDate.week = now.getDay();
        cal.currentDate.time = now.getTime();
        var current = new Date(cal.currentDate.year, cal.currentDate.month - 1, cal.currentDate.day);
        cal.currentDate.start_time = current.getTime();
    },
    renderOneCalendar: function() {
        var strs = new Array();
        strs.push('<div class="calendar_wrap"  id="contentid2">');
        strs.push(this.buildOneCalendar());
        strs.push("</div>");
        $(this.target).html(strs.join(""));
        this.bind();
    },
    renderTwoCalendar: function() {
        var strs = new Array();
        strs.push('<div class="calendar_wrap" id="contentid2">');
        strs.push('<div style="width:600px">');
        strs.push('<div class="calendar_left"><a id="cal_pre" class="left left_arrow" href="javascript:void(0);">前两个月</a></div>');
        strs.push('<div class="calendar_right"><a id="cal_next" class="right right_arrow" href="javascript:void(0);">后两个月</a></div>');
        strs.push('</div>');
        strs.push('<div class="calendar_left">' + this.buildOneCalendar() + "</div>");
        this.month += 1;
        strs.push('<div class="calendar_right">' + this.buildOneCalendar() + "</div>");
        strs.push("</div>");
        $(this.target).html(strs.join(""));
        this.bind();
    },
    buildOneCalendar: function() {
        if (this.month < 1) {
            this.year -= 1;
            this.month = this.month + 12
        }
        if (this.month - 12 > 0) {
            this.year += 1;
            this.month = this.month - 12
        }
        var days = this.getDays(this.year, this.month - 1);
        var strs = new Array();
        strs.push('<h1>' + this.year + '年' + this.month + '月</h1>');
        strs.push('<table cellspacing="0">');
        strs.push('<thead><tr><th>日</th>');
        strs.push('<th>一</th>');
        strs.push('<th>二</th>');
        strs.push('<th>三</th>');
        strs.push('<th>四</th>');
        strs.push('<th>五</th>');
        strs.push('<th>六</th></tr></thead><tbody>');
        var k = 0;
        var day = 1;
        var now = new Date(this.year, (this.month - 1));
        var weeks = week = now.getDay();
        while (true) {
            strs.push("<tr>");
            if (k == 0) {
                for (i = 0; i <= 6; i++) {
                    if (i < weeks) {
                        strs.push('<td class="padding"></td>');
                    } else {
                        strs.push(this.formatCalendarDay(this.year, this.month, day, week));
                        day++;
                        week++;
                        week = (week == 7) ? 0 : week;
                    }
                }
            } else {
                for (i = 0; i <= 6; i++) {
                    if (day > days) {
                        strs.push('<td class="padding"></td>');
                    } else {
                        strs.push(this.formatCalendarDay(this.year, this.month, day, week));
                        day++;
                        week++;
                        week = (week == 7) ? 0 : week;
                    }
                }
            }
            strs.push("</tr>");
            k++;
            if (day > days) {
                break;
            }
        }
        strs.push("</tbody></table>");
        return strs.join("");
    },
    formatCalendarDay: function(year, month, day, week) {
        var cal = this;
        var sdate = this.formatDate(year,month,day);
        var ddate = new Date(year, month - 1, day);
        var stime = ddate.getTime();
        var dindex = this.arr_find(sdate, cal.startDate);
        if(cal.currentDate.start_time> stime){
        	return cal.buildDay(sdate, day);
        }else if (cal.currentDate.start_time == stime) {
            return cal.buildDay(sdate, day + "<br>今天");	
        }else {
        	if(cal.showEveryDay){
        		if(cal.currentDate.start_time+cal.afterdayes*24*60*60*1000 > stime){
        			return cal.buildDay(sdate, day);
        		}
        		if(dindex === false){
        			if(cal.defaultPriceIndex===false){
        				return cal.buildDay(sdate, day);
        			}else{
        				dindex=cal.defaultPriceIndex;
        				//alert(cal.defaultPriceIndex);
        			}
        		}
        	}
            if (dindex !== false&&cal.priceInfo[dindex]) {
            	var last_date = cal.priceInfo[dindex][5];//报名截止日期
            	if(cal.showEveryDay){
                	last_date=false;
                }
                if (last_date===false||(last_date&&cal.currentDate.start_time<this.intDate(last_date))) {
                    var cr_ms_price = cal.priceInfo[dindex][1];//成人门市价
                    var cr_ala_price = cal.priceInfo[dindex][2];//成人阿拉价
                    var rt_ms_price = cal.priceInfo[dindex][3];//儿童门市价
                    var rt_ala_price = cal.priceInfo[dindex][4];//儿童阿拉价
                    
                    
                    var back_date = this.getNextDay(year,month,day,this.outdays);//返回日期
                    var sprice = "&yen;" + cr_ala_price;//日历显示价格
                    return cal.buildDay(sdate, day, sprice, cr_ms_price,cr_ala_price,rt_ms_price,rt_ala_price,last_date,back_date);
                }
            }
        }
        return cal.buildDay(sdate, day);
    },
    buildDay: function(sdate, day, sprice,cr_ms_price,cr_ala_price,rt_ms_price,rt_ala_price,last_date,back_date) {
        if (sprice) {
            var str_price = day + '<br/><span class="show_price">' + sprice + "起</span>";
            var strs = new Array();
            strs.push('<div class="events"><ul>');
            strs.push('<li><span>出发日期：'+sdate+'('+this.getCnWeek(sdate)+')</span></li>');
            strs.push('<li><span>返回日期：'+back_date+'('+this.getCnWeek(back_date)+')</span></li>');
            if(last_date){
            	strs.push('<li><span>预订截止：'+last_date+'('+this.getCnWeek(last_date)+')</span></li>');
            }
            strs.push('<li><span class="ms">门市价</span><span class="ala">阿拉价</span></li>');
            strs.push('<li><span>成人</span><span class="ms_price">&yen;'+cr_ms_price+'</span><span class="ala_price">&yen;'+cr_ala_price+'起</span></li>');
            if("0"!=rt_ms_price){
            strs.push('<li><span>儿童</span><span class="ms_price">&yen;'+rt_ms_price+'</span><span class="ala_price">&yen;'+rt_ala_price+'起</span></li>');
            }
            strs.push('<li><span class="bar">');
            if(this.callback){
                strs.push('<input type="button" class="btn" value="确定" onclick="chooseDate(\''+sdate+'\',\''+back_date+'\',\''+last_date+'\',\''+cr_ms_price+'\',\''+cr_ala_price+'\',\''+rt_ms_price+'\',\''+rt_ala_price+'\')">');
            }else{
                strs.push('<input type="button" class="btn" value="立即预订" onclick="jumpDate(\''+sdate+'\')">');
            }
            strs.push('</span></li></ul></div>');	
	
            return '<td class="date_has_event" id="' + sdate + '">' + str_price + strs.join("") + "</td>";
        } else {
        	if(day.length>2)
               return '<td class="today" id="' + sdate + '">' + day + "</td>";
            else
               return '<td>' + day + "</td>";
        }
    },
    inArray: function(str, arr) {
        if (str == undefined) {
            return false;
        } else {
            for (var i = 0; i < arr.length; B++) {
                if (str == arr[i]) {
                    return true;
                }
            }
            return false;
        }
    },
    nextCalendar: function() {
        this.getCurrentDate();
        if (this.currentDate.time - this.queryTime < 1000) {
            alert("请求时间间隔太短!");
            return false
        }
        this.queryTime = this.currentDate.time;
        this.month = this.month + 1;
        if (this.calendarCount == 2) {
            this.renderTwoCalendar()
        } else {
            this.renderOneCalendar()
        }
    },
    prevCalendar: function() {
        this.getCurrentDate();
        if (this.currentDate.time - this.queryTime < 1000) {
            alert("请求时间间隔太短!");
            return false
        }
        this.queryTime = this.currentDate.time;
        if (this.calendarCount == 2) {
            this.month = this.month - 3;
            this.renderTwoCalendar()
        } else {
            this.month = this.month - 1;
            this.renderOneCalendar()
        }
    },
    bind: function() {
        var cal = this;
        if(cal.currentDate.month==(13-cal.month)){
        	$("#cal_pre").attr("disabled","disabled");
        };
        $("#cal_pre").click(function() {
            cal.prevCalendar()
        });
        $("#cal_next").click(function() {
            cal.nextCalendar()
        });
        if (cal.showDetail) {
		$('.date_has_event').each(function () {
			// options
			var distance = 10;
			var time = 250;
			var hideDelay = 500;

			var hideDelayTimer = null;

			// tracker
			var beingShown = false;
			var shown = false;

			var trigger = $(this);
			var popup = $('.events ul', this).css('opacity', 0);

			// set the mouseover and mouseout on both element
			$([trigger.get(0), popup.get(0)]).mouseover(function () {
				// stops the hide event if we move from the trigger to the popup element
				if (hideDelayTimer) clearTimeout(hideDelayTimer);

				// don't trigger the animation again if we're being shown, or already visible
				if (beingShown || shown) {
					return;
				} else {
					beingShown = true;

					// reset position of popup box
					popup.css({
						bottom: 25,
						left: -115,
						display: 'block' // brings the popup back in to view
					})

					// (we're using chaining on the popup) now animate it's opacity and position
					.animate({
						bottom: '+=' + distance + 'px',
						opacity: 1
					}, time, 'swing', function() {
						// once the animation is complete, set the tracker variables
						beingShown = false;
						shown = true;
					});
				}
			}).mouseout(function () {
				// reset the timer if we get fired again - avoids double animations
				if (hideDelayTimer) clearTimeout(hideDelayTimer);

				// store the timer so that it can be cleared in the mouseover if required
				hideDelayTimer = setTimeout(function () {
					hideDelayTimer = null;
					popup.animate({
						bottom: '-=' + distance + 'px',
						opacity: 0
					}, time, 'swing', function () {
						// once the animate is complete, set the tracker variables
						shown = false;
						// hide the popup entirely after the effect (opacity alone doesn't do the job)
						popup.css('display', 'none');
					});
				}, hideDelay);
			});
		});
      }
    }
};
