﻿/************************************************
** AUTHOR:    Guozhiyi  ( glonely@live.cn )    ** 
** DATA:      2008-08-03                       **
** COPYRIGHT: www.kugou.com                    **
************************************************/

var kg = {
    fnTrue: function() { return true; },
    fnFalse: function() { return false; },
    Browser: {
        navigator: window.navigator,
        ie: !!(window.attachEvent && !window.opera),
        opera: !!window.opera,
        safari: navigator.userAgent.indexOf('AppleWebKit/') > -1,
        moz: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
    }
};
kg.Class = {
    Create: function() {
        return function() {
            this.initialize.apply(this, arguments);
        }
    }
};
if (typeof ($) == "undefined") {
    $ = function(elem) {
        return document.getElementById(elem);
    }
}

if (typeof ($A) == "undefined") {
    $A = function(arg) {
        var result = [];
        for (var i = 0; i < arg.length; i++) {
            result.push(arg[i]);
        }
        return result;
    }
}

kg.extend = function(arg) {
    var srcs = $A(arguments);
    srcs.splice(0, 1);
    for (var i = 0; i < srcs.length; i++) {
        var src = srcs[i];
        for (var p in src) {
            arg[p] = src[p];
        }
    }
    return arg;
}

/**
**   Function
**/

kg.extend(Function.prototype, {
    argumentNames: function() {
        var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
        return names.length == 1 && !names[0] ? [] : names;
    },

    bind: function() {
        if (arguments.length < 2 && typeof arguments[0] == "undefined") return this;
        var __method = this, args = $A(arguments), object = args.shift();
        return function() {
            return __method.apply(object, args.concat($A(arguments)));
        }
    },

    bindAsEventListener: function() {
        var __method = this, args = $A(arguments), object = args.shift();
        return function(event) {
            return __method.apply(object, [(event || window.event)].concat(args).concat($A(arguments)));
        }
    }
});


/**
**   String
**/

kg.extend(
    String.prototype,
   {
       trim: function() {
           return this.replace(/^\s+|\s+$/g, "");
       },
       ltrim: function() {
           return this.replace(/^\s+/, "");
       },
       rtrim: function() {
           return this.replace(/\s+$/, "");
       },
       getBytes: function() {
           var bytes = 0;
           for (var i = 0; i < this.length; i++) {
               if (this.charCodeAt(i) > 256) { bytes += 2; }
               else { bytes += 1; }
           }
           return bytes;
       },
       intercept: function(length, appendStr) {
           var str = this;
           str = str.trim();
           if (str.getBytes() < length) return str;
           var countLen = 0;
           var charCount = 0;
           if (appendStr.length > 0) {
               length = length - appendStr.length;
           }
           for (var i = 0; i < str.length; i++) {
               if (this.charCodeAt(i) > 256) {
                   countLen += 2;
               }
               else {
                   countLen += 1;
               }
               if (countLen > length) {
                   break;
               }
               charCount++;
           }
           return str.substr(0, charCount) + appendStr;
       },
       include: function(str) {
           return this.indexOf(str) == 0;
       },
       toArray: function() {
           return this.split('');
       }
   }
);

/*****************
**   String
*****************/
kg.Cookie = {
    write: function(name, value, day) {
        var expires = "";
        if (day) {
            var dt = new Date();
            dt.setTime(dt.getTime() + (day * 24 * 60 * 60 * 1000));
            expires = "; expires=" + dt.toGMTString();
        }
        document.cookie = name + "=" + value + expires + "; path=\;"; /*domain=kugou.com*/
    },
    read: function(name) {
        var cookieValue = "";
        var search = name + "=";
        if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1) end = document.cookie.length;
                cookieValue = decodeURIComponent(document.cookie.substring(offset, end))
            }
        }
        return cookieValue;
    },
    readSingle: function(cookie, key) {
        var cookieValue = "";
        var search = cookie + "=";
        if (document.cookie.length > 0) {
            offset = document.cookie.indexOf(search);
            if (offset != -1) {
                offset += search.length;
                end = document.cookie.indexOf(";", offset);
                if (end == -1) end = document.cookie.length;
                var reg = new RegExp(key + "=([^&]*)?");
                var co = document.cookie.substring(offset, end);
                if (reg.test(co)) {
                    cookieValue = RegExp.$1;
                }
            }
        }
        return cookieValue;
    },
    remove: function(name) {
        this.write(name, "", -1);
    }
}

kg.Event = {
    stop: function(ent) {
        var e = ent || window.event;
        if (e.preventDefault) {
            e.preventDefault();
            e.stopPropagation();
        }
        else {
            e.returnValue = false;
            e.cancelBubble = true;
        }
    },
    add: function(elem, name, fn, useCapture) {
        if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || elem.attachEvent))
            name = 'keydown';
        if (elem.addEventListener) {
            elem.addEventListener(name, fn, useCapture);
        }
        if (elem.attachEvent) {
            elem.attachEvent("on" + name, fn);
        }
    },
    remove: function(elem, name, fn, useCapture) {
        if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || elem.attachEvent))
            name = 'keydown';
        if (elem.removeEventListener) {
            elem.removeEventListener(name, fn, useCapture);
        }
        else if (elem.detachEvent) {
            elem.detachEvent("on" + name, fn);
        }
    },
    getEvent: function() {
        if (window.event) {
            return this.formatEvent(window.event);
        } else {
            return this.getEvent.caller.arguments[0];
        }
    },
    formatEvent: function(oEvent) {
        if (kg.Browser.ie) {
            oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
            oEvent.eventPhase = 2;
            oEvent.isChar = (oEvent.charCode > 0);
            oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
            oEvent.pageY = oEvent.clientY + document.body.scrollTop;
            oEvent.preventDefault = function() {
                this.returnValue = false;
            };

            if (oEvent.type == "mouseout") {
                oEvent.relatedTarget = oEvent.toElement;
            } else if (oEvent.type == "mouseover") {
                oEvent.relatedTarget = oEvent.fromElement;
            }
            oEvent.stopPropagation = function() {
                this.cancelBubble = true;
            };
            oEvent.target = oEvent.srcElement;
            oEvent.time = (new Date).getTime();
        }
        return oEvent;
    }
}

kg.Va = {
    validate: function(o, reg) {
        return new RegExp(reg).test(o.value);
    }
}
/********************
** Element
********************/
kg.Element = {
    getStyle: function(element, style) {
        var elem = typeof element == "string" ? $(element) : element;
        if ('float' == style.toLowerCase() || 'cssFloat' == style.toLowerCase()) {
            style = (typeof elem.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
        }
        var value = elem.style[style];
        if (!value) {
            if (document.defaultView && document.defaultView.getComputedStyle) {
                var css = document.defaultView.getComputedStyle(elem, null);
                value = css ? css[style] : null;
            } else if (elem.currentStyle) {
                value = elem.currentStyle[style];
            }
        }
        return value || 0;
    }

}

/********************
** position
********************/
kg.Page = {
    pointer: function(e) {
        return { x: (e.pageX || e.clientX), y: (e.pageY || e.clientY) };
    },
    getWindowClientWidth: function() {
        return window.innerWidth
        || document.documentElement.clientWidth
        || document.body.clientWidth
        || 0;
    },
    getWindowClientHeight: function() {
        return window.innerHeight
        || document.documentElement.clientHeight
        || document.body.clientHeight
        || 0;
    },
    getWindowScrollWidth: function() {
        return window.scrollWidth
        || document.documentElement.scrollWidth
        || document.body.scrollWidth;
    },
    getWindowScrollHeight: function() {
        return window.scrollHeight
        || document.documentElement.scrollHeight
        || document.body.scrollHeight;
    },
    getWindowScrollLeft: function() {
        if (window.scrollWidth) {
            return window.scrollLeft;
        } else if (document.documentElement.scrollWidth) {
            return document.documentElement.scrollLeft;
        } else if (document.body.scrollWidth) {
            return document.body.scrollLeft
        } else {
            return 0;
        }
    },
    getWindowScrollTop: function() {
        if (window.scrollWidth) {
            return window.scrollTop;
        } else if (document.documentElement.scrollWidth) {
            return document.documentElement.scrollTop;
        } else if (document.body.scrollWidth) {
            return document.body.scrollTop;
        } else {
            return 0;
        }
    },
    getObjOffsetWidth: function(o) {
        return o.offsetWidth;
    },
    getObjOffsetHeight: function(o) {
        return o.offsetHeight;
    },
    getRealLeft: function(o) {
        var l = 0;
        while (o) {
            l += o.offsetLeft - o.scrollLeft;
            var border = parseInt(kg.Element.getStyle(o, "borderLeftWidth"));
            if (parseInt(border)) { l += border; }
            o = o.offsetParent;
        }
        return (l);
    },

    getRealTop: function(o) {
        var t = 0;
        while (o) {
            t += o.offsetTop - o.scrollTop;
            o = o.offsetParent;
        }
        return (t);
    },
    setFocus: function() {
        var colInputs = document.getElementsByTagName("input");
        for (var i = 0; i < colInputs.length; i++) {
            if (colInputs[i].type == "text" || colInputs[i].type == "password") {
                colInputs[i].focus();
                break;
            }
        }
    }
}

/*****************************************************  AJAX  ***********************************************
var url = "default3.aspx";    
var para = new kg.Ajax.Param();
para.$("id","11").$("ke","value")   
new kg.Ajax().Async(url,"GET",para.stringValue(),function(test){
var result = kg.Ajax.parseResult(test, {text: true});       
});
*************************************************************************************************************/


kg.Ajax = kg.Class.Create();
kg.extend(kg.Ajax.prototype, {
    initialize: function() {
        this.xmlhttp = false;
        this.isComplete = false;
        try { this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
        catch (e) {
            try { this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
            catch (e) {
                try { this.xmlhttp = new XMLHttpRequest(); }
                catch (e) { this.xmlhttp = false; }
            }
        }
    },
    Async: function(url, method, vars, callback) {
        if (!this.xmlhttp) return false;
        this.isComplete = false;
        try {
            if (method.toUpperCase() == "GET") {
                this.xmlhttp.open(method, vars ? (url + "?" + vars) : url, true);
                vars = "";
            } else {
                this.xmlhttp.open(method, url, true);
                this.xmlhttp.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
                this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            var _this = this;
            this.xmlhttp.onreadystatechange = function() {
                if (_this.xmlhttp.readyState == 4 && !_this.isComplete) {
                    _this.isComplete = true;
                    callback(_this.xmlhttp);
                }
            };
            this.xmlhttp.send(vars);
        } catch (z) {
            alert(z.message);
            return false;
        }
        return true;
    },
    Sync: function(url, method, vars, options) {
        if (!this.xmlhttp) return false;
        options = options ? options : { text: true, xml: false, json: false };
        this.isComplete = false;
        method = method.toUpperCase();
        try {
            if (method == "GET") {
                this.xmlhttp.open(method, url + "?" + vars, false);
                vars = "";
            } else {
                this.xmlhttp.open(method, url, false);
                this.xmlhttp.setRequestHeader("Method", "POST " + url + " HTTP/1.1");
                this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            }
            this.xmlhttp.send(vars);
        } catch (e) {
            alert(e.message);
            return false;
        }
        var o = {};
        if (options.text) {
            o["text"] = this.xmlhttp.responseText;
        }
        if (options.xml) {
            o["xml"] = this.xmlhttp.responseXML;
        }
        if (options.json) {
            o["json"] = eval("(" + this.xmlhttp.responseText + ")");
        }
        return o;
    }
});

kg.Ajax.Param = kg.Class.Create();
kg.extend(kg.Ajax.Param.prototype, {
    initialize: function() {
        this._m = {};
    },
    append: function(k, v) {
        this.put(k, v);
        return this;
    },
    $: function(k, v) {
        this.put(k, v);
        return this;
    },
    put: function(k, v) { return this._m["_" + k] = v; },
    stringValue: function() {
        var m = this._m;
        var s = "";
        var i = 0;
        var v = null;
        for (var k in m) {
            if (i++ > 0) {
                s += "&";
            }
            v = m[k];
            k = k.substring(1, k.length);
            s += k + "=" + encodeURIComponent(v);
        }
        return s;
    }

});

kg.Ajax.parseResult = function(xhq, options) {
    var opt = kg.extend({ text: true, xml: false, json: false }, options || {});
    var o = {};
    if (opt.text && xhq != null) {
        o["text"] = xhq.responseText;
    }
    if (opt.xml && xhq != null) {
        o["xml"] = xhq.responseXML;
    }
    if (opt.json && xhq != null) {
        o["json"] = eval("(" + xhq.responseText + ")");
    }
    return o;
}
kg.Ajax.quickFillGet = function(fillId, url, vars) {
    var ajax = new kg.Ajax();
    ajax.Async(
    url,
    "get",
    vars ? vars : "",
    function(xhq) {
        $(fillId).innerHTML = xhq.responseText;
    });
}


/**********************************************************************************************************************
** 
** autocomplete 
**
**********************************************************************************************************************/
kg.AutoComplete = kg.Class.Create();
kg.extend(kg.AutoComplete.prototype, {
    initialize: function(input, button, form, flag, searchUrl, submitUrl, top, left, width) {
        this.elem = $(input);
        this.searchUrl = searchUrl;
        this.submitUrl = submitUrl;
        this.top = top;
        this.left = left;
        this.width = width;
        this.btn = $(button);
        this.lastChars = "";
        this.index = 0;
        this.l_index = 0;
        this.entryCount = 0;
        this.tip = null;
        this.close = null;
        this.observer = null;
        this.mask = null;
        this.form = $(form);
        this.flag = flag;

        this.Event = {
            KEY_TAB: 9,
            KEY_RETURN: 13,
            KEY_ESC: 27,
            KEY_LEFT: 37,
            KEY_UP: 38,
            KEY_RIGHT: 39,
            KEY_DOWN: 40
        };

        this.elem.setAttribute('autocomplete', 'off');
        kg.Event.add(this.elem, "keypress", this.onkeypress.bindAsEventListener(this), false);
        kg.Event.add(this.elem, "blur", this.onblur.bindAsEventListener(this), false);
        kg.Event.add(this.btn, "click", this.onsubmit.bindAsEventListener(this), false);
    },
    onkeypress: function(e) {
        switch (e.keyCode) {
            case this.Event.KEY_LEFT:
            case this.Event.KEY_RIGHT:
                return;
            case this.Event.KEY_RETURN:
                this.onsubmit();
                kg.Event.stop(e);
                return;
            case this.Event.KEY_ESC:
            case this.Event.KEY_TAB:
                this.hide();
                kg.Event.stop(e);
                return;
            case this.Event.KEY_UP:
                this.PageReturn(false);
                return;
            case this.Event.KEY_DOWN:
                this.PageReturn(true);
                return;
            default:
                this.observer = setTimeout(this.update.bind(this), 400);
                return;
        }
    },
    createTip: function(text) {
        if (!this.tip && !this.mask) {
            this.mask = document.createElement("IFRAME");
            this.mask.style.allowTransparency = "allowTransparency";
            this.mask.style.filter = "Alpha(Opacity=0)";
            this.mask.style.border = "0px";
            this.mask.style.position = "absolute";
            document.body.appendChild(this.mask);

            this.tip = document.createElement("DIV");
            document.body.appendChild(this.tip);
            this.tip.className = "search_tip";
            this.mask.style.width = this.tip.style.width = kg.Page.getObjOffsetWidth(this.elem) - 2 + this.width + "px";
            this.mask.style.top = this.tip.style.top = kg.Page.getRealTop(this.elem) + kg.Page.getObjOffsetHeight(this.elem) + this.top + "px";
            var left = kg.Page.getRealLeft(this.elem);
            if (!kg.Browser.moz) {
                left = left - 1;
            }
            this.tip.style.left = left + this.left + "px";
        } else {
            this.tip.style.display = "block";
            this.mask.style.display = "block";
        }
        this.tip.innerHTML = this.setOptions(text);
        this.addevent(this.tip);
        this.createClose();
        this.tip.appendChild(this.close);
        this.mask.style.height = kg.Page.getObjOffsetHeight(this.tip) + "px";
        this.mask.style.left = kg.Page.getRealLeft(this.elem) + "px";
    },
    createClose: function() {
        this.close = document.createElement("div");
        this.close.className = "close";
        var link = document.createElement("a");
        link.href = "javascript:void(0)";
        link.innerHTML = "关闭";
        link.style.marginRight = "5px";
        kg.Event.add(link, "click", this.hide.bind(this), false);
        this.close.appendChild(link);
    },
    mouseover: function(o, index) {
        this.mouseout($("item" + (this.index)))
        this.index = index - 1;
        o.className = "over";
        o.childNodes[1].className = "c_over";
        this.elem.value = this.getText(o);

    },
    mouseout: function(o) {
        if (o) {
            o.className = "out";
            o.childNodes[1].className = "count";
        }
    },
    onclick: function(o) {
        this.elem.value = this.getText(o);
    },
    onsubmit: function() {
        if (this.elem.value == "输入你喜欢的歌曲或者歌手" || this.elem.value == "") {
            alert("请输入关键字!");
            kg.Event.stop(window.event);
            return;
        }
        this.form.target = this.flag ? "_blank" : "_self";
        this.form.action = this.submitUrl;
        this.form.method = "GET";
        this.form.submit();
    },
    update: function() {
        if (this.elem.value != "" && this.elem.value != this.lastChars) {
            this.lastChars = this.elem.value;
            var self = this;
            var param = new kg.Ajax.Param();
            param.$("k", self.elem.value.trim()).$("d", escape(Date()));
            new kg.Ajax().Async(self.searchUrl, "GET", param.stringValue(), function(text) {
                result = kg.Ajax.parseResult(text, { "json": true });
                if (result.json.IsSuccess && result.json.Error != "") {
                    self.createTip(result.json, self)
                }
                else {
                    self.hide();
                }
            });
        }
    },
    setOptions: function(result) {
        var item = [];
        var Info = JSON.parse(result.Error);
        this.entryCount = Info.Count;
        var k = this.index = Info.Count;
        for (var i = k - 1; i >= 0; i--) {
            item.push("<li id=\"item" + i + "\"><div class=\"result\">" + Info.Data[i].Keyword + "</div><div class=\"count\">" + Info.Data[i].ResultCount + "&nbsp;结果</div></li>");
        }
        return "<ul>" + item.join("") + "</ul>";
    },
    getText: function(o) {
        return o.firstChild.innerHTML.trim();
    },
    addevent: function(o) {
        var items = o.getElementsByTagName("li");
        var self = this;
        for (var i = 0; i < items.length; i++) {
            (function() {
                var temp = i;
                kg.Event.add(items[i], "click", function(e) { self.elem.onfocus(); self.onsubmit(e); }, false);
                kg.Event.add(items[i], "mouseover", function() { self.mouseover(items[temp], items.length - temp) }, false);
            })();
        }
    },
    PageReturn: function(flag) {
        this.l_last = this.index;
        if (flag) {
            this.index--;
        }
        else {
            this.index++;
        }
        if (this.index < 0) {
            this.index = this.entryCount - 1;
        }
        if (this.index >= this.entryCount) {
            this.index = 0;
        }
        var elem = $("item" + (this.index));
        if (elem) {
            elem.className = "over";
            elem.childNodes[1].className = "c_over";
            this.elem.value = this.getText(elem);
        }
        var l_elem = $("item" + (this.l_last));
        if (l_elem) {
            l_elem.className = "out";
            l_elem.childNodes[1].className = "count";
        }
    },
    onblur: function() {
        setTimeout(this.hide.bind(this), 250);
        if (this.elem.value)
            this.elem.value = this.elem.value;
        else
            this.elem.value = "输入你喜欢的歌曲或者歌手";
        this.elem.style.color = "#CECECE";
    },
    hide: function() {
        if (this.tip && this.mask) {
            this.tip.style.display = "none";
            this.mask.style.display = "none";
            this.index = -1;
            this.entryCount = 0;
            window.clearTimeout(this.observer);
        }
    }
});


/************************************    kg    end     ******************************************/


/**************************
**
** Add URL
**
**************************/
function addPostParam(sParams, sParamName, sParamValue) {
    if (sParams.length > 0) {
        sParams += "&";
    }
    return sParams + encodeURIComponent(sParamName) + "="
                   + encodeURIComponent(sParamValue);
}

function addURLParam(sURL, sParamName, sParamValue) {
    sURL += (sURL.indexOf("?") == -1 ? "?" : "&");
    sURL += encodeURIComponent(sParamName) + "=" + encodeURIComponent(sParamValue);
    return sURL;
}

/*JSON----start*/
if (!this.JSON) {
    JSON = function() {
        function f(n) { return n < 10 ? '0' + n : n; }
        Date.prototype.toJSON = function() {
            return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
        }; var m = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\\': '\\\\' }; function stringify(value, whitelist) {
            var a, i, k, l, r = /["\\\x00-\x1f\x7f-\x9f]/g, v; switch (typeof value) {
                case 'string': return r.test(value) ? '"' + value.replace(r, function(a) {
                    var c = m[a]; if (c) { return c; }
                    c = a.charCodeAt(); return '\\u00' + Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
                }) + '"' : '"' + value + '"'; case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': return String(value); case 'object': if (!value) { return 'null'; }
                    if (typeof value.toJSON === 'function') { return stringify(value.toJSON()); }
                    a = []; if (typeof value.length === 'number' && !(value.propertyIsEnumerable('length'))) {
                        l = value.length; for (i = 0; i < l; i += 1) { a.push(stringify(value[i], whitelist) || 'null'); }
                        return '[' + a.join(',') + ']';
                    }
                    if (whitelist) { l = whitelist.length; for (i = 0; i < l; i += 1) { k = whitelist[i]; if (typeof k === 'string') { v = stringify(value[k], whitelist); if (v) { a.push(stringify(k) + ':' + v); } } } } else { for (k in value) { if (typeof k === 'string') { v = stringify(value[k], whitelist); if (v) { a.push(stringify(k) + ':' + v); } } } }
                    return '{' + a.join(',') + '}';
            }
        }
        return { stringify: stringify, parse: function(text, filter) {
            var j; function walk(k, v) {
                var i, n; if (v && typeof v === 'object') { for (i in v) { if (Object.prototype.hasOwnProperty.apply(v, [i])) { n = walk(i, v[i]); if (n !== undefined) { v[i] = n; } else { delete v[i]; } } } }
                return filter(k, v);
            }
            if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { j = eval('(' + text + ')'); return typeof filter === 'function' ? walk('', j) : j; }
            throw new SyntaxError('parseJSON');
        }
        };
    } ();
}
/*JSON----end*/



//用来读取Url里的参数

Request = {
    QueryString: function(item) {
        var svalue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"));
        return svalue ? svalue[1] : svalue;
    }
}



//勋章兑换
function ShowIntegralWork(toUserID, toUserName, pid, aLink) {
    $("toUserID").value = toUserID;
    $("toUserName").innerHTML = toUserName;
    $("Work_Pid").value = pid;

    var top = kg.Page.getRealTop(aLink);
    var left = kg.Page.getRealLeft(aLink);
    $('IntegralWorkRim').style.top = (top + 20) + "px";
    $('IntegralWorkRim').style.left = (left - 200) + "px";
    $('IntegralWorkRim').style.display = "block";
}

function IntegralWork() {
    if ($("toUserID").value == "") {
        alert("错误，操作失败");
        return;
    }

    if ($("integral").value == "") {
        alert("请输入要操作的分数！");
        return;
    }

    var para = new kg.Ajax.Param();
    para.$("toUserID", $("toUserID").value).$("integral", $("integral").value).$("type", $("selectType").value).$("pid", $("Work_Pid").value);
    new kg.Ajax().Async("/aspx/NewPage/IntegralWork.aspx", "POST", para.stringValue(), function(retext) { IntegralWorkBack(retext); });
}

function IntegralWorkBack(result) {
    if (result.responseText == "ok") {
        alert("操作成功！");
    }
    else if (result.responseText == "todayo") {
        alert("错误:今天可操作积分不够。");
    }
    else if (result.responseText == "integralo") {
        alert("错误:您的积分不够本次操作。");
    }
    else if (result.responseText == "notlogin") {
        alert("错误:请登录后操作。");
    }
    else if (result.responseText == "oneself") {
        alert("错误:不可以对自己操作积分。");
    }
    else {
        alert("错误:操作失败，请稍后在试。");
    }

    $('IntegralWorkRim').style.display = "none";
}

function BuyCertificate(form) {
    var isSelect = false;
    var certificateID;
    for (var i = 0; i < form.elements.length; i++) {
        if (form.elements[i].type == "radio" && form.elements[i].checked) {
            //alert(form.elements[i].value);
            isSelect = true;
            certificateID = form.elements[i].value;
        }
    }

    if (!isSelect) {
        alert("请选择要兑换的证书！");
        return;
    }

    var para = new kg.Ajax.Param();
    para.$("CID", certificateID);
    new kg.Ajax().Async("/aspx/NewPage/BuyCertificate.aspx", "POST", para.stringValue(), function(retext) { BuyCertificateBack(retext); });
}

function BuyCertificateBack(result) {
    if (result.responseText == "ok") {
        alert("兑换成功！");
    }
    else if (result.responseText == "integralo") {
        alert("您的积分不够,要加油哦！");
    }
    else if (result.responseText == "monthNot") {
        alert("您本月已经兑换证书,限每月一次！");
    }
    else {
        alert("错误:操作失败，请稍后在试。");
    }

    $('BuyCertificateRim').style.display = "none";
}

function GetCertificate(aLink) {
    var para = new kg.Ajax.Param();
    para.$("date", "1");
    new kg.Ajax().Async("/aspx/NewPage/GetCertificate.aspx", "POST", para.stringValue(), function(retext) { GetCertificateBack(retext); });

    var top = kg.Page.getRealTop(aLink);
    var left = kg.Page.getRealLeft(aLink);
    $('BuyCertificateRim').style.top = (top + 150) + "px";
    $('BuyCertificateRim').style.left = (left - 200) + "px";
}

function GetCertificateBack(result) {
    var list = JSON.parse(result.responseText);
    if (list.length > 0) {
        var htmlList = "";
        for (var i = 0; i < list.length; i++) {
            htmlList += "<li>" +
                            "<img src=\"/images/medals/" + list[i].Image + "\" height=\"30px\" width=\"80px\" />" +
                            "<input type=\"radio\" id=\"" + list[i].ID + "\" name=\"selectCertificate\" value=\"" + list[i].ID + "\" />" +
                        "</li>";
        }
        $("insigniaList").innerHTML = htmlList;
    }
    $("BuyCertificateRim").style.display = "block";
}
//END 勋章兑换

function GetUserCookie() {
    var MyCookie = document.cookie.toLowerCase();
    re = /kugooid=(\d+)&/g;
    if (re.test(MyCookie)) {
        IsLogined = true;
        KugooID = RegExp.$1;
        re2 = /nickname=([^&]+)/g;
        re2.test(MyCookie);
        NickName = unescape(RegExp.$1).replace("+", " ").replace("+", " ");
        return KugooID;
    }
}

var kugooid = GetUserCookie();
//消息弹窗
var WinMessage = function(mList) {
    this.MsgList = new Array();
    this.IsShow = false;
    this.IsLogin = false;
    this.Winclose = kg.Cookie.read("Winclose");
    this.Winclose2 = kg.Cookie.read("Winclose2");

    if (kugooid != null && kugooid != undefined) {
        this.IsLogin = true;
    }

    if (mList.length > 0) {
        this.MsgList = mList;
        var othis = this;
        window.setInterval(function() { othis.ViewMessage(); }, 5000); //10000
        kg.Event.add(window, "scroll", function() { setTimeout(othis.SetMsgXY2, 0); setTimeout(othis.SetMsgXY, 0); }, false);
        kg.Event.add(window, "resize", othis.SetMsgXY, false);
        kg.Event.add(window, "resize", othis.SetMsgXY2, false);
    }
    if(location.href.indexOf("?test")>0)
	{
	alert("d");
	}
}
WinMessage.prototype.ViewMessage = function() {
    var showIDs = kg.Cookie.read("ShowIDs");
    if (kg.Cookie.read("Winclose") == "1") {
        this.ShowSmallWindow(); this.SetMsgXY2(74);
    } else {
        this.ShowBigWindow(); this.SetMsgXY(224);
    }


    if (this.IsLogin) {
        $("msg_body").style.height = "181px";
        $("msg_desc").style.display = "block";
    } else {
        $("msg_Rim").style.height = "163px";
        $("msg_body").style.height = "121px";
        $("msg_desc").style.display = "none";
        /*$("msg_bottom").style.backgroundImage = "url(/aspx/images/msg_bottom.jpg)";
        $("msg_bottom").style.width = "266px";
        $("msg_bottom").style.height = "18px";*/
    }

    if (this.IsShow)
    { return; }

    var view = false;
    var contentStr = "";
    var titleStr = "";
    for (var i = 0; i < this.MsgList.length; i++) {
        if (showIDs.indexOf(this.MsgList[i].ID) != -1) { continue; }

        this.MsgList[i].IsShow = 1;
        if (this.MsgList[i].Type == 1) {
            titleStr = "<div id=\"msg_title\"><a onclick=\"sdnClick(2766);\" href=\"http://bbs.kugou.com/usercpshowpm.aspx?pmid=" + this.MsgList[i].ID + "\" target=\"_blank\">" + this.MsgList[i].Title.intercept(18, '') + "</a>&nbsp;&nbsp;&nbsp;</div>";
            contentStr = "<div id=\"msg_content_rim2\">" +
                            "<div id=\"msg_content_value\">&nbsp;&nbsp;&nbsp;&nbsp;<a style=\"color:#000000\" target=\"_blank\" href=\"http://bbs.kugou.com/usercpshowpm.aspx?pmid=" + this.MsgList[i].ID + "\" onclick=\"sdnClick(2766);\">" + this.MsgList[i].Content.intercept(140, '...') + "</a></div>" +
                            "<span><a onclick=\"sdnClick(2766);\" href=\"http://bbs.kugou.com/usercpshowpm.aspx?pmid=" + this.MsgList[i].ID + "\" target=\"_blank\" style=\"color:#005AC5;text-decoration: underline;\">&gt;&gt;&nbsp;&nbsp;点击查看</a></span>" +
                         "</div>";
            view = true;
        }
        else {
            titleStr = "<div id=\"msg_title\"><a onclick=\"sdnClick(2767);\" href=\"" + this.MsgList[i].LinkUrl + "\" target=\"_blank\">" + this.MsgList[i].Title.intercept(18, '') + "</a>&nbsp;&nbsp;&nbsp;</div>";
            if (this.MsgList[i].ImgUrl != "") {
                contentStr = "<a onclick=\"sdnClick(2767);\" href=\"" + this.MsgList[i].LinkUrl + "\" target=\"_blank\"><img  id=\"ContentImage\" src=\"" + this.MsgList[i].ImgUrl + "\" alt=\"" + this.MsgList[i].Title + "\"/></a>" +
                             "<div id=\"msg_content_rim\">" +
                               "<div id=\"msg_content_value\">&nbsp;&nbsp;&nbsp;&nbsp;<a style=\"color:#000000\" target=\"_blank\" href=\"" + this.MsgList[i].LinkUrl + "\" onclick=\"sdnClick(2767);\">" + this.MsgList[i].Content.intercept(80, '...') + "</a></div>" +
                               "<span><a onclick=\"sdnClick(2767);\" href=\"" + this.MsgList[i].LinkUrl + "\" target=\"_blank\" style=\"color:#005AC5;text-decoration: underline;\">&gt;&gt;&nbsp;&nbsp;点击查看</a></span>";
                "</div>";
            }
            else {
                contentStr = "<div id=\"msg_content_rim2\">" +
                            "<div id=\"msg_content_value\">&nbsp;&nbsp;&nbsp;&nbsp;<a style=\"color:#000000\" target=\"_blank\" href=\"" + this.MsgList[i].LinkUrl + "\" onclick=\"sdnClick(2767);\">" + this.MsgList[i].Content.intercept(140, '...') + "</a></div>" +
                            "<span><a onclick=\"sdnClick(2767);\" href=\"" + this.MsgList[i].LinkUrl + "\" target=\"_blank\" style=\"color:#005AC5;text-decoration: underline;\">&gt;&gt;&nbsp;&nbsp;点击查看</a></span>" +
                         "</div>";
            }

            view = true;
            kg.Cookie.write("ShowIDs", showIDs + "," + this.MsgList[i].ID, 1);

            if (showIDs.split(',').length == this.MsgList.length) {
                kg.Cookie.write("ShowIDs", "", 1);
            }
        }
        break;
    }
    $("msg_content").innerHTML = titleStr + contentStr;

    if (view) {
        this.IsShow = true;
    }
}

WinMessage.prototype.SetMsgXY = function(WinTop) {
    var strP = /^\d*$/;
    if (!strP.test(WinTop)) {
        WinTop = 1;
    }
    this.isIE6 = false;
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var version = b_version.split(";");
    var trim_Version = version[1].replace(/[ ]/g, "");
    if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE6.0") {
        this.isIE6 = true;
    } else {
        this.isIE6 = false;
    }
    if (this.isIE6) {

    } else {
        $("msg_Rim").style.position = "fixed";
        $("msg_Rim").style.right = "0px";
        $("msg_Rim").style.bottom = "0px";
    }
}
WinMessage.prototype.SetMsgXY2 = function(WinTop) {
    var strP = /^\d*$/;
    if (!strP.test(WinTop)) {
        WinTop = 1;
    }
    this.isIE6 = false;
    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    var version = b_version.split(";");
    var trim_Version = version[1].replace(/[ ]/g, "");
    if (browser == "Microsoft Internet Explorer" && trim_Version == "MSIE6.0") {
        this.isIE6 = true;
    } else {
        this.isIE6 = false;
    }
    if (this.isIE6) {

    } else {
        $("msg_Rim2").style.position = "fixed";
        $("msg_Rim2").style.right = "0px";
        $("msg_Rim2").style.bottom = "1px";
    }
}

WinMessage.prototype.ShowBigWindow = function() {
    $("msg_Rim").style.display = "block";
    $("msg_Rim2").style.display = "none";
    kg.Cookie.write("Winclose", "0", 1);
    this.SetMsgXY(224);
    this.Winclose = 0;
}


WinMessage.prototype.ShowSmallWindow = function() {
    $("msg_Rim").style.display = "none";
    $("msg_Rim2").style.display = "block";
    this.SetMsgXY2(74);

    if (this.IsLogin) {
        $("msg_Rim2").style.display = "block";

        if (kg.Cookie.read("initvalue") == "1") {
            kg.Cookie.write("initvalue", "0");
        } else {
            kg.Cookie.write("initvalue", "1");
            kg.Cookie.write("Winclose", "1");
            this.Winclose = 1;
        }
    } else {
        $("msg_Rim2").style.display = "none";
        kg.Cookie.write("Winclose", "1", 1);
        this.Winclose = 1;
    }
}

WinMessage.prototype.CloseWindow = function() {
    if (this.IsLogin) {
        kg.Cookie.write("initvalue", "1");
        this.ShowSmallWindow();
    } else {
        new WinMessage(this.MsgList);
    }
}

WinMessage.prototype.HideWindow = function() {
    $("msg_Rim").style.display = "none";
}
//END 消息弹窗