﻿var TY = {
    site:"",
    Url:"http://www.91118.com",
    InterfaceUrl:"http://interface.91118.com",
    synPlayUrl:"http://www.91118.com/klxt/synclassroom/play/play_v2.aspx",
    synIndexUrl:"http://www.91118.com/synclassroom",
    findPasswordUrl:"/user/findpassword",
    suppInfoUrl:"http://www.91118.com/user/suppinfo",
    regUrl:"/user/reg",
    domain:".91118.com",
    path:"/",
    timer:"",
    IsOpenTimer:true,
    //单位秒
    timerInterval:60000,
    //单位天
    requestInterval:1/(24*60) * 5,
    //用户登录状态时间
    userStatusTime:1,
    breakReminderTime:1/24,
    breakReminderNum:2,
    loginOutUrl:"/klxt/LoginOutHandler.ashx",
    oldLoginOutUrl:"/user/logout.aspx",
    loginUrl:"/klxt/LoginHandler.ashx",
    loadStudyInfoUrl:"/klxt/synclassroom/LoadStudyInfo.ashx",
    resultsUrl:"/xiaowuManage/index.Aspx?my_url=ReortSortTable_Pro",
    onLineUrl:"http://www.91118.com/klxt/OnLineHandler.ashx",
    cookieSupport:function() {
        var isOk = (navigator.cookieEnabled) ? true : false;
        if (typeof(navigator.cookieEnabled) == "undefined" && !isOk)
        { 
            document.cookie = "test" 
            isOk = (document.cookie=="test") ? true : false;
            document.cookie = "" 
        }
        return isOk;
    },
    goHome:function(userId) {
        window.open(TY.Url + "/xiaowu/index.aspx?spaceid=" + userId);
    },
    getDomain:function() {
        var url = (window.location.host).toLocaleLowerCase();
        url = url.replace("www.", "");
        if (url.indexOf(".") != url.lastIndexOf("."))
            url = url.substr(url.indexOf(".") + 1);
	    if (url.indexOf(":") > 0)
	        url = url.substr(0, url.indexOf(":"));
        return "." + url;
    },
    isLogin:function(load) {
        var uid = TY.cookie("UserId");
        if (uid) {
            return true;
        } 
        if (typeof(load) != 'undefined' && load) {
            var info = TY.getUserInfo("UD", load);
            return (info && info.ID != "")
        }
    },
    getParam:function(key) {
        var reg = new RegExp("(^|\\?|&)"+ key+"=([^&]*)(\\s|&|$)", "i");
        if (reg.test(window.location.href)) {
            return RegExp.$2;
        } else {
            return "";
        }
    },
    reload:function(url) {
        if (null != url && typeof(url) != "undefined") {
            window.location.href = url;
        } else {
            window.location.reload();
        }
    },
    exit:function(callback) {
	    TY.setUserInfo(null);
	    $.getJSON(TY.Url + TY.loginOutUrl + "?jsoncallback=?");
		if (typeof(callback) == "undefined" || null == callback) {
		    TY.exit_callback();
		} else {
		    callback();
		}
		$.getJSON(TY.Url + TY.oldLoginOutUrl + "?jsoncallback=?");
    },
    exit_callback:function() {
        TY.reload();
    },
    loginInClientById:function(userId, verify, callback) {
        $.getJSON(TY.Url + TY.loginUrl + "?jsoncallback=?",{userId:userId, verify: verify, type: "getlogininfo", r: Math.random()}, function(json) {
            if (json.ret == 0) {
                TY.setUserInfo(json);
                var info = TY.getUserInfo();
                if (typeof(callback) != "undefined")
                    callback(info);
                return info;
            } else if (json.ret == -1) {
                alert("登录失败，参考信息：" + json.ret);
            } else if (json.ret == -3) {
                alert("登录时发生了异常，请与管理员联系");
            } else {
                alert("登录时发生了未知异常，请与管理员联系");
            }
            if (typeof(callback) != 'undefined') {
                TY.exit(callback);
            }
        });
    },
    loginInfoById:function(userId, callback) {
        if (typeof(userId) != 'undefined' && userId == 'e') {
            TY.exit(callback);
            return;
        }
        if (userId == 'otherlogin') {
            alert("已退出，您的帐号在别处登录！");
            TY.exit(callback);
            return;
        }
        if (TY.isLogin(false)) {
            var cinfo = TY.getUserInfo("CK");
            var uinfo = TY.getUserInfo("UD");
            if ((typeof(userId) =='undefined' || userId == "" || !uinfo) && cinfo) {
                TY.getUserInfoByClient(callback);
                return;
            } else if (cinfo && uinfo 
                             && $.trim(cinfo.ID) != "" 
                             && cinfo.ID == uinfo.ID 
                             && cinfo.ID == userId) {
                //如果客户端登录次数不一致，则更新用户数据
                if (typeof(cinfo.LC) != 'undefined' && !isNaN(cinfo.LC) 
                                                    && parseInt(cinfo.LC) > 0 
                                                    && cinfo.LC == uinfo.LC) {
                    callback(uinfo);
                } else {
                    TY.getUserInfoBySession(callback);
                }
                return;
            } else if (userId != "" && (!cinfo || userId != cinfo.ID || userId != uinfo.ID)) {
                TY.getUserInfoBySession(callback);
                return;
            }
            else {
                TY.exit(callback);
            }
        } else {
            if (typeof(userId) != 'undefined' && userId != '') {
                TY.getUserInfoBySession(callback);
                return;
            }
        }
        TY.setUserInfo(null);
        callback();
    },
    getUserInfo:function(type, load, callback) {
        if (typeof(type) == "undefined" || type == "UD") {
            var userInfo = TY.userData.peek('UserInfo');
	        if (null == userInfo || userInfo == "") {
	            if (typeof(load) != "undefined" && load)
	                userInfo = TY.getUserInfoByClient(callback);
	        }
	        if (!userInfo || null == userInfo || userInfo == "") {
	            return;
	        }
            var userInfo = "var info = " + userInfo;eval(userInfo);
            return info;
        } else {
            var userInfo = TY.cookie('UserInfo');
            if (null == userInfo || userInfo == "") return null;
            eval(userInfo);
            return info;
        }
    },
    setReloadInfoStatus:function() {
        var info = TY.getUserInfo("CK");
        var cookieInfo = "var info = {ID:'" + info.ID + "', VC:'" + info.VC + "',IS:'" + info.IS + "',LC:'-1'}"; 
        TY.cookie("UserInfo", cookieInfo, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
    },
    setUserInfo:function(json) {
        if (json === null) {
            TY.userData.push("UserInfo", "");
            TY.cookie("UserId", null, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
            TY.cookie("UserInfo", null, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
            TY.cookie("openReminderTimer", null, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
        } else {
            if (json) {
                TY.userData.push("UserInfo", "");
                TY.userData.push("UserInfo", json.data);
            }
            var info = TY.getUserInfo("UD");
            if (info === null || typeof(info) == 'undefined') return;
            var cookieInfo = "var info = {ID:'" + info.ID + "', VC:'" + info.VERIFYCODE + "',IS:'" + info.IS + "',LC:'" + info.LC + "'}";
            ///兼容老平台用户ID
            TY.cookie("UserId", info.ID, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
            TY.cookie("UserID", info.ID, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
            TY.cookie("UserInfo", cookieInfo, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
        }
    },
    getUserInfoByClient:function(callback) {
        if (TY.isLogin()) {
            var cinfo = TY.getUserInfo("CK");
            TY.loginInClientById(cinfo.ID, cinfo.VC, callback);
        } else {
            if (typeof(callback) != 'undefined') {
                TY.exit(callback);
            }
        }
        return false;
    },
    getUserInfoBySession:function(callback) {
        $.getJSON(TY.Url + TY.loginUrl + "?jsoncallback=?",{type: "getforsession", r: Math.random()}, function(json) {
            if (json.ret == 0) {
                TY.setUserInfo(json);
                var info = TY.getUserInfo("UD");
                if (typeof(callback) != "undefined")
                    callback(info);
                return info;
            } else {
                callback();
            }
            return false;
        });
    },
    userLogin:function(callback) {
        var name = $("#input_userName").val();
        var pwd = $("#input_userPwd").val();
        var userType = $("#input_userType").val();
        userType = typeof(userType) == 'undefined' ? "0" : userType;
        $.getJSON(TY.Url + TY.loginUrl + "?jsoncallback=?",{userName:name, password: pwd, type: "login", userType:userType, r: Math.random()}, function(json) {
		    if (json.ret == 0) {
		        TY.setUserInfo(json);
		        var info = TY.getUserInfo("CK");
		        if (info.IS == "1") {
		            ///资料补充
		            window.location.href = "http://www.91118.com/member/anomaly";
		            return;
		        }
		        if (typeof(callback) == 'undefined') {
		            if ($("#isCnc").val()) {
		                window.location.href = "http://www1.91118.com/synclassroom/";
		            }
		            TY.showLogin();
		        } else {
		            callback();
		        }
		    } else if (json.ret == -1) {
                TY.userData.push("UserInfo", "");
                alert("用户名或密码错误!如有疑问请与管理员联系!");
                $("#input_userPwd").focus();
                $("#input_userPwd").select();
                return;
            } else if (json.ret == -3) {
                TY.userData.push("UserInfo", "");
                alert("登录时发生了异常，请与管理员联系!");
            } else {
                TY.userData.push("UserInfo", "");
                alert("登录时发生了未知异常，请与管理员联系!");
            }
        });
    },
    addFriend:function(friendID) {
        if (TY.isLogin()) {
            $.getJSON(TY.InterfaceUrl + "/index/addFriendHandler.ashx?jsoncallback=?",{friendID:friendID},function(json) {
                alert(json.msg);        
            });
        } else {
            alert("请先登录！");
        }
    },
    initTimer:function() {
        if (!TY.IsOpenTimer) return;
        if (!TY.cookie("openTimer")) {
            TY.cookie("openTimer", "on", {expires:TY.requestInterval/2, path:TY.path, domain:TY.getDomain()});
        }
        if (!TY.cookie("openReminderTimer")) {
            TY.cookie("breakReminderNum", 0, {expires:1, path:TY.path, domain:TY.getDomain()});
            TY.cookie("openReminderTimer", "on", {expires:TY.breakReminderTime, path:TY.path, domain:TY.getDomain()});
        }
        TY.timer = setInterval(TY.pageTimer, TY.timerInterval);
    },
    pageTimer:function() {
        if (TY.IsOpenTimer) {
            if (null != TY.timer && TY.timer != "" && !TY.cookie("openTimer")) {
                clearInterval(TY.timer);
                if (TY.isLogin()) {
                    var info = TY.getUserInfo("CK");
                    $.getJSON(TY.onLineUrl + "?jsoncallback=?",{userId: info.ID, verify: info.VC, r: Math.random()}, function(json) {
                        if (json.ret == 0) {
                            TY.cookie("openTimer", "on", {expires:TY.requestInterval, path:TY.path, domain:TY.getDomain()});
                            if (json.data == 'isnull') {
                                TY.cookie("openReminderTimer", "on", {expires:TY.breakReminderTime, path:TY.path, domain:TY.getDomain()});
                            }
                            TY.timer = setInterval(TY.pageTimer, TY.timerInterval);
                        }
                    });
                } else {
                    clearInterval(TY.timer);
                }
            }
            if (TY.isLogin() && (!TY.cookie("openReminderTimer") || TY.cookie("openReminderTimer") == "loading")) {
                TY.cookie("openReminderTimer", "loading", {path:TY.path, domain:TY.getDomain()});
                var breakReminderNum = TY.cookie("breakReminderNum");
                if (parseInt(breakReminderNum) < TY.breakReminderNum) {
                    TY.playEye();
                }
            }
        } else {
            if (TY.timer)
                clearInterval(TY.timer);
        }
    },
    closeEye:function() {
        $("#msg-eye").remove();
    },
    playEye:function() {
        var info = TY.getUserInfo("UD");
	    if ($("#msg-eye").size() < 1) {
		    $("body").append("<div id=\"msg-eye\" style=\"position:absolute;width:0;height:0\"><iframe id=\"eye\" name=\"eye\" width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" src=\"about:blank\"><\/iframe></div>");
		    var name = null != info ? info.TN : "小朋友";
		    var breakReminderNum = TY.cookie("breakReminderNum");
			breakReminderNum ++;
		    $("#eye").attr("src","http://www.91118.com/klxt/synclassroom/eyeplay.aspx?username=" + escape(name) + "&flag=" + breakReminderNum);
	    }
    },
    uploadLeaveWord:function(messagecontent, messagetype) {
        if (!TY.isLogin()) {
            alert('请先登录，再发表评论！');
            return false;
        }
        var info=TY.getUserInfo("UD");
        if ($.trim(messagecontent)=="") {
            alert('内容不能为空！');
            return false;
        }
        $.getJSON(TY.InterfaceUrl + "/index/upwordhandler.ashx?jsoncallback=?", {userId:info.ID, messcon:messagecontent, messtype:messagetype, objID:"-1"},function(json) {
            if (json.ret != 1) {
                alert(json.msg);
            }
            if (json.ret == "1") {
                return true;
            } else {
                return false;
            }
        });
    },
    getGradeName:function(grade)
    {
        switch(grade)
        {
             case "1":
                 return "一年级";
             case "2":
                 return "二年级";
             case "3":
                 return "三年级";
             case "4":
                 return "四年级";
             case "5":
                 return "五年级";
             case "6":
                 return "六年级";
             case "7":
                 return "初中";
        }
    },
    cookie:function (name, value, options) {
		if (typeof(value) != 'undefined') {
			options = options || { };
			if (value === null) {
				value = '';
				options.expires = -1;
			}
			var expires = '';
			if (options.expires 
			    && (typeof(options.expires) == 'number' 
			        || options.expires.toUTCString)) {
				var date;
				if (typeof(options.expires) =='number') {
					date = new Date();
					date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
				} else {
					date=options.expires;
				}
				expires ='; expires=' + date.toUTCString();
			}
			var path = options.path ? '; path=' + options.path : '';
			var domain = options.domain ? '; domain=' + options.domain: '';
			var secure = options.secure ? '; secure' : '';
			document.cookie = [name, '=', escape(value), expires, path, domain, secure].join('');
		} else {
			var cookieValue=null;
			if (document.cookie && document.cookie != '') {
				var cookies = document.cookie.split(';');
				for (var i = 0; i < cookies.length; i ++) {
					var cookie = jQuery.trim(cookies[i]);
					if (cookie.substring(0, name.length + 1) == (name + '=')) {
						cookieValue = unescape(cookie.substring(name.length + 1));
						break;
					}
				}
			}
			return cookieValue;
		}
	},
	userData:function() {
	    return {
	        ie:!!document.all,
	        name:"91118_UserInfo",
	        init:function() {
		        if (this.ie) {
			        document.documentElement.addBehavior("#default#userdata");
		        }
	        },
	        push:function(key, value) {
	            if (this.ie) {
	                with (document.documentElement) 
	                try {
                        load(this.name);
                        setAttribute(key, value);
                        save(this.name);
                        return getAttribute(key);
                    } catch (ex) {
                        return null;
                    }
		        } else if(window.sessionStorage) {
			        try {
				        sessionStorage.setItem(key, value)
			        } catch (ex) {
				        return null;
			        }
		        }
	        },
	        peek:function(key) {
	            if (this.ie) {
			        with(document.documentElement) try {
                        load(this.name);
                        return getAttribute(key);
                    } catch (ex) {
                        //alert(ex.message);
                        return null;
                    }
		        } else if (window.sessionStorage) {
			        try {
				        return sessionStorage.getItem(key)
			        } catch (ex) {
				        return null;
			        }
		        }
	        },
	        remove:function(key) {
	            if (this.ie) {
			        with(document.documentElement) try {
                        load(this.name);
                        setAttribute(key, "");
                        expires = new Date(315532799000).toUTCString();
                        return getAttribute(key);
                    } catch (ex) {
                        //alert(ex.message);
                        return null;
                    }
		        } else if (window.sessionStorage) {
			        try {
				        return sessionStorage.removeItem(key)
			        } catch (ex) {
				        return null;
			        }
		        }
	        }
	    }
	}()
};

TY.userData.init();
TY.initTimer();