/**
 * @author   杨煌<yanghuang@tomonline-inc.com>
 * @依赖于jQuery
 *
 */
(function() {
    //缓存处理机制
    var cache = (function() {
        var cache = function() {
            this.cacheBase = {};
        };
        cache.prototype = {
            get: function(pKey) {
                if( this.cacheBase[pKey] ) {
                    if( this.cacheBase[pKey].expire == 0 
                        ||this.cacheBase[pKey].expire < new Date().getTime()) {
                        return this.cacheBase[pKey].entry;
                    } else {
                        this.remove($pKey);
                        return false;
                    }
                } else {
                    return false;
                }
            },
            set: function(pKey, pContent, pExpire) {
                //默认为0,永不过期
                if (pExpire) {
                    pExpire = pExpire*1000 + new Date().getTime();
                } else {
                    pExpire = 0;
                }
                this.cacheBase[pKey] = {'entry':pContent, 'expire':pExpire};
            },
            remove: function(pKey) {
                this.cacheBase[pKey].expire = pExpire;
            },
            flush: function() {
                this.cacheBase = {};
            }
        };
        return new cache();
    })();
    var compiler = function() {
        this.vars = {};
    };
    compiler.prototype = {
        fetch: function(pTemplate) {
            return this.compile(pTemplate);
        },
        assign: function(pMixed, pVal) {
            if(typeof pMixed == 'object') {
                this.vars = pMixed;
            } else {
                this.vars[pMixed.toString()] = pVal.toString();
            }
        },
        compile: function(pStr) {
            var tThis   = this;
            //if
            var tIf = pStr.match(/\{if +?\$(\w).+\{\/if\}/ig);
            if(tIf) {
                $.each(tIf, 
                    function(pIndex, pMatch) {
                        var tCondition = pMatch.match(/\{if[^}]+\}/g);
                        var tPattern = new RegExp(pMatch.replace(/([\[\]{}$*?+.()^])/ig,'\\$1'), 'ig');
                        tCondition && (tCondition = tCondition[0]);
                        tCondition = tCondition.replace(/(?:\{if)|[$}]/g, '');
                        var tTrue = false;
                        with(tThis.vars) {
                            tTrue = eval(tCondition);
                        }
                        if (tTrue) {
                            var tReplace = pMatch.replace(/\{if[^}]+\}|\{\/if\}/g, '');
                            pStr = pStr.replace(tPattern, tReplace);
                        } else {
                            pStr = pStr.replace(tPattern, '');
                        }
                    }
                );
            }
            var matches = pStr.match(/\{\$[^}]*\}/ig);
            $.each(matches, 
                function(pIndex, pMatch) {
                    var tName = pMatch.replace(/[{}$]/g, '');
                    var tPattern = new RegExp(pMatch.replace(/([\]\[{}$*?+.()^])/ig,'\\$1'), 'ig');
                    pStr = pStr.replace(tPattern, tThis.vars[tName]);
                }
            );
            return pStr;
        },
        clearVars: function() {
            this.vars = {};
        }
    };
    var showUser = function() {
        this.tUrl = '/AJAX_LatestPlayer.php?uid={$uid}';
        this.template = '<div class="userbox"> <dl> <dt><a href="/User_UserCenter.php?userid={$user_id}&username={$layer_name}" target="_blank"><img src="{$pic_url}" onerror="this.src=tom.face.getURL(\'{$tom_username}\');" alt="" /></a></dt> <dd class="fw"><strong>{$nick_name}</strong> {$age}岁 {$sex}</dd> {if $state == 1}<dd>刚刚参加了<span><a target="_blank" href="/static-page/{$test_id}_cover.html">[{$title}]</a></span></dd>{/if} </dl> </div>';
        this.compiler = new compiler();
        this.tMess    = {};
        this.tMaxNum  = 0;
        this.tTimer   = {};
        this.tTimeout = 6000;
    };
    showUser.prototype = {
        init: function() {
            var tElements = $("a[uid]");
            var tThis     = this;
            $.each(tElements, function(pIndex, pEle) {
                var tSpan = $(pEle.parentNode);
                pEle = $(pEle);
                tSpan.hover(
                    function(pE) {
                        tThis.clearAllInfo();
                        tThis.getInfo(pEle, pE);
                    },
                    function(pE) {
                        var tIndex = 'mess_'+pEle.attr('uid');
                        var tCall  = function() {
                            tThis.removeInfo(tIndex);
                        }
                        tThis.tTimer[tIndex]
                            = window.setTimeout(tCall, tThis.tTimeout);
                    }
                );
            });
        },
        getInfo: function(pEle, pE) {
            var tUid = pEle.attr('uid');
            this.compiler.assign('uid', tUid);
            var tUrl  = this.compiler.fetch(this.tUrl);
            this.compiler.clearVars();
            var tThis = this;
            pEle = pEle.parent();
            var tParent = pEle.parent().parent();
            var tCallBack = function(data) {
                pEle.css('position', 'absolute');
                var tPosition = pEle.position();
                tPosition.top = tPosition.top+pEle.height();
                pEle.css('position', 'static');
                tThis.showInfo(data, tPosition, tParent, tUid);
            };
            var tCachKey = 'getUserInfo_'+tUid;
            var tData    = null;
            if(tData = cache.get(tCachKey)) {
                tCallBack(tData);
            } else {
                $.getJSON(tUrl, '',
                    function(data) {
                        tCallBack(data);
                        cache.set(tCachKey, data);
                    }
                )
            }
        },
        uniqueID: function(pPrefix, pSpan) {
            var prefix    = pPrefix || 'TOM_TEST';
            this.tMaxNum  = this.tMaxNum || 1;
            return prefix+this.tMaxNum++;
        },
        showInfo: function(pObj, tPosition, pTarget, pUid) {
            this.compiler.assign(pObj);
            var tHtml = this.compiler.fetch(this.template);
            this.compiler.clearVars();
            var tDom  = $(tHtml);
            var tID   = 'mess_'+pUid;
            tDom.attr('id', tID);
            tDom.css({
                'position' : 'absolute',
                'left': tPosition['left']+'px',
                'top': tPosition['top']+'px' 
            });
            //清除所有
            this.clearAllInfo();
            this.tMess[tID] = tDom;
            var tThis  = this;
            tDom.hover(
                function() {
                    window.clearTimeout(tThis.tTimer[tID]);
                },
                function() {
                    tThis.removeInfo(tID);
                }
            );
            pTarget.append(tDom);
        },
        removeInfo: function(pIndex) {
            this.tMess[pIndex]
                && this.tMess[pIndex].remove();
        },
        clearAllInfo: function() {
            var tThis = this;
            $.each(this.tMess,
                function(i, val) {
                    if(tThis.tMess[i]) {
                        tThis.tMess[i].remove();
                        tThis.tMess[i] = null;
                    }
                }
            );
            $.each(this.tTimer,
                function(i, val) {
                    if(tThis.tTimer[i]) {
                        window.clearTimeout(tThis.tTimer[i]);
                        tThis.tTimer[i] = null;
                    }
                }
            );
        }
    }
    $(document).ready(function() {
        var tUser = new showUser();
        tUser.init();
       $("#random").click(function(){
        	var tHref = this;
            $.ajax({
				type: "GET",
				url: "AJAX_RandomTest.php",
				async: false,
				success:function(data) {
					tHref.href = '/static-page/'+data+'_cover.html';
				}
			});
			 return true;
       })
    });
})();
