﻿var TY = {
    info:null,
    site:"",
    Url:"http://www.91118.com",
    InterfaceUrl:"http://interface.91118.com",
    synPlayUrl:"http://www.91118.com/klxt/synclassroom/play/play_v2.aspx",
    synIndexUrl:"/synclassroom",
    findPasswordUrl:"/member/recover-password",
    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/LoginHandler2.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) {
       if (TY.site != "139") {
          var homeUrl = (TY.site=="" ? "http://home.91118.com" : "");
          if(userId==''){
             userId =TY.cookie("UserId");
          }
          if(userId){
             window.open(homeUrl + "/" + userId);
          }else{
              window.open("http://www.91118.com/user/login.aspx");
          }          
       }
    },
    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;
        }
        return false;
        if (typeof(load) != 'undefined' && load) {
            var info = TY.getUserInfo("UD", load);
            return (info && info.ID != "")
        }
    },
    initLoginEvent:function() {
        $(".e-tab>a").each(function(i){
		    $(this).click(function(){
			    $(".e-tab>a").attr("class","").eq(i).attr("class","click");
			    $("#input_userType").val(i);
		    })
	    });
    },
    getParam:function(key) {
        var reg = new RegExp("(^|\\?|&)"+ key+"=([^&]*)(\\s|&|$)", "i");
        if (reg.test(window.location.href)) {
            return RegExp.$2;
        } else {
            return "";
        }
    },
    reload:function(url) {
        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();
    },  
    loadLoginInfo:function(userid, callback){
        $.getJSON(TY.Url  + "/klxt/loaduserinfo.ashx?jsoncallback=?", {userid:userid, r: Math.random()}, function(json){
            if (json.ret == 0) {
                var info = TY.getInfo(json);
                TY.setUserInfo(json);
                if (info.IS == "1") {
                    ///资料补充
                    window.location.href = "http://www.91118.com/member/anomaly";
                    return;
                }
                if((info.TN=='' || info.SC=='') &&(typeof(TY.site) == 'undefined' || TY.site == "www" || TY.site == "") && info.UT=='0'){
                     if (TY.cookie("NameisSet") == null || typeof(TY.cookie("NameisSet")) == 'undefined' || TY.cookie("NameisSet")=='1') {
                           TY.Syn.playIframe(TY.Url + "/klxt/member/temp.aspx", {w:500, h:160});
                        return;
                        }
                }
                if ((info.IS == "2"||info.IS == "3")  && info.UT=='0') {
                    if (TY.cookie("isSet") == null || typeof(TY.cookie("isSet")) == 'undefined' || TY.cookie("isSet")=='1') {
                       //TY.Syn.setTextBook(true);
                       TY.Syn.playIframe(TY.Url + "/klxt/member/temp.aspx", {w:500, h:160});
                        return;
                    }
                }
                if(info==null ||info.ID==''){
                    TY.exit();
                   // callback(null);
                    return;
                }else{
                    callback(info);
                }
            } else if (json.ret == -1) {
                callback(null);
            }
        });
    },
    userLogin:function(callback) {
        var name = $("#input_userName").val();
        var pwd = $("#input_userPwd").val();
        var userType = $("#input_userType").val();
        if ($.trim(name) == "") {
            alert("请输入登录用户名！");
            $("#input_userName").focus();
            return;
        }
        if ($.trim(pwd) == "") {
            alert("请输入登录密码！");
            $("#input_userPwd").focus();
            return;
        }
        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.cookie("userName", name, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
		        TY.cookie("userType", userType, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
                TY.cookie("UserId", json.data);
                if (typeof(callback) != 'undefined') {
		            callback(userType,json.data);
		        }
		    } else if (json.ret == -2) {
                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("登录时发生了未知异常，请与管理员联系!");
            }
        });
    },
    loginInfoById:function(userId, callback) {
        
        if (userId == 'otherlogin') {
            alert("已退出，您的帐号在别处登录！");
            TY.exit(callback);
            return;
        }
        if (typeof(userId) != 'undefined' && userId != 'e' && userId != '') {
            callback(0,userId);
            return;
        } else {
            TY.setUserInfo(null);
            $.getJSON(TY.Url + TY.loginOutUrl + "?jsoncallback=?");
            callback(0,'');
            return;
        }
    },
    loginInClientById:function(userId, verify, callback) {
        $.getJSON(TY.Url  + "/klxt/loaduserinfo.ashx?jsoncallback=?",{userId:userId, verify: verify, type: "getlogininfo", r: Math.random()}, function(json) {
            if (json.ret == 0) {
                TY.setUserInfo(json);
                TY.getUserInfo("UD", false, function(info) {
                    if (typeof(callback) != "undefined") {
                        callback(info.UT,info.ID);
                    }
                });
                return;
            } else if (json.ret == -1) {
                alert("登录失败，参考信息：" + json.ret);
            } else if (json.ret == -3) {
                alert("登录时发生了异常，请与管理员联系");
            } else {
                alert("登录时发生了未知异常，请与管理员联系");
            }
            if (typeof(callback) != 'undefined') {
                TY.exit(callback);
            }
        });
    },
    setUserInfo:function(json) {
        if (json === null) {
            TY.setReloadInfoStatus();
            TY.userData.push("UserInfo", "");
            TY.cookie("UserId", null, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});  
            TY.cookie("UserId", null);
            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 {
            var info = TY.getInfo(json);
            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()});
        }
    },
    delUserCache:function(userId, callback) {
        var id = '';
        if (typeof(userId) == 'undefined' || null == userId || $.trim(id) == "") {
            id = TY.cookie("UserId");
        }
        if ($.trim(id) != "") {
            $.getJSON("http://www.91118.com/klxt/interface/delusercachehandler.ashx?jsoncallback=?", {userId: id}, function() {
                TY.setReloadInfoStatus();
                TY.getUserInfo("UD", false, callback);
            });
        }
    },
    showLoginDiv:function(callback) {
            var html="";
          
            if(TY.site=="")
            {
                if (callback)
                    TY.reload = callback;
                html = "<div class=\"entrance\">";
                html += "<div class=\"top\">";
	            html += "<h2>用户登陆</h2>";
	            html += "<div class=\"e-tab\">";
		        html += "   <a href=\"javascript:void(0)\" class=\"click\"><span>学生（家长）</span></a><a href=\"javascript:void(0)\"><span>　老师　</span></a>";
	            html += "</div>";
                html += "</div>";
                html += "<ul class=\"content cb\">";
	            html += "<li>帐号：<input type=\"text\" id=\"input_userName\" size=\"12\" /></li>";
	            html += "<li>密码：<input type=\"password\" id=\"input_userPwd\" size=\"12\"/><input type=\"hidden\" id=\"input_userType\"/>";
	            html += "<input type=\"submit\" onclick=\"TY.userLogin(TY.reload);\" value=\"登陆\" class=\"btn-signin\" /></li>";
	            html += "<li><input type=\"radio\" name=\"isCnc\" checked/> 电信 <input id=\"isCnc\" type=\"radio\" name=\"isCnc\"/> 网通（联通）";
	            html += "</li>";
	            html += "<li><a href=\"" + TY.Url + TY.findPasswordUrl+ "\" class=\"forgot-password\">·忘记密码</a>";
	            html += "    <a href=\"" + TY.Url + TY.regUrl+ "\" class=\"regsiter\">免费注册</a>";
	            html += "</li>";
	            html += "</ul>";
                html += "<div class=\"bottom\"></div>";
                html += "</div>";
              }
            if(TY.site=="gd")
            {
               html += "<div class=\"gd-entrance\">";
			   html += "<div class=\"gd-entrance-top\"></div>";
			   html += "<div class=\"content\">";
			   html += "<a href=\"http://edu.gd.chinamobile.com/gdhtm/index.htm\"><img src=\"http://assets.91118.com/img/index/no-login.gif\" onmouseover=\"this.src='http://assets.91118.com/img/index/no-login-hover.gif'\" onmouseout=\"this.src='http://assets.91118.com/img/index/no-login.gif'\" border=\"0\" alt=\"登陆\" /></a>";
			   html += "</div>";
			   html += "<div class=\"gd-entrance-bottom\"></div>";
			   html += "</div>";
            }
            if(TY.site=="cy52")
            {
               html = "<div class=\"gd-entrance\">";
	           html += "<div class=\"gd-entrance-top\">";
			   html += "</div>";
               html += "<div class=\"content\">"; 
		       html += "<a href=\"http://91118.com/klxt/appservice/loginchange.aspx?appname=cy52\">";
		       html += "<img src=\"http://assets.91118.com/img/index/no-login-growth52.gif\" onmouseover=\"this.src='http://assets.91118.com/img/index/no-login-growth52-hover.gif'\" onmouseout=\"this.src='http://assets.91118.com/img/index/no-login-growth52.gif'\" />";
		       html += "</a>";
	           html += "</div><div class=\"gd-entrance-bottom\"></div>";
               html += "</div>";
            }
            $("#loginInfo").html(html);
	        
	        if(TY.cookie("userName")!=null && TY.site=="")
	        {
	              $("#input_userName").val(TY.cookie("userName"));
	         }
	         if(TY.cookie("userType")!=null && TY.site=="")
	        {
	             $("#input_userType").val(TY.cookie("userType"));
	            if($("#input_userType").val()==1)
	            {
	                 var tempHtml="   <a href=\"javascript:void(0)\" ><span>学生（家长）</span></a><a href=\"javascript:void(0)\" class=\"click\"><span>　老师　</span></a>";
	                  $("#loginInfo .e-tab").html(tempHtml);
	                 
	            }
	         }
	        TY.initLoginEvent();
            return html;
    },
    synUserInfo:function(userId, callback) {
        if (!userId || typeof(userId) == 'undefined')
            TY.delUserCache('', callback);
        else
            TY.delUserCache(userId, callback);
    },
    setReloadInfoStatus:function() {
        var info = TY.getUserInfo("CK");
        var uInfo = {ID:'', VC:'', IS:''};
        if (null != info && info) {
            uInfo.ID = info.ID;
            uInfo.VC = info.VC;
            uInfo.IS = info.IS;
        }
        cookieInfo = "var info = {ID:'" + uInfo.ID + "', VC:'" + uInfo.VC + "',IS:'" + uInfo.IS + "',LC:'0'}"; 
        TY.cookie("UserInfo", cookieInfo, {expires:TY.userStatusTime, path:TY.path, domain:TY.getDomain()});
    },
    suppInfo:function(info, callback) {
        try {
            if (typeof(info.IS) == 'undefined') {
                TY.getUserInfo("UD", false, function(info) {
                    if (info.IS == "1") {
                        ///资料补充
                        window.location.href = "http://www.91118.com/member/anomaly";
                        return;
                    }
                });
            } else {
                if (info.IS == "1") {
                    ///资料补充
                    window.location.href = "http://www.91118.com/member/anomaly";
                    return;
                }
                callback(info.UT,info.ID);
            }
        } catch (ex) {
            callback(info);
        }
    },
    getInfo:function(json) {
        var userInfo = "var info = " + json.data;
        eval(userInfo);
        return info;
    },
    getUserInfo:function(type, load, callback) {
        if (typeof(type) == "undefined" || type == "UD") {
            $.getJSON(TY.Url + TY.loginUrl + "?jsoncallback=?",{type: "getforsession", r: Math.random()}, function(json) {
                var tinfo = null;
                if (json.ret == 0) {
                    tinfo = TY.getInfo(json);
		            TY.setUserInfo(json);
                }
                if (typeof(callback) != 'undefined') {
                    callback(tinfo);
                }
                return false;
            });
        } else {
            var userInfo = TY.cookie('UserInfo');
            if (null == userInfo || userInfo == "") return null;
            eval(userInfo);
            return info;
        }
    },
    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  + "/klxt/loaduserinfo.ashx?jsoncallback=?", {userid:'', r: Math.random()}, function(json) {
            if (json.ret == 0) {
                TY.setUserInfo(json);
                TY.getUserInfo("UD", false, function(info) {
                    if (typeof(callback) != "undefined") {
                        TY.suppInfo(info, callback);
                    }
                });
                return true;
            } else {
                callback();
            }
            return false;
        });
    },
    addFriend:function(friendID) {
        if (TY.isLogin()) {
            $.getJSON(TY.InterfaceUrl + "/index/addFriendHandler.ashx?jsoncallback=?",{friendID:friendID},function(json) {
                alert(json.msg);        
            });
        } else {
            alert("请先登录！");
        }
    },
    closeMask:function() {
        $(".mask").remove();
        $(".mask").fadeOut(200, function() {
            if ($.browser.version = "6.0") {
                $("select").fadeIn();
            }
            $(this).remove();
        });
    },
    showMask:function() {	
	    if($(".mask").size() < 1) {
		    $("body").append("<div class=\"mask\"></div>");		
		    $(".mask").height($(document).height());
		    $(".mask iframe").height($(document).height());
		    if($.browser.version="6.0") $("select").fadeOut("slow");
	    }	
    },
    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(); 
         clearInterval(TY.timer);
        
    },
    playEye:function() {
        TY.loadLoginInfo(TY.cookie("UserId"), function(info) {
            if(typeof(info) != 'undefined' && info != '' && null != info && info.ID!='' && parseInt(info.UT)==0){
                if ($("#msg-eye").size() < 1) {
		            $("body").append("<div id=\"msg-eye\" style=\"position:absolute;width:550;height:400;\"><iframe id=\"eye\" name=\"eye\" width=\"550\" height=\"400\" frameborder=\"0\" scrolling=\"no\" src=\"about:blank\"><\/iframe></div>");
		            var name = null != info ? info.TN : "小朋友";
		            var breakReminderNum = TY.cookie("breakReminderNum");
			        breakReminderNum ++;
			        TY.cookie("breakReminderNum",breakReminderNum,{path:TY.path, domain:TY.getDomain()});
			        $("#msg-eye").css({left:($(window).width() - $("#msg-eye").innerWidth())/2});
			      $("#msg-eye").css({top:($(window).height() - $("#msg-eye").innerHeight())/2});
		            $("#eye").attr("src","http://www.91118.com/klxt/synclassroom/eyeplay.aspx?username=" + escape(name) + "&flag=" + breakReminderNum);
	            }
	        }
        });
    },
    uploadLeaveWord:function(messagecontent, messagetype,checkcode) {
        if (!TY.isLogin()) {
            alert('请先登录，再发表评论！');
            return false;
        }
        var info=TY.getUserInfo("UD", false, function(info) {
            if ($.trim(messagecontent)=="") {
                alert('内容不能为空！');
                return false;
            }
            $.getJSON(TY.InterfaceUrl + "/index/upwordhandler.ashx?jsoncallback=?", {userId:info.ID, messcon:messagecontent, messtype:messagetype, objID:"-1",checkcode:checkcode,truename:info.TN},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 = $.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:"91118UI_100401",
	        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();