/**
 * @author zyxiong
 */

/*
 * create time region
 * options:
 * 	yearlist: {
 * 		id:
 * 		diy:
 * 		current,
 * 		template
 * }
 * monthist: {
 * 		id:
 * 		dim:
 * 		current,
 * 		template
 * }
 * submitdate
 * requestMethod
 * timeRegion
 * set(timeRegion)
 */
var getDateList = function(options){
    var o = options, _yl = o.yearList ||
    {}, _ypo = $(_yl.id) ||
    {}, _dsy = $(_yl.diy) ||
    {}, _ml = o.monthList ||
    {}, _mpo = $(_ml.id) ||
    {}, _dsm = $(_ml.dim) ||
    {}, _sbd = $(o.submitDate) ||
    {}, _tr = o.timeRegion || '', _fn = o.requestMethod ||
    function(){
    }, _nt = new Array(2);
    
    this._nt = _nt;
    var self = this;
    this.set = function(timeRegion,fn_,current){
		current?_yl.current = current : 1;
        _tr = timeRegion;
        //time region	
        {
            _tr = _tr.split('~');
            _tr.start = [];
            _tr.s = _tr[0].split('.');
            _tr.start = [parseInt(_tr.s[0]), parseInt(_tr.s[1])];
            _tr.end = [];
            _tr.e = _tr[1].split('.');
            _tr.end = [_tr.e[0] == 'now' ? (new Date()).getFullYear() : parseInt(_tr.e[0]), _tr.e[1] == 'now' ? (new Date).getMonth() + 1 : parseInt(_tr.e[1])]
            _nt = _tr.end.slice('')
        }
        return this;
    }
    
    this.Run = function(callback,y){
		callback?_fn=callback:1;
        //set list
        _ypo.append(setYearList()).find('a').click(function(){
            var $this = $(this);
            adv($this.text());
			if(y){
				_fn(_nt);
			}
			return false;
        })
        
        _mpo.append(setMonthList()).find('a').click(function(){
            _dsm.text($(this).text());
            _nt[1] = $(this).text() * 1;
        }).end().find('a:gt(' + (_tr.end[1] - 1) + ')').css('display', 'none');
        
        _sbd.click(function(){
			var button = $(this);
                _fn(_nt,self,button);
            return false;
        });
		return this;
    }
	
	this.auto = function(fn){
		fn();
		return this;
	}
    
    if (_tr) {
        this.set(o.timeRegion);
    }
    
    function setYearList(){
        /* year list */
        var first = _tr.start[0], tem = _yl.template, t = tem[0], h = '', s = new RegExp(tem[1], 'g'), i = 0, last = _tr.end[0], l = last - first;
        
        _dsy.text(_yl.current ? _yl.current == 'now' ? (new Date()).getFullYear() : _yl.current : _tr.end[0])
        
        while (l >= i) {
            h += t.replace(s, first + i) + '\n';
            i++;
        }
        return h;
    }
    
    function setMonthList(){
        /* year list */
        var c = _tr.end[1], tem = _ml.template, t = tem[0], h = '', s = new RegExp(tem[1], 'g'), i = 0, first = 1
        
        _dsm.text(_ml.current ? _ml.current == 'now' ? (new Date()).getMonth() + 1 : _ml.current : _tr.end[1]);
        
        while (12 > i) {
            h += t.replace(s, first + i) + '\n';
            i++;
        }
        return h;
    }
	
	function adv(year){
		var r,a=year;
		if (a == _tr.start[0]) {
                if (_tr.start[1] - 1 == 0) {
                    r = 2;
                }
                else 
                    if (_tr.start[1] == 12) {
                        r = 12
                    }
                    else {
                        r = _tr.start[1];
                    }
                _dsm.text(r);
                _nt[1] = r * 1;
                _mpo.find('a').css('display', 'block').end().find('a:lt(' + (r - 1) + ')').css('display', 'none');
            }
            else 
                if (a == _tr.end[0]) {
                    if (_tr.end[1] - 1 == 0) {
                        r = 2;
                    }
                    else 
                        if (_tr.end[1] == 12) {
                            r = 12
                        }
                        else {
                            r = _tr.end[1];
                        }
                    _dsm.text(1);
                    _nt[1] = 1;
                    _mpo.find('a').css('display', 'block').end().find('a:gt(' + (r - 1) + ')').css('display', 'none');
                }
                else {
                    _mpo.find('a').css('display', 'block');
                    _dsm.text(1);
                    _nt[1] = 1;
                }
            _nt[0] = a * 1;
            _dsy.text(a)	
	}
    
    this.setNowTime = function(a, b,oc){
		if(oc){
			adv(a)
		}
        _nt = [a, b];
        _dsm.text(b);
        _dsy.text(a);
    }
	
	
    
    this.getEndDate = function(){
        return _tr.end;
    }
    
    this.getStartDate = function(){
        return _tr.start;
    }
    
    this.getCurrentTime = function(){
        return _nt;
    }
}

// create a Reuse div obj ,
var createSingleCover = function(options){

    var o = options, _t = $(o.handle) ||
    function(){
        return false
    }, _oFn = o.onOpen ||
    function(){
    }, _cFn = o.onClose ||
    function(){
    }, oFn_ = o.onBeforeOpen ||
    function(){
    }, cFn_ = o.onBeforeClose ||
    function(){
    }, _c = o.coverProperty ||
    {}, _shade = o.shade === false ? false : true, publicVar = {};
    _c.css = _c.css ||
    {};
    
    publicVar.existCover = false;
    if (o.close == o.handle) {
        _t.toggle(function(){
            if (!publicVar.existCover) {
                hasExist(_c.id);
            }
            publicVar.coverObject.css(_c.css)
            toggleShow(true, _oFn, oFn_);
            return false;
        }, function(){
            toggleShow(false, _cFn, cFn_);
            return false;
        });
    }
    else {
        _t.click(function(){
            if (!publicVar.existCover) {
                hasExist(_c.id);
            }
            publicVar.coverObject.css(_c.css)
            toggleShow(true, _oFn, oFn_);
            return false;
        });
    }
    //private method for rebind
    function close(){
        toggleShow(false, _cFn, cFn_);
        publicVar.closeObject = true;
        return false;
    }
    
    //private method , rebind the close handle because jquery.version is 1.3.2
    function rebind(id, n){
        if (n) {
            $(id).click(close);
        }
        else {
            $(id).unbind('click', close)
        }
    }
    
    //if not exist , create a ele(div)
    function hasExist(d){
        if (!$(d)[0]) {
            createCover();
        }
        else 
            if (!publicVar.existCover) {
                publicVar.existCover = true;
                publicVar.coverObject = $(d);
                publicVar.coverObject.css(_c.css).attr('cssHasChanged', 'true');
            }
        return true;
    }
    
    /* create cover div */
    function createCover(){
        var _dfc = {
            'background': 'black',
            'position': 'absolute',
            'top': '0',
            'left': '0',
            'display': 'none',
            'opacity': '0',
            'zIndex': '10'
        };
        var cover = $('<div id="' + _c.id.substring(1, _c.id.length) + '"></div').css(_dfc).css(_c.css);
        $('body').append(cover);
        publicVar.existCover = true;
        publicVar.coverObject = cover;
        if (_c.id == o.close) {
            rebind(_c.id);
        }
        fixed();
        $(window).bind('resize scroll', fixed);
    }
    
    /* if unexist , create */
    function fixed(){
		var bw = $('body').width(), ww = $(window).width(), bh = $('body').height(), wh = $(window).height(), w, h;
            w = bw >= ww ? bw : ww;
            h = bh >= wh ? bh : wh;
        if ('existCover' in publicVar) {
            publicVar.coverObject.css({
                'width': $('body').width() + 'px',
                'height': h + 'px'
            });
        }
        else {
            createCover();
        }
    }
    
    //show or hide
    function toggleShow(n, _fn, fn_){
        if (n) {
            _fn = _fn ? _fn : _oFn;
            fn_ = fn_ ? fn_ : cFn_;
            if (publicVar.existCover) {
                if (!_shade) {
                    fn_(obj);
                    return function(){
						publicVar.coverObject.css({
                        'display': 'block',
                        'visibility': 'visible',
                        'opacity': _c.endOpacity
                    	});
						_fn(publicVar.coverObject);
						publicVar.coverZoneHasShow = true;
            			rebind(o.close, true);
					}()
                }
                else {
                        fn_(publicVar.coverObject);
                        return publicVar.coverObject.css('display', 'block').stop().animate({
                            'opacity': _c.endOpacity
                        }, function(){
                                _fn(publicVar.coverObject);
								publicVar.coverZoneHasShow = true;
								rebind(o.close, true);
                        });
                }
            }
        }
        else {
            _fn = _fn ? _fn : _cFn;
            fn_ = fn_ ? fn_ : cFn_;
            if (!_shade) {
                fn_(publicVar.coverObject);
				
            	publicVar.coverZoneHasShow = false;
                return function(){
                    publicVar.coverObject.css({
                        'display': 'none',
                        'opacity': '0'
                    });
                    _fn(publicVar.coverObject);
					rebind(o.close, false);
                }
            }
            else {
                    fn_(publicVar.coverObject);
					rebind(o.close, false);
            		publicVar.coverZoneHasShow = false;
                    return publicVar.coverObject.stop().fadeOut(function(){
                        $(this).css('opacity', '0');
                        _cFn(publicVar.coverObject)
                    });
            }
        }
    }
    
    this.show = function(fn){
        toggleShow(true, fn);
        return this;
    }
    this.close = function(fn){
        toggleShow(false, fn);
        return this;
    }
    this.create = function(){
		if(!$(_c.id)[0]){
			createCover();
		}
        return this;
    }
    this.coverHasShow = function(){
        return publicVar.coverZoneHasShow;
    }
}

var weekly = function(options){
    var o = options ||
    {}, _p = $(o.weeklyListWrap) ||
    {}, _f = $(o.fieldZone).css('opacity', '0'), _w = $(o.weeklyList) ||
    {}, _pbtn = $(o.prev) ||
    {}, _nbtn = $(o.next) ||
    {}, _tr = {}, aSfn_, _aSfn, _iz = $(o.iframeZone) ||
    {}, _izi = $(o.izi) ||
    {}, _lo = $(o.loadingImage).css('opacity', '0'), _u, _dft, ie6 = $.browser.msie && $.browser.version == '6.0', publicVar = {}, hasinit = false;
    
    this.__time = __time = new getDateList({
        yearList: {
            id: '.getYearList',
            diy: '.displayYear',
            template: ['<a href="#" title="{%year%}">{%year%}</a>', '{%year%}']
        },
        monthList: {
            id: ".getMonthList",
            dim: '.displayMonth',
            template: ['<a href="#" title="{%month%}">{%month%}</a>', '{%month%}']
        },
        submitDate: '#submitDate',
        requestMethod: function(time){
            getListWeeklyList(time);
            return false;
        }
    });
    
    var csc = new createSingleCover({
        handle: '#weekly',
        close: '#closeWeekly',
        coverProperty: {
            id: '#weekly-cover',
            css: {
                'background': 'white',
                'position': 'absolute',
                'top': '0',
                'left': '0',
                'display': 'none',
                'opacity': '0',
                'zIndex': '10'
            },
            endOpacity: '0.7'
        },
        onOpen: function(){
            getListWeeklyList(__time.getCurrentTime());
            ie6 ? keepfixed(_f) : 1;
            _f.css('display', 'block')
            _f.animate({
                'opacity': '1'
            });
        },
        onBeforeClose: function(){
            _f.fadeOut(function(){
                $(this).css('opacity', '0')
            });
        }
    }).create();
    
    this.Run = function(opt_init){
    
        _nt = this.__time.getCurrentTime();
        _tr.end = this.__time.getEndDate();
        _tr.start = this.__time.getStartDate();
        
        var _RR = opt_init;
        _aSfn = _RR.ajaxStart ||
        function(){
        }, aSfn_ = _RR.ajaxStop ||
        function(){
        }, _u = _RR.requestUrl || '';
        _dft = _RR.dataFormat || false;
        //load 
        
        /* get box */
        {
            _f.oW = _f.outerWidth();
            _f.oH = _f.outerHeight();
        }
        
        //init 
        {
            if (ie6) {
                $(window).bind('scroll resize', function(e){
                    //if (publicVar.fieldZoneHasShow) {
                        keepfixed(_f);
                    //}
                })
                mouseBorder();
                _f.css({
                    'position': 'absolute',
                    'marginTop': '0'
                });
                
            }
        }
        //addEvent
        {
            _pbtn.click(function(){
                var k = __time.getCurrentTime()
                var _1 = k[0], _2 = k[1];
                if (_tr.start.join('') == _1 + '' + _2) {
                    ;
                }
                else {
                    _2 - 1 > 0 ? (_2 = _2 - 1) : (_1 = _1 - 1, _2 = 12);
                    __time.setNowTime(_1, _2,true);
                    getListWeeklyList([_1, _2]);
                }
                return false;
            });
            
            _nbtn.click(function(){
                var k = __time.getCurrentTime()
                var _1 = k[0], _2 = k[1];
                if (_tr.end.join('') == _1 + '' + _2) {
                    ;
                }
                else {
                    _2 + 1 <= 12 ? (_2 = _2 + 1) : (_1 = _1 + 1, _2 = 1);
                    __time.setNowTime(_1, _2,true);
                    getListWeeklyList([_1, _2]);
                }
                return false;
            });
        }
        return this;
    }
    
    /* position:fixed for ie6 */
    function keepfixed(_i){
        var $window = $(window), b;
        if ($window.height() > _i.oH) {
            b = $window.scrollTop() + ($window.height() - _i.oH) / 2 + 'px';
        }
        _i.css('top', b)
    }
    
    function mouseBorder(){
        _w.find('img').mouseover(function(){
            $(this).css('border-color', '#69ADDC');
        }).mouseout(function(){
            $(this).css('border-color', '#DEDDDC');
        });
    }
    
    function setWidth(){
        var _l = _w.find('li'), _bw = _l.eq(0).outerWidth(),_ls = _l.size(), w = _bw * _ls - parseInt(_l.eq(0).css('paddingRight'));
        if(!isNaN(w)){
			w = Math.abs(w) < 320 ? 320 : Math.abs(w);
		}else{
			w = 400
		}
		if(_l.size()==1){
			if(_l.eq(0).attr('empty')=='true'){
				var h = _l.find('a').html();
				_l.find('a').remove();
				_l.eq(0).append(h).css('textAlign','center');
				_l.find('img').css('cursor','default')
			}
			 _p.animate({
	            'width': w/2 + 'px'
	        });
		}else{
			 _p.animate({
	            'width': w + 'px'
	        });
			
		}
        _w.css({
	            'width': w * 2 + 'px'
	        });
        _f.animate({
            'width': 110 + w + 'px',
            'marginLeft': -(110 + w) / 2 + 'px'
        });
        
    }
    
    function getListWeeklyList(n){
        var _ru = _u, _fm = _dft;
        if (!_dft) {
            _ru = _ru.replace('{%year%}', n[0]).replace('{%month%}', n[1]);
            _fm = {}
        }
        else {
            for (var i in _dft) {
                if (_dft[i] == '{%year%}') {
                    _fm[i] = n[0]
                }
                if (_dft[i] == '{%month%}') {
                    _fm[i] = n[1]
                }
            }
        }
        var lazy = setTimeout(function(){
            _w.ajaxStart(function(){
                _aSfn(_w);
            }).ajaxStop(function(){
                aSfn_(_w);
            }).load(_ru, _fm, function(){
                if (ie6) {
                    mouseBorder();
                }
                _w.find('a').click(function(){
                    _iz.css({
                        'display': 'block'
                    });
                    _lo.css('display', 'block')
                    showIframe($(this).attr('rel'));
                    return false;
                });
                setWidth();
				clearTimeout(lazy)
            })
        }, 800)
    }
    
    function showIframe(src){
    
        _izi.append('<iframe frameborder="0" scrolling="no" hspace="0" src="' + src + '" id="iframe"></iframe>')
        
        var or = $('#iframe'), _c = $('#closeIframe'), o = or[0], h, w;
        
        _lo.css({
            'display': 'block',
            'opacity': '1'
        });
        
        or.load(function(){
            if (o.contentDocument && o.contentDocument.body.offsetHeight) {
                h = o.contentDocument.body.offsetHeight;
                w = o.contentDocument;
            }
            else 
                if (o.Document && o.Document.body.scrollHeight) {
                    h = o.Document.body.scrollHeight;
                    w = o.Document;
                }
                else 
                    if (o.contentDocument.height) {
                        h = o.contentDocument.height;
                        w = o.contentDocument;
                    }
                    else {
                        h = o.contentDocument.documentElement.offsetHeight;
                        w = o.contentDocument;
                    }
					
            w = $(w).find('a').attr('target','_blank').end().find('body table').eq(0).attr('align','center').width();
            
            w = w < 300 ? 1000 : w + 50;
            
            
            or.css({
                'height': h + 30 + 'px',
                'width': w + 'px'
            });
            _lo.fadeOut(function(){
                _lo.css('display', 'none');
            });
            
            _iz.animate({
                width: w + 50 + 'px',
                height: h + 80 + 'px',
                marginLeft: -(w + 50) / 2 + 'px',
                opacity: '1'
            })
            or.animate({
                width: '100%',
                height: '100%'
            });
        });
        
        _c.click(function(){
            or.remove();
            or.unbind('load')
            _iz.animate({
                'opacity': '0'
            }, function(){
                _iz.css({
                    width: '300px',
                    height: '200px',
                    marginLeft: '-100px',
                    display: 'none'
                })
            });
            return false;
        })
    }
    return this;
};

var roller = function(obj){
	var o = $(obj.obj) || {};
	var d = obj.duration || 2000;
	var many = obj.many || 3;
	var oh = o.height();
	var op = oh/2;
	o.html(o.html()+o.html());
	function r(){
	   o.animate({
		top : -oh
		},d,'linear',function(){
			o.css('top',0);
			r();
		})
	}
	r();
	
}

var arrow = function(options){
    var o = options ||
    {}, _l = $(o.mleft), _r = $(o.mright), _u, _b = $(o.loadZone), _c = 0;
    this.Run = function(opt_init){
        var _O = opt_init;
        _u = _O.requestUrl || '';
        this.max = _O.max || 0, _dft = _O.dateFormat || false;
        o.ol = _O.onLoad ||
        function(){
        };
        var k = consAd(_c);
        load(k[0], k[1])
    }
    var self = this;
    
    var max = self.max;
    function load(a, b){
    
        _b.html('载入中 ...');
        _b.load(a, b, function(html){
            o.ol(self, _c, html)
        });
        return self;
    }
    function consAd(r){
        var _ru = _u, _fm = _dft, __o = [];
        if (!_dft) {
            _ru = _ru.replace('{%current%}', r)
            _fm = {}
        }
        else {
            for (var i in _dft) {
                if (_dft[i] == '{%current%}') {
                    _fm[i] = r
                }
            }
        }
        
        __o = [_ru, _fm];
        return __o;
    }
    _l.click(function(){
        if (_c > 0) {
            _c--;
            var k = consAd(_c)
            load(k[0], k[1])
        }
    });
    
    _r.click(function(){
        if (_c <= self.max) {
            _c++;
            var k = consAd(_c)
            load(k[0], k[1])
        }
    });
}

var toggleBar = function(options){
    var o = options ||
    {}, $h = $(o.handle), $c = o.handleClass, $cu = o.handleCurrentClass, $l = $(o.toggleItem).eq(0).css('display', 'block').end();
    
    $h.each(function(index){
        var $t = $(this);
        $t.click(function(){
            $h.removeClass($cu).addClass($c);
            $t.addClass($cu);
            $l.css('display', 'none');
            $l.eq(index).css('display', 'block');
        })
    })
}

var weeklyGlobleFunction = {
    defaultPage: function(){
        this.getCkgsbByMonth = new getDateList({
            yearList: {
                id: '.getYearList2',
                diy: '.displayYear2',
                template: ['<a href="#" title="{%year%}">{%year%}</a>', '{%year%}']
            },
            monthList: {
                id: ".getMonthList2",
                dim: '.displayMonth2',
                template: ['<a href="#" title="{%month%}">{%month%}</a>', '{%month%}']
            },
            submitDate: '#submitCKGSB'
        });
        
        this.getWeekList = new weekly({
            fieldZone: '#fieldZone',
            weeklyListWrap: '#weeklyWrap',
            weeklyList: '#weeklyList',
            prev: '#prevMonth',
            next: '#nextMonth',
            iframeZone: '#iframeZone',
            izi: '#iframeZoneInner',
            loadingImage: '#loadingAnimation',
            iframe: '#iframe'
        });
        
        new toggleBar({
            handle: 'ul#tab li',
            handleClass: 'tabKey',
            handleCurrentClass: 'current',
            toggleItem: '.tabItemsValue'
        });
        
        this.getWeeklyByStep = new arrow({
            mleft: '#arrowLeft',
            mright: '#arrowRight',
            loadZone: '#getWeeklyEDM'
        });
        
        this.getCkgsbByStep = new arrow({
            mleft: '#arrowLeft2',
            mright: '#arrowRight2',
            loadZone: '#getChangJEDM'
        });
        return this;
    },
    weeklyPage: function(){
        this.createIframe = new getDateList({
            yearList: {
                id: '.getYearList2',
                diy: '.displayYear2',
                current: 'now',
                template: ['<a href="#" title="{%year%}">{%year%}</a>', '{%year%}']
            },
            monthList: {
                id: ".getMonthList2",
                dim: '.displayMonth2',
                template: ['<a href="#" title="{%month%}">{%month%}</a>', '{%month%}']
            },
            submitDate: '#submitCKGSB'
        });
		return this;
    }
}

