/**
 * 生日选择插件
 * todo 选择年，月，之后初始化日
 * 是不是必须要select 才有选中状态
 *
 */
(function ($,CalendarConvert){
    var zodiacArr = ["-", "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"];

    var constellationArr = ["-", "摩羯座", "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座", "狮子座", "处女座", "天秤座", "天蝎座", "射手座"];
    $.rollingMatch = rollingMatch;
    function rollingMatch(clickId, listId, highLightClass) {
        var targetValue = $.trim($(clickId).text());
        var childernValue = $(listId).find("li");
        var listIdShort = listId.slice(1);
        for (var i = 0; i < childernValue.length; i++) {
            var ConformValue = $.trim($(childernValue[i]).text());
            if (targetValue == ConformValue) {
                var highLightItem = childernValue[i];
                $(childernValue).removeClass(highLightClass);
                $(highLightItem).addClass(highLightClass);
                document.getElementById(listIdShort).scrollTop = childernValue[i].offsetTop;
                break;
            }
        }
        $(listId).mouseover(function (event) {
            event.stopPropagation();
            $(childernValue).removeClass(highLightClass);
        })
    } //sq


    function isRN(y){//计算闺年
        return y%4 == 0 || (y%100 == 0 && y%400 == 0);
    }
    function getDays(y, m){//计算每月天数
        if (m == 2) {
            return isRN(y) ? 29 : 28;
        }else if(m < 8){
            return m%2 == 0 ? 30 : 31
        }else{
            return m%2 == 0 ? 31 : 30
        }
    }
    function showYearList(){
        var myDate = new Date();
        var year = myDate.getFullYear();
        var html = '';
        //如果为农历
        for(var i=year;i>1899;i--){
            html +='<li><a class="yearItem"  value="'+i+'" href="javascript:;">'+i+'年</a></li>';
        }
        $('#yearList').html(html);
        $('.yearItem').click(function(){
            $('#yearList').hide();
            $('#yearContainer').text($(this).text());
            $('#year').attr('value',$(this).attr('value'));
            setBirth();
            return false;
        });
        if('none'==$('#yearList').css('display')){
            $('#yearList').show();
            $('#monthList').hide();
            $('#dayList').hide();
        }else{
            $('#yearList').hide();
        }

    }

    function getCurrentYear(){
        return $('#year').attr('value');
    }
    function setCurrentYear(y){
        $('#year').attr('value',y);
        $('#yearContainer').text(y+'年');
    }
    function getCurrentMonth(){
        var m = $('#month').attr('value');
        return m;
    }

    $.setCurrentYear = setCurrentYear;
    $.setCurrentMonth = setCurrentMonth;
    $.setCurrentDay = setCurrentDay;

    function leftPad(v){
        if(parseInt(v) <10){
            return '0'+v;
        }else{
            return v;
        }
    }

    function setCurrentMonth(m){
        $('#month').attr('value',m);
        $('#monthContainer').text(m+'月');
    }
    function getCurrentDay(){
        var d = $('#day').attr('value');
        return d;
    }
    function setCurrentDay(d){
        $('#day').attr('value',d);
        $('#dayContainer').text(d+'日');
    }

    function showMonthList(){
        var html = '';
		var lastMonth = 12;
		if((new Date()).getFullYear()==getCurrentYear()){
			lastMonth = (new Date()).getMonth()+1;
		}
        for(var i=1;i<=lastMonth;i++){
            html +='<li><a class="monthItem" value="'+i+'" href="javascript:;">'+i+'月</a></li>';
        }
        $('#monthList').html(html);
        $('.monthItem').click(function(){
            $('#monthContainer').text($(this).text());
            $('#month').attr('value',$(this).attr('value'));
            $('#monthList').hide();
            setBirth();
            return false;
        });
        if('none'==$('#monthList').css('display')){
            $('#monthList').show();
            $('#yearList').hide();
            $('#dayList').hide();
        }else{
            $('#monthList').hide();
        }
    }

    function showLunarYear(){
        var html = '';
        var myDate = new Date();
        var year = myDate.getFullYear();

        for(var i=year;i>1899;i--){
            html +='<li><a class="yearItem"  value="'+i+'" href="javascript:;">'+CalendarConvert.GetLunarDay(i,6,6)[0]+'年'+'('+i+')</a></li>';
        }
        $('#yearList').html(html);
        $('.yearItem').click(function(){
            $('#yearList').hide();
            $('#yearContainer').text($(this).text());
            $('#year').attr('value',$(this).attr('value'));
            setBirth();
            return false;
        });
        if('none'==$('#yearList').css('display')){
            $('#yearList').show();
            $('#monthList').hide();
            $('#dayList').hide();
        }else{
            $('#yearList').hide();
        }
    }

    function showLunarMonth(){
        var html = '';
         //取得选中农历年份
        var year = $('#year').attr('value');
        var lunarMonth = CalendarConvert.getLunarMonth(year);

        for (var i in lunarMonth) {
            html +='<li><a class="monthItem" value="'+lunarMonth[i].value+'" href="javascript:;">'+lunarMonth[i].name+'</a></li>';
        };

        $('#monthList').html(html);
        $('.monthItem').click(function(){
            $('#monthContainer').text($(this).text());
            $('#month').attr('value',$(this).attr('value'));
            $('#monthList').hide();
            setBirth();
            return false;
        });
        if('none'==$('#monthList').css('display')){
            $('#monthList').show();
            $('#dayList').hide();
            $('#yearList').hide();
        }else{
            $('#monthList').hide();
        }
    }

    function showLunarDays(){
        var html = '';
         //取得选中农历年份
        var year = $('#year').attr('value');
        //取农历月份
        var month = $('#month').attr('value');
        var lunarDays = CalendarConvert.getLunarDateC(year,month);

        for(var i in lunarDays){
            html +='<li><a class="dayItem" value="'+lunarDays[i].value+'" href="javascript:;">'+lunarDays[i].name+'</a></li>';
        }
        $('#dayList').html(html);
        $('.dayItem').click(function(){
            $('#dayContainer').text($(this).text());
            $('#day').attr('value',$(this).attr('value'));
            $('#dayList').hide();
            setBirth();
            return false;
        });
        if('none'==$('#dayList').css('display')){
            $('#dayList').show();
            $('#yearList').hide();
            $('#monthList').hide();
        }else{
            $('#dayList').hide();
        }
    }

    function showDayList(){
        var html = '';
        var daysCount = getDays(getCurrentYear(),getCurrentMonth());
		if((new Date()).getFullYear()==getCurrentYear()&&((new Date()).getMonth()+1)==getCurrentMonth()){
			daysCount = (new Date()).getDate();
		}
        for(var i=1;i<=daysCount;i++){
            html +='<li><a class="dayItem" value="'+i+'" href="javascript:;">'+i+'日</a></li>';
        }
        $('#dayList').html(html);
        $('.dayItem').click(function(){
            $('#dayContainer').text($(this).text());
            $('#day').attr('value',$(this).attr('value'));
            $('#dayList').hide();
            setBirth();
            return false;
        });
        if('none'==$('#dayList').css('display')){
            $('#dayList').show();
            $('#yearList').hide();
            $('#monthList').hide();
        }else{
            $('#dayList').hide();
        }
    }
    //获取当前历法
    function getCurrentCalendar(){
        //判断公历 农历
        if($('#lunarDiv').hasClass('selected')){
            return 1;
        }else{
            return 0;
        }
    }
    //获取当前公历日期（是农历的话转为公历）
    function getCurrentDate(){
        var y = getCurrentYear();
        var m = getCurrentMonth();
        var d = getCurrentDay();
        var date = '' ;
        if(1==getCurrentCalendar()){
            var obj = CalendarConvert.GetGregorianDay(y,m,d);
            date = obj.y + '-' + leftPad(obj.m) + '-' + leftPad(obj.d);

        }else{
            date = y+'-'+leftPad(m)+'-'+leftPad(d);
        }

        return date;
    }

    function gregorianRoLunarSelect(info){
        //初始位置
        var isLunar = parseInt(info.BirthLunar);
        if(isLunar==1){
            $('#lunarDiv').addClass('selected');
            $('#gregorianDiv').removeClass('selected');
        }else{
            $('#gregorianDiv').addClass('selected');
            $('#lunarDiv').removeClass('selected');
        }
        //切换
        $('#lunarDiv').click(function(){
            $('#lunarDiv').addClass('selected');
            $('#gregorianDiv').removeClass('selected');
            
            var cBirth = getCurrentBirth();
            for(var i in cBirth){
                console.log('#########  '+i +'::::'+cBirth[i]);
            }
            var obj = CalendarConvert.GetLunarDay(cBirth.y,cBirth.m,cBirth.d);
            $('#yearContainer').text(obj[0]+'年('+obj[1]+')');
            $('#year').attr('value',obj[1]);
            $('#monthContainer').text(obj[2].name);
            $('#month').attr('value',obj[2].value)
            $('#dayContainer').text(obj[3].name);
            $('#day').attr('value',obj[3].value);
            $('#editBirthday').text(obj[0]+'年'+obj[2].name+obj[3].name);
            return false;
        });

        $('#gregorianDiv').click(function(){

            $('#gregorianDiv').addClass('selected');
            $('#lunarDiv').removeClass('selected');
            var birth = getCurrentBirth();
            //月份小于0为闰月，需要重新转换
            if(birth.m <0 ){
                 var obj = CalendarConvert.GetGregorianDay(getCurrentYear(),getCurrentMonth(),getCurrentDay());
                 birth.y = obj.y;
                 birth.m = obj.m;
                 birth.d = obj.d;
            }

            for(var i in birth){
                console.log('------******   '+i +'::::'+birth[i]);
            }
            console.log(birth);
            $('#yearContainer').text(birth.y+'年');
            $('#year').attr('value',birth.y);
            $('#monthContainer').text(birth.m+'月');
            $('#month').attr('value',birth.m)
            $('#dayContainer').text(birth.d+'日');
            $('#day').attr('value',birth.d);
            $('#editBirthday').text(birth.y+'-'+birth.m+'-'+birth.d);
            return false;
        });
    }


    function initBirth(info){
        var birth = info.Birthday || '';
        if(birth != ''){
            birth = birth.split('-');
        }

        var myDate = new Date();
        var year = myDate.getFullYear();
        var month = (myDate.getMonth()+1);       //获取当前月份(0-11,0代表1月)
        var day = myDate.getDate();
        y = Number(birth[0]) || year;
        m = Number(birth[1]) || month;
        d = Number(birth[2]) || day;
        var isLunar = info.BirthLunar || 0;
        if(parseInt(isLunar) == 1){
            var obj = CalendarConvert.GetLunarDay(y,m,d);
            $('#yearContainer').text(obj[0]+'年('+obj[1]+')');
            $('#year').attr('value',obj[1]);
            $('#monthContainer').text(obj[2].name);
            $('#month').attr('value',obj[2].value)
            $('#dayContainer').text(obj[3].name);
            $('#day').attr('value',obj[3].value);
            $('#editBirthday').text(obj[0]+'年'+obj[2].name+obj[3].name);
            // $('#editBirthday').attr('currentYear',obj[1]);
            // $('#editBirthday').attr('currentMonth',obj[2]['value']);
            // $('#editBirthday').attr('currentDay',obj[3]['value']);
            $('#editBirthday').attr('currentYear',y);
            $('#editBirthday').attr('currentMonth',m);
            $('#editBirthday').attr('currentDay',d);
        }else{
            $('#yearContainer').text(y+'年');
            $('#year').attr('value',y);
            $('#monthContainer').text(m+'月');
            $('#month').attr('value',m)
            $('#dayContainer').text(d+'日');
            $('#day').attr('value',d);
            $('#editBirthday').text(y+'-'+m+'-'+d);
            $('#editBirthday').attr('currentYear',y);
            $('#editBirthday').attr('currentMonth',m);
            $('#editBirthday').attr('currentDay',d);
        }
    }

    function setBirth(){
        var y = getCurrentYear();

        var m = getCurrentMonth();

        var d = getCurrentDay();

        if(getCurrentCalendar()){
            $('#editBirthday').text($('#yearContainer').text().substr(0,3)+$('#monthContainer').text()+$('#dayContainer').text());
        }else{
            $('#editBirthday').text(y+'-'+m+'-'+d);
        }
        setCurrentbirth();

        //生肖，年龄，星座信息联动

        if(getCurrentCalendar()){
            var animal = CalendarConvert.getYearAnimal(y);

            var date = CalendarConvert.GetGregorianDay(y,m,d);
            var age = CalendarConvert.getAge(date.y,date.m,date.d);

            var astro = CalendarConvert.getAstro(date.m,date.d);

        }else{
            var date = CalendarConvert.GetLunarDay(y,m,d);
            var animal = CalendarConvert.getYearAnimal(date[1]);

            var age = CalendarConvert.getAge(y,m,d);
            var astro = CalendarConvert.getAstro(m,d);
        }

        $('#editAge').text(age);
        //设置星座  ???
        $('#editConstellationContainer').text(constellationArr[astro]);
        $('#editConstellationContainer').attr('value', astro);
        //设置生肖
        $('#editZodiacContainer').text(zodiacArr[animal]);
        $('#editZodiacContainer').attr('value', animal);
    }

    function setCurrentbirth(){
        var isLunar = getCurrentCalendar();
        if(isLunar){
            var obj = CalendarConvert.GetGregorianDay(getCurrentYear(),getCurrentMonth(),getCurrentDay());
            $('#editBirthday').attr('currentYear',obj.y);
            $('#editBirthday').attr('currentMonth',obj.m);
            $('#editBirthday').attr('currentDay',obj.d);
            console.log('农历：：：'+obj.y+obj.m+obj.d);
        }else{
            $('#editBirthday').attr('currentYear',$('#year').attr('value'));
            $('#editBirthday').attr('currentMonth',$('#month').attr('value'));
            $('#editBirthday').attr('currentDay',$('#day').attr('value'));
            console.log('公历：：：'+$('#year').attr('value')+$('#month').attr('value')+$('#day').attr('value'));
        }
        
    }

    function getCurrentBirth(){
        var obj = {}
        obj.y = $('#editBirthday').attr('currentYear');
        obj.m = $('#editBirthday').attr('currentMonth');
        obj.d = $('#editBirthday').attr('currentDay');
        return obj;
    }

    $.getBirth = getCurrentDate;
    $.getCalendar = getCurrentCalendar;

    $.birthdaySelect = function (info){

        initBirth(info);
        gregorianRoLunarSelect(info);

        $('#year').click(function(){
            if(getCurrentCalendar()){
                showLunarYear();
            }else{
                showYearList();
            }
            rollingMatch('#yearContainer', '#yearList', 'hover'); //sq
            return false;
        });
        $('#month').click(function(){
            if(getCurrentCalendar()){
                showLunarMonth();
            }else{
                showMonthList();
            }
            rollingMatch('#monthContainer', '#monthList', 'hover'); //sq
            return false;
        });
        $('#day').click(function(){
            if(getCurrentCalendar()){
                showLunarDays();
            }else{
                showDayList();
            }
            rollingMatch('#dayContainer', '#dayList', 'hover'); //sq
            return false;
        });
        $('#editBirthdaySpan').click(function(){
            $.hideOtherList();
            if('none'==$('#birthdayContainer').css('display')){
                $('#birthdayContainer').show();
            }else{
                $('#birthdayContainer').hide();
            }
            return false;
        });

    };
})(jQuery,window.CalendarConvert)

