﻿String.prototype.lTrim = function() {
    return this.replace(/^[\s|&nbsp;]*/, "");
};
var randnum = function(){ now = new Date(); return now.getTime(); };
function widthCheck(name, maxLength) {
    if (!maxLength) {
        maxLength = 20;
    }
    if (name == null || name.length < 1) {
        return ["", ""];
    }
    var w = 0; //字符串长度，一个汉字长度为2
    var s = 0; //汉字个数
    var p = false; //判断字符串当前循环的前一个字符是否为汉字
    var b = false; //判断字符串当前循环的字符是否为汉字
    var nameSub;
    for (var i = 0; i < name.length; i++) {
        if (i > 1 && b == false) {
            p = false;
        }
        if (i > 1 && b == true) {
            p = true;
        }
        var c = name.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            w++;
            b = false;
        } else {
            w += 2;
            s++;
            b = true;
        }
        if (w > maxLength && i <= name.length - 1) {
            if (b == true && p == true) {
                nameSub = name.substring(0, i - 2) + "...";
            }
            if (b == false && p == false) {
                nameSub = name.substring(0, i - 3) + "...";
            }
            if (b == true && p == false) {
                nameSub = name.substring(0, i - 2) + "...";
            }
            if (p == true) {
                nameSub = name.substring(0, i - 2) + "...";
            }
            break;
        }
    }
    if (w <= maxLength) {
        return [name, ""];
    }
    return [nameSub, name];
}
Date.prototype.formatDate = function(cdti) {
    var dt = this;
    if (cdti !== undefined) {
        return cdti.replace(/(yyyy|nn|dd|hh|mm|ss|ms|wd)/ig, function($1) {
            switch ($1.toLowerCase()) {
                case 'yyyy': return dt.getFullYear();
                case 'nn': return padNum(dt.getMonth()+1, 0, 2);
                case 'dd': return padNum(dt.getDate(), 0, 2);
                case 'hh': return padNum(dt.getHours(), 0, 2);
                case 'mm': return padNum(dt.getMinutes(), 0, 2);
                case 'ss': return padNum(dt.getSeconds(), 0, 2);
                case 'ms': return padNum(dt.getMilliseconds(), 0, 3);
                case 'wd': return week(dt.getDay());
            }
        }
            )
    } else {
        return dt.getFullYear() + '-' + padNum(dt.getMonth(), 0, 2) +
            '-' + padNum(dt.getDate(), 0, 2);
    }
    function week(day) {
        switch (day) {
            case 0: day = '日'; break;
            case 1: day = '一'; break;
            case 2: day = '二'; break;
            case 3: day = '三'; break;
            case 4: day = '四'; break;
            case 5: day = '五'; break;
            case 6: day = '六'; break;
        }
        return day;
    }
    function padNum(str, num, len) {
        var temp = ''
        for (var i = 0; i < len; temp += num, i++);
        return temp = (temp += str).substr(temp.length - len);
    }
}
function QueryString(fieldName) {
    var urlString = document.location.search;
    if (urlString != null) {
        var typeQu = fieldName + "=";
        var urlEnd = urlString.indexOf(typeQu);
        if (urlEnd != -1) {
            var paramsUrl = urlString.substring(urlEnd + typeQu.length);
            var isEnd = paramsUrl.indexOf('&');
            if (isEnd != -1) {
                return paramsUrl.substring(0, isEnd);
            }
            else {
                return paramsUrl;
            }
        }
        else {
            return '';
        }
    }
    else {
        return '';
    }
}

var myPager = {
    pageNum: 1,
    pageSize: 20,
    totalCount: 0,
    totalPage: 0,
    getData: function() { },
    container: null,
    create: function() {
        if (!this.container)
            return alert('attribute "container" is essential.');

        var ps = '';
        if (this.pageNum - 1 > 0)
            ps += '<a href="javascript:void(0);" class="btnPrev eventTarget" pageNum="' + (this.pageNum - 1) + '"> << 上一页 </a>';

        var stratPN = 0, endPN = 0;

        if ((this.pageNum - 4) > 0)
            stratPN = this.pageNum - 4;
        else
            stratPN = 1;
        if (stratPN != 1) {
            ps += '<a href="javascript:void(0);" class="btnFirst">1</a><span>...</span>';
        }
        if (this.pageNum + 4 < this.totalPage)
            endPN = this.pageNum + 4;
        else
            endPN = this.totalPage;

        for (var i = stratPN; i <= endPN; i++) {
            if (i == this.pageNum) ps += '<a class="CURRENT">' + i + '</a>';
            else ps += '<a href="javascript:void(0);" class="eventTarget" pageNum="' + i + '">' + i + '</a>';
        }
        if (endPN != this.totalPage) {
            ps += '<span>...</span><a href="javascript:void(0);" class="eventTarget" pageNum="' + this.totalPage + '">' + this.totalPage + '</a>';
        }
        if (this.pageNum + 1 <= this.totalPage)
            ps += '<a href="javascript:void(0);" class="btnNext eventTarget" pageNum="' + (this.pageNum + 1) + '"> 下一页 >> </a>';
        ps += '<a href="javascript:void(0);" class="btnRefresh eventTarget" pageNum="' + (this.pageNum) + '"> 刷新 </a>';

        if (typeof this.container == 'object')
            $(this.container).html(ps);
        else if (this.container.indexOf('.') == 0) {
            $(this.container).each(function(i, dv) {
                $(dv).html(ps);
            });
        }
        var gd = this.getData;
        $('.eventTarget').each(function(i, btn) {
            $(btn).bind('click', function() {
                myPager.pageNum = $(this).attr('pageNum');
                gd();
            });
        });
    }
};

function vote(id) {
    $.ajax({
        url: "/script/req.aspx?voteid=" + id + "&g=" + randnum(),
        success: function(msg) {
            if (msg.indexOf('成功') != -1) {
                var a = $('#vote_' + id);
                if (a) {
                    a.html(Math.floor(a.html()) + 1);
                }
            }
            alert(msg);
        }
    });
}
function RemoveHTML(strText) {
    var regEx = /<[^>]*>/g;
    return strText.replace(regEx, "");
}
function unclick(tg) {
    var url = tg.attr('src');
    if (url && !tg.attr('current')) {
        tg.attr('src', url.replace('_o', '_c'));
        $('#dvSubmenu').remove();
        if (document.getElementById('ifm')) $('#ifm').remove();
        if (tg.attr('sm')) {
            tg.css({ 'position': '', 'z-index': '' });
        }
    }
}
function loadArticle(type, obj, reqObj, keys) {
    var template = '<div class="Item"><div class="itemTitle">{$Title}</div><div class="itemContent"><a href="/View.aspx?id={$ArticleId}">{$Content}</a></div><div class="itemBottom"><div>编 号：{$ArticleId}&nbsp;&nbsp;&nbsp;票 数：<span id="vote_{$ArticleId}">{$Vote}</span></div><div>作 者：{$AuthorName}</div><a href="javascript:vote(\'{$ArticleId}\');">投 票</a></div></div>';
    $.ajax({
    url: reqObj + "?page=1&pageSize=6&type=" + type + "&g=" + randnum() + (keys ? ('&' + keys) : ''),
        success: function(els) {
            els = eval(els);
            if(els.length == 0)
            {
                if(type==0)
                {
                    $("#textParent>.list1_content").hide();
                    $("#hideDiv").show();
                }
                else
                {
                    $("#picParent>.list1_content").hide();
                    $("#hideDiv1").show();
                }
                return;
            }
            for (var i = 0; i < els.length; i++) 
            {
                if (els[i].Type == 1) 
                {
		     //els[i].Content = '<div style="overflow:hidden;width:100%;"><div style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled= true,src=' + els[i].Content.replace('~/', '') + ', sizingMethod=scale);width:300px; height: 200px"></div></div>';
                    els[i].Content = '<img style="width:100%;height:100%" src="' + els[i].Content.replace('~/', '') + '" />';
                } 
                else 
                {
                    var temp = els[i].Title.indexOf("img");
                    if(temp != 1)
                    {
                        els[i].Content = '<div style="text-indent:24px;text-align:left;">' + widthCheck(RemoveHTML(els[i].Content), 130)[0].lTrim() + '</div>';
                    }
                    else
                    {
                        var textContent = $.ajax({type: "GET", url:els[i].Content,async: false,dataType:"text",processData:false,cache:false}).responseText;
                        //String textTemp = new String(ajax.getBytes(textContent),"gb2312");
                        els[i].Content = '<div style="text-indent:24px;text-align:left;">' + widthCheck(RemoveHTML(textContent), 130)[0].lTrim() + '</div>';                        
                    }
                }
                var html = template.replace(/(\{\$\w+\})/ig, function($1) {
                    switch ($1) {
                        case '{$Title}': return els[i].Title;
                        case '{$Content}': return els[i].Content;
                        case '{$AuthorArea}': return els[i].Author.Area;
                        case '{$AuthorName}': return els[i].Author.Name;
                        case '{$Vote}': return els[i].Vote;
                        case '{$DateCreated}': return els[i].DateCreated.formatDate('yyyy-nn-dd');
                        case '{$ArticleId}': return els[i].ArticleId;
                    }
                });
                obj.append(html);
            }
        }
    });
}
var thisMenu = null;
$(document).ready(function() {

    if (document.getElementById('top_menus')) {

        $('#top_menus').bind('mouseover', function(e) {
            var tg = $(e.target);
            if (thisMenu) {
                unclick(thisMenu);
            }
            thisMenu = tg;
            var url = tg.attr('src');
            if (url && !tg.attr('current')) {
                tg.attr('src', url.replace('_c', '_o'));
                if (tg.attr('sm')) {
                    tg.css({ 'position': 'relative', 'z-index': '999' });
                    var position = tg.position();

                    var dv = document.createElement('div');
                    dv.id = 'dvSubmenu';
                    dv.className = 'submenu';
                    dv.style.top = (position.top + 39) + 'px';
                    dv.style.left = (position.left - 1) + 'px';
                    dv.innerHTML = '<div class="dvContent" id="dvContent"></div><div class="dvBottom"></div>';
                    $('#top_menusCon').append(dv);

                    var sm = eval(tg.attr('sm'));
                    var sms = '';
                    for (var i = 0; i < sm.length; i++) {
                        for (var s in sm[i]) {
                            sms += '<a onmouseover="javascript:mover(this);" onmouseout="javascript:mout(this);" onclick="javascript:showSTList(this,\'' + sm[i][s] + '\');">' + s + '</a>';
                        }
                    }
                    $('#dvContent').html(sms);

                    var ifm = document.createElement('iframe');
                    ifm.style.top = (position.top + 39) + 'px';
                    ifm.style.left = (position.left - 1) + 'px';
                    ifm.frameborder = '0px';
                    ifm.className = 'ifm';
                    ifm.id = 'ifm';
                    ifm.style.height = ($('#dvContent').height() + 20) + 'px';
                    ifm.style.width = '120px';
                    $('#top_menusCon').append(ifm);

                    if (document.getElementById('stList1Con')) {
                        $('#stList1Con').remove();
                        $(document).unbind("click");
                    }
                }
            }
        });

        $('#top_menus').bind('mouseout', function(e) {
            $(document).bind('click', function(de) {
                var tg2 = $(de.target);
                var flag = false;
                while (tg2 && tg2.attr('tagName') != 'HTML') {
                    if (tg2.attr('id') == 'top_menusCon') {
                        flag = true;
                    }
                    tg2 = tg2.parent();
                }
                if (!flag) {
                    if (thisMenu) unclick(thisMenu);
                    if (document.getElementById('stList1Con')) {
                        $('#stList1Con').remove();
                    }
                    thisMenu = null;
                    $(document).unbind("click");
                }
            });
        });

    }
    if (document.getElementById('btnSearch')) {
        $('#btnSearch').bind('click', function() {
            if ($('searchKey').val() != '') {
                location = '/List.aspx?act=1&page=1&aType=' + $('#at').val() + '&uType=' + $('#ut').val() + '&t1=' + $('#searchKey').val();
            }
        });
    }
});
var areaClick = null;
function showSTList(tg, id) {
    if (id.indexOf('ID=') != 0) {
        location = id;
        return;
    } else {
        id = id.replace(/^ID=/, '');
    }
    if (areaClick) $(areaClick).css('background-color', '');
    areaClick = tg;
    if (document.getElementById('stList1Con')) {
        $('#stList1Con').remove();
        $(document).unbind("click");
    }
    var position = cumulativeOffset(tg);
    var dv = document.createElement('div');
    dv.style.top = (position.top) + 'px';
    dv.style.left = (position.left + 115) + 'px';
    dv.style.position = 'absolute';
    dv.className = 'stList1Con';
    dv.id = 'stList1Con';
    dv.innerHTML = '<div id="stList1_top"></div><div id="stList1"><img src="images/wait.gif" /></div><div id="stList1_bottom"></div>';
    document.body.appendChild(dv);
    
    var html = '<ul></ul>';
    $.ajax({
        url: "/Activity.aspx?id=" + id + "&g=" + randnum(),
        success: function(stArrStr) {
            var stArr = eval(stArrStr);
            if (stArr.length > 0) {
                for (var i = 0; i < stArr.length; i++) {
                    html += '<li><a href="/Station.aspx?s=' + stArr[i].ID + '">' + stArr[i].Name + '</a></li>';
                }
                html += '</ul>';
                $('#stList1').html(html);
            } else {
                setTimeout(function() {
                    $('#stList1').html('<span style="font-size:12px;color:gray;">&nbsp;&nbsp;没有站点...</span>');
                }, 300);
            }
            $(document).bind('click', function(de) {
                var tg2 = $(de.target);
                var flag = false;
                while (tg2 && tg2.attr('tagName') != 'HTML') {
                    if (tg2.attr('id') == 'stList1Con') {
                        flag = true;
                    }
                    tg2 = tg2.parent();
                }
                if (!flag) {
                    if (document.getElementById('stList1Con')) $('#stList1Con').remove();
                    if (thisMenu) unclick(thisMenu);
                    $(document).unbind("click");
                }
            });
        }
    });
}
function mover(o) {
    $(o).css('background-color', '#FAEAD8');
}
function mout(o) {
    if (areaClick && areaClick == o) return;
    $(o).css('background-color', '');
}
function returnOffset(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
}
function cumulativeOffset(element) {
    var valueT = 0, valueL = 0;
    do {
        valueT += element.offsetTop || 0;
        valueL += element.offsetLeft || 0;
        element = element.offsetParent;
    } while (element);
    return returnOffset(valueL, valueT);
}
function positionedOffset(element) {
    var valueT = 0, valueL = 0;
    do {
        valueT += element.offsetTop || 0;
        valueL += element.offsetLeft || 0;
        element = element.offsetParent;
        if (element) {
            if (element.tagName == 'BODY') break;
            var p = getStyle(element, 'position');
            if (p !== 'static') break;
        }
    } while (element);
    return returnOffset(valueL, valueT);
}
function getStyle(element, style) {
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : camelize(style);
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];
    if (style == 'opacity') {
        if (value = (getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
        return 1.0;
    }
    if (value == 'auto') {
        if ((style == 'width' || style == 'height') && (getStyle(element,'display') != 'none'))
        return element['offset' + capitalize(style)] + 'px';
        return null;
    }
    return value;
}
function camelize(s) {
    var parts = s.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = s.charAt(0) == '-' ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1) : parts[0];
    for (var i = 1; i < len; i++)
        camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
    return camelized;
}
function capitalize(s) {
    return s.charAt(0).toUpperCase() + s.substring(1).toLowerCase();
}


