window.console || (console = {
    log: function(msg) {
        document.title = msg;
    }
});
doU = {
    settings: {
        begin: '{{',
        end: '}}',
        varname: 'data'
    },
    template: function(tmpl, conf) {
        conf = conf || doU.settings;
        var str = '',
        tb = conf.begin,
        te = conf.end,
        m, l, arr = tmpl.replace(/\s*<!\[CDATA\[\s*|\s*\]\]>\s*|[\r\n\t]|(\/\*[\s\S]*?\*\/)/g, '').split(tb).join(te + '\x1b').split(te);
        for (var m = 0,
        l = arr.length; m < l; m++) {
            str += arr[m].charAt(0) !== '\x1b' ? "out+='" + arr[m].replace(/(\\|["'])/g, '\\$1') + "'": (arr[m].charAt(1) === '=' ? ';out+=(' + arr[m].substr(2) + ');': (arr[m].charAt(1) === '!' ? ';out+=(' + arr[m].substr(2) + ").toString().replace(/&(?!\\w+;)/g, '&#38;').split('<').join('&#60;').split('>').join('&#62;').split('" + '"' + "').join('&#34;').split(" + '"' + "'" + '"' + ").join('&#39;').split('/').join('&#x2F;');": ';' + arr[m].substr(1)));
        }
        str = ('var out="";' + str + ';return out;').split("out+='';").join('').split('var out="";out+=').join('var out=');
        try {
            return new Function(conf.varname, str);
        } catch(e) {
            throw e;
        }
    }
};
var Map = {
    '白羊座': {
        'd': '03.21-04.19',
        'i': 1,
        'c': '4'
    },
    '金牛座': {
        'd': '04.20-05.20',
        'i': 2,
        'c': '5'
    },
    '双子座': {
        'd': '05.21-06.21',
        'i': 3,
        'c': '6'
    },
    '巨蟹座': {
        'd': '06.22-07.22',
        'i': 4,
        'c': '7'
    },
    '狮子座': {
        'd': '07.23-08.22',
        'i': 5,
        'c': '8'
    },
    '处女座': {
        'd': '08.23-09.22',
        'i': 6,
        'c': '9'
    },
    '天秤座': {
        'd': '09.23-10.23',
        'i': 7,
        'c': '10'
    },
    '天蝎座': {
        'd': '10.24-11.22',
        'i': 8,
        'c': '11'
    },
    '射手座': {
        'd': '11.23-12.21',
        'i': 9,
        'c': '12'
    },
    '摩羯座': {
        'd': '12.22-01.19',
        'i': 10,
        'c': '1'
    },
    '水瓶座': {
        'd': '01.20-02.18',
        'i': 11,
        'c': '2'
    },
    '双鱼座': {
        'd': '02.19-03.20',
        'i': 12,
        'c': '3'
    }
};
function getMapIndex(xz) {
    return Map[xz]['c']
}
var Main = function() {
    var apps = {},
    num = 0,
    tabLists = $('#xz-tab>a'),
    highlightLi = tabLists.eq(0);
    return {
        add: function() {
			
            $.each(Array.prototype.slice.call(arguments),
            function() {
                apps[this.name] || (apps[this.name] = this);
                this.__UID = num++;
            });
        },
        create: function() {
            this.listen();
            this.events();
            this._run();
        },
        listen: function() {
            var _this = this;
            var hash = {
                'week': '您本周每日的运势曲线',
                'month': '您本月每周的运势曲线',
                'year': '您本年每月的运势曲线'
            };
            $(this).bind('APP_ACTIVE',
            function(event, app) {
                $('#ploader').show();
                tabLists.removeClass('app_bt_sc');
                highlightLi.addClass('app_bt_sc');
                $.each(apps,
                function() {
                    this.name === app.name || this.unActive();
                });
                this.activeApp = app;
                this.updateHeightPosition();
                if (app.chartType) {
                    $('#detail_tit').html(hash[app.chartType]);
                }
            });
            $(this).bind('APP_ONSHOW',
            function(event, app) {
                $('#ploader').hide();
                app.bindevent();
                var times = 0;
                function charts() {
					
                    if (!window.__SWF__ && times < 80) {
                        setTimeout(arguments.callee, 500);
                        console.log(times++);
                    } else if (window.__SWF__) {
                        _this.renderFlash(app);
                        $('div.fenlei input').eq(0).click();
                    } else {
                        console.log('flash charts error!');
                    }
                }
                charts();
            });
        },
        events: function() {
            var _this = this;
            tabLists.click(function() {
                if (this.className === 'guess' || highlightLi[0] === this) return false;
                var appname = $.trim(this.innerHTML);
                highlightLi = $(this);
                return apps[appname].active();
            });
            var r = 0,
            s = 1;
            $('#myset').click(function() {
                if (r === 1) return;
                r = 1;
                if (s) {
                    $('#xz_list').slideDown(function() {
                        r = 0;
                        updateHeight();
                        $('#myset').html('[收起]')
                    });
                    s = 0;
                } else {
                    $('#xz_list').slideUp(function() {
                        r = 0;
                        updateHeight();
                        $('#myset').html('[更换星座]')
                    });
                    s = 1;
                }
                return false;
            });
            var dd = $('#xz_list dd'),
            h = dd.find('div.plf');
            dd.click(function() {
                h.removeClass('on');
                var xz = $.trim($(this).find('div.plf').addClass('on').html().split('<')[0]);
                _this.display(xz);
                getIns('xingzuo').__cfg.xz = xz;
                getIns('xingzuo').__simpleSave(function() {});
                $('#details').html('星座-' + xz + '<span style="font-family:Tahoma"> （' + Map[xz]['d'] + '）</span>');
            });
            $('div.fenlei input').click(function() {
                _this.showChart(_this.dataTemp[this.value]);
            });
        },
        renderFlash: function(app) {
            if (!app.chartType) {
                return;
            }
			alert(this.xz)
            var chartData = Xbase[this.xz][app.chartType + '_charts'],
            xruling = [].concat(chartData.des);
            dataTemp = {},
            types = ['整体', '事业', '爱情', '财运'],
            des = ['最差', '不佳', '平平', '出运', '一级棒'];
            if (app.name === '明日运程') {
                $.each(xruling,
                function(i, d) {
                    var s = d.split('|');
                    if (s.length == 2) {
                        xruling[i] = s[0];
                        var j = i > 5 ? 0 : i + 1;
                        xruling[j] += '|' + s[1];
                        return false;
                    }
                })
            }
            $.each(types,
            function(k, v) {
                if (!dataTemp[v]) {
                    dataTemp[v] = {
                        Y: des,
                        V: []
                    };
                }
                $.each(xruling,
                function(i, d) {
                    var x = chartData[v][i];
                    dataTemp[v]['V'].push([d, x, x + '颗星']);
                })
            }) 
			this.dataTemp = dataTemp;
            this.showChart(dataTemp['整体']);
        },
        showChart: function(data) {
            window.__SWF__.setData(data);
        },
        _run: function(xz) {
            this.activeApp = Today;
            this.display(getIns('xingzuo').__cfg.xz || '白羊座');
            $('#xz_list .plf').removeClass('on').each(function() {
                var xz = $.trim($(this).html().split('<')[0]);
                if (xz == getIns('xingzuo').__cfg.xz) {
                    $(this).addClass('on');
                    $('#details').html('星座-' + xz + '<span style="font-family:Tahoma"> （' + Map[xz]['d'] + '）</span>');
                    return false;
                }
            });
        },
        display: function(xz) {
            this.xz = xz;
            this.activeApp.active(true);
        },
        updateHeightPosition: function() {
            var t = 300;
            if (!this.activeApp.chartType) t = -999;
            $('#flashchart').css('top', t);
        }
    }
} ();
var Xbase = function() {
    this.init.apply(this, arguments)
};
Xbase.prototype = {
    __UID: 0,
    _cache: {},
    init: function(name, tpl) {
        var _this = this;
        this.name = name;
        this.tpl = tpl;
    },
    active: function(always) {
        this._fire('APP_ACTIVE', [this]);
        if (this.actived && !always) return false;
        this.actived = true;
        this.requestAndRender();
    },
    requestAndRender: function() {
        var _this = this,
        xz = Main.xz,
		
        d = Map[xz];
        if (Xbase[xz]) {
            Templater.render(_this, Xbase[xz]);
            return;
        }
		
        $.getScript(G_dirUrl+'images/xingzuo/Ajax_value.asp?v=a&j='+d.i+"&t="+new Date(),
        function() {
            $xingzuo_data['__timstamp'] = d.d;
            $xingzuo_data['__class'] = 'a_' + d.c;
            Templater.render(_this, Xbase[xz] = $xingzuo_data);
        });
	
    },
    unActive: function() {
        this.actived = false;
        this.wrap && this.wrap.hide();
    },
    onshow: function(html) {		
        if (!this.wrap) {
            this.wrap = $('<div />').appendTo('#container').attr('id', '_' + this.__UID);
        }
        this.wrap.html(html).show();
        this._fire('APP_ONSHOW', [this]);
    },
    bindevent: function() {},
    _fire: function(eventType, args) {
        $(Main).trigger(eventType, args)
    }
};
var Templater = function() {
    var temp = {},
    compiledFn = {},
    VIEWDIR = 'views';
    return {
        render: function(app, data) {
            var _this = this;
            this.requestTpl(app.tpl,
            function(tpl) {
                _this.renderCallback(app, tpl, data);
            });
        },
        requestTpl: function(tpl, fn) {
			
            if (!temp[tpl]) {
                $.get(G_dirUrl + 'images/xingzuo/Ajax_value.asp?v=b&j=' + tpl+"&t="+new Date(),
                function(d) {
                    fn && fn(temp[tpl] = d)
                });
            } else {
                fn && fn(temp[tpl])
            }
        },
        renderCallback: function(app, html, data) {
            app.onshow(this.tpl(html, data));
            setTimeout(function() {
                updateHeight();
            },
            0);
        },
        tpl: function(temp, data) {
            if (!data) return temp;
            var k = temp.length;
            if (!compiledFn[k]) {
                compiledFn[k] = doU.template(temp);
            }
            return compiledFn[k](data);
        }
    }
} ();
var Year = $.extend(new Xbase('2011年运程', 'year01.html'), {
    submitModel: 1,
    _data: null,
    active: function() {
        if (!this.wrap) {
            var d = '<div id="_' + this.__UID + '"><div id="year01"></div><div id="year02"></div></div>';
            this.wrap = $(d).appendTo('#container');
        }
        Xbase.prototype.active.apply(this, arguments);
    },
    requestAndRender: function() {
        Templater.render(this, this._data);
    },
    requestYear: function() {
        var _this = this,
        name = $.trim($('#_NickName').val());
        if (!valide(name, 10)) {
            alert('昵称不能为空且不能超过10个字符或汉字！');
            $('#_NickName').focus(); 
			return false;
        }
        var birthday = [$('#iYear').val(), $('#iMonth').val(), $('#iDay').val()].join('-');
        var sexy = 0;
        $('input[name=iSex]').each(function() {
            if (this.checked) sexy = this.value
        });
        var p = $.param({
            'action': 'getYear',
            'name': name,
            'sexy': sexy,
            'birthDay': birthday
        });
        window.notiFy && notiFy('loading...');
        $.getScript('http://apps.1616.net/xingzuo/app.php?' + p,
        function() {
            for (var i = 1; i <= 12; i++) {
                var res = $xingzuo_data['result'],
                e = res['enemies_' + i],
                f = res['friends_' + i];
                $xingzuo_data['result']['enemies_' + i] = {
                    x: e.replace('座', ''),
                    c: 'c_' + getMapIndex(e)
                };
                $xingzuo_data['result']['friends_' + i] = {
                    x: f.replace('座', ''),
                    c: 'c_' + getMapIndex(e)
                };
            }
            $xingzuo_data.c = 'b_' + getMapIndex($xingzuo_data.result.astro_name);
            Templater.render(_this, $xingzuo_data);
            _this._data = $xingzuo_data;
            var j = $xingzuo_data['_current_month_'];
            setTimeout(function() {
                var tbl = $('#tbl')[0];
                tbl.rows[0].cells[j].className = 'focus_txt_month';
                tbl.rows[1].cells[j].className = 'focus_month';
                tbl.rows[2].cells[j].className = 'focus_month';
            },
            100);
        });
        return true;
    },
    switchModel: function(i) {
        this.submitModel = i;
        this.tpl = ['year02.html', 'year01.html'][ + i];
    },
    onshow: function(html) {
		
        var layer = this.submitModel ? $('#year01') : $('#year02');
        this.wrap.find('>div').hide();
        layer.html(html).show();
        this.wrap.show();
        this._fire('APP_ONSHOW', [this]);
    },
    bindevent: function() {
        var _this = this;
        $('#submit_year').unbind().click(function() {
            if (_this.requestYear() !== false) {
                _this.switchModel(0);
            }
            return false;
        });
        $('#_NickName').unbind().keyup(function(e) {
            if (e.keyCode === 13) {
                $('#submit_year').click();
            }
        });
        $('a.re_test').unbind().click(function() {
            _this.switchModel(1);
            _this.requestAndRender();
            return false;
        });
        var list = $('#ysresult_tab>li');
        list.unbind().click(function() {
            var i = list.index(this);
            list.removeClass('on');
            this.className = 'on';
            $('.ys_content').hide().eq(i).show();
            updateHeight();
        });
    }
});
var Zhanxing = $.extend(new Xbase('占星测算', 'cs_index.html'), {
    _data: null,
    onshow: function() {
        Xbase.prototype.onshow.apply(this, arguments);
        if (!this.lrcspTpl) {
            this.lrcspTpl = $('#lrcsp_tpl').html();
            this.cmgxjxTpl = $('#cmgxjx_tpl').html();
            this.rjxgxTpl = $('#rjxgx_tpl').html();
            this.mxpdTpl = $('#mxpd_tpl').html();
        }
        this.liveEvents();
    },
    liveEvents: function() {
        $('#container').delegate('a.re', 'click',
        function() {
            var layers = $(this).parents('div.mtop').prev().andSelf();
            console.log(layers);
            layers.eq(1).hide();
            layers.eq(0).show();
            updateHeight();
            return false;
        });
        function showSelect(area, sex) {
            var select = $('#_starname')[0];
            var allstars = STARS[area][0][sex];
            select.options.length = 0;
            $.each(allstars,
            function(k, v) {
                select.options.add(new Option(v));
            })
        }
        $('#_sex2, #_area').change(function() {
            var area = ['', '大陆', '港台', '欧美', '日韩'][ + $('#_area').val()];
            var sex = ['女', '男'][ + $('#_sex2').val()];
            showSelect(area, sex);
        });
        showSelect('大陆', '男');
    },
    bindevent: function() {
        var _this = this;
        $('#zxcs_tab li').unbind().click(function() {
            if (this.className === 'on') return false;
            _this.switchCase($('#zxcs_tab li').index(this));
            return false;
        });
        $('#lrcsp_submit').unbind().click(function() {
            var str = $('#lrcsp_form').serialize();
            $.getScript('app.php?action=LianRenChaoSuPei&' + str,
            function(e) {
                $('#supei>div').eq(0).hide();
                $('#supei>div').eq(1).html(Templater.tpl(_this.lrcspTpl, RESULT)).show();
                updateHeight();
            });
            return false;
        });
        $('#cmgxjx_submit').unbind().click(function() {
            var str = $('#cmgxjx_form').serialize();
            $.getScript('app.php?action=ChaoMengGeXingJieXi&' + str,
            function(e) {
                $('#chaomeng>div').eq(0).hide();
                $('#chaomeng>div').eq(1).html(Templater.tpl(_this.cmgxjxTpl, RESULT)).show();
                updateHeight();
            });
            return false;
        });
        $('#rjxgx_submit').unbind().click(function() {
            var nick1 = $.trim($('#rjxgx_form input[name=nickname]').val());
            var nick2 = $.trim($('#rjxgx_form input[name=nickname2]').val());
            if (!valide(nick1, 10) || !valide(nick2, 10)) {
                alert("呢称必须为中文或者字母，且长度小于10！"); 
				return false;
            }
            var str = $('#rjxgx_form').serialize();
            $.getScript('app.php?action=RenJiXingGuanXi&' + str,
            function(e) {
                console.log(RESULT);
                $('#renji>div').eq(0).hide();
                $('#renji>div').eq(1).html(Templater.tpl(_this.rjxgxTpl, RESULT)).show();
                updateHeight();
            });
            return false;
        });
        $('#mxpd_submit').unbind().click(function() {
            var n = $.trim($('#mxpd_form input[name=_yourname]').val());
            if (!valide(n, 10)) {
                alert("名字必须为中文或者字母，且长度小于10！");
				return false;
            }
            var str = $('#mxpd_form').serialize();
            $.getScript('app.php?action=MingXingPeiDui&' + str,
            function(e) {
                $('#mingxing>div').eq(0).hide();
                $('#mingxing>div').eq(1).html(Templater.tpl(_this.mxpdTpl, RESULT)).show();
                updateHeight();
            });
            return false;
        });
    },
    switchCase: function(i) {
        var layers = $('#supei,#chaomeng,#renji,#mingxing').hide();
        $('#zxcs_tab li').removeClass('on').eq(i).addClass('on');
        layers.eq(i).show();
        updateHeight();
    },
    requestAndRender: function() {
		
        var _this = this;
        if (!this.requestedStarJs) {
            $.getScript('js/stars.js',
            function() {
                Templater.render(_this, _this._data);
                _this.requestedStarJs = true;
            })
        } else {
            Templater.render(_this, _this._data);
        }
    }
});
var Today = new Xbase('今日运程', 'today.html');
var Tomorrow = new Xbase('明日运程', 'tomorrow.html');
var Week = new Xbase('本周运程', 'week.html');
var Month = new Xbase('本月运程', 'month.html');
Today.chartType = 'week';
Tomorrow.chartType = 'week';
Week.chartType = 'month';
Month.chartType = 'year';
Main.add(Today, Tomorrow, Week, Month, Year, Zhanxing);
var xingzuo = {
    init: function() {
        var _this = this;
    },
    save: function(v) {
        var T = this;
        this.__cfg.xz = v;
        this.__simpleSave(function(e) {
            if (e == 1) {
                T.request();
                notiFy('已保存您的星座')
            }
        })
    },
    adjustConfig: function() {
        if (!this.__cfg.xz) this.__cfg.xz = '白羊座';
    },
    __login: function() {
        this.adjustConfig();
        Main.create();
    },
    __logout: function() {
        this.adjustConfig();
        Main.create();
    }
};
if (parent && parent.J) {
/*    $('#ploader').hide();
    xingzuo.__cfg = {
        xz: '狮子座'
    }
    xingzuo.init();


    getIns = function() {
        return xingzuo;
    }
    Main.create();	*/
	
	
    parent.J.add('xingzuo', xingzuo, window);
    $(Main).bind('NEED_UPDATE_HEIGHT',
    function(event, height) {
        getIns('xingzuo').__updateHeight(true);
        $('#ploader').height($('body').height());
    })
	
	
/*	parent.J.add(
		'xingzuo', 
		{
			__keepAlive : 0,
			init : function(){
				var _this = this;
				window.onload = function(){
					_this.__updateHeight();
				}
			},
			__onUnload : function(){
				parent.$(parent).unbind('scroll');
			}
		}, 
		window
	);*/	
	
} else {
    $('#ploader').hide();
    xingzuo.__cfg = {
        xz: '狮子座'
    }
    xingzuo.init();


    getIns = function() {
        return xingzuo;
    }
    Main.create();
}
function updateHeight() {
    setTimeout(function() {
        $(Main).trigger('NEED_UPDATE_HEIGHT');
    },
    0);
}
$(function() {
    window.__DOMLOADED__ = true;
});
function getSWF(id) {
    var swf = window[id] || document[id];
    return navigator.userAgent.indexOf('MSIE 9.0') !== -1 ? swf[0] : (swf['1'] || swf);
}
function swfReady() {
    window.__SWF__ = getSWF('chartswf');
    console.log('called');
}
function valide(s, len) {
    return s && !s.match(/([^\u4E00-\u9FA5a-zA-Z])/g) && s.length <= len;
}