﻿/** 
 * @fileOverview 通用JS类
 * @author Tang Guohui 2010-4-19
 * @version 1.0.0
 */
window.HELP_PAGE_LIST = ['faq', 'faqaccount', 'faqim', 'faqserver', 'faqchannel', 'faqvoice', 'faqoverlay', 'faqfb'];

//PAGE_NAME赋值
window.PAGE_NAME;
var _pageName = getPageName();
if (_pageName) 
{
    if ($.inArray(_pageName, HELP_PAGE_LIST) != -1) 
        PAGE_NAME = 'help';
    else 
        PAGE_NAME = _pageName;
}
else 
{
    PAGE_NAME = 'index';
}

/**
 * getElementById快捷方式
 * @param {String} objId DOM ID
 * @return {DOM}
 */
function _$(objId)
{
    if (typeof(objId) == 'string') 
        return document.getElementById(objId);
    else 
        return objId;
}

/**
 * 设置Cookie
 * @param {String} key Cookie名称
 * @param {String} value Cookie值
 * @param {Bool} expire 是否过期，为真的话保存一年
 */
function setCookie(key, value, expire)
{
    if (expire == null) 
        expire = true;
    var d = '';
    if (expire) 
    {
        expires = new Date();
        expires.setTime(expires.getTime() + (1000 * 86400 * 365));
        var d = 'expires=' + expires.toGMTString() + '; '
    }
    document.cookie = key + '=' + escape(value) + '; ' + d + 'path=/'
}

/**
 * 获取Cookie值
 * @param {String} key Cookie Name
 * @return {Stirng|Null}
 */
function getCookie(key)
{
    cookie_name = key + '=';
    cookie_length = document.cookie.length;
    cookie_begin = 0;
    while (cookie_begin < cookie_length) 
    {
        value_begin = cookie_begin + cookie_name.length;
        if (document.cookie.substring(cookie_begin, value_begin) == cookie_name) 
        {
            var b = document.cookie.indexOf(';', value_begin);
            if (b == -1) 
            {
                b = cookie_length
            }
            return unescape(document.cookie.substring(value_begin, b))
        }
        cookie_begin = document.cookie.indexOf(' ', cookie_begin) + 1;
        if (cookie_begin == 0) 
        {
            break
        }
    }
    return null
}

/**
 * 删除Cookie
 * @param {String} key Cookie Name
 */
function delCookie(key)
{
    var b = new Date();
    document.cookie = key + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT' + '; path=/'
}

/**
 * 獲取字符長度，雙字節字符算兩單位長度
 * @param {String} value
 */
function getStrLen(value)
{
    var w = 0;
    for (var i = 0; i < value.length; i++) 
    {
        var c = value.charCodeAt(i);
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) 
            w++;
        else 
            w += 2;
    }
    return w;
}

/**
 * 获取一个值在数组中最先出现的索引
 * @param {Array} array 要查找的数组
 * @param {Object} value 要查找的值
 */
function arrayIndex(array, value)
{
    var index = -1;
    for (var i = 0, len = array.length; i < len; i++) 
    {
        if (array[i] === value) 
        {
            index = i;
            break;
        }
    }
    return index;
}

/**
 * 根据访问URL返回页面名称(小写)，如http://www.raidcall.com.tw/index.php 返回 index
 * @param {String} url
 */
function getPageName(url)
{
    var url = url || window.location.href;
    var matchUrl = url.match(/\/([a-z]+)\.(php|html)/i);
    var page = (matchUrl && matchUrl.length) ? matchUrl[1] : '';
    return page.toLowerCase();
}

/**
 * 获取当前页面URL包含的锚点名称
 */
function getAnchor()
{
    var anchor = '';
    var url = window.location.href;
    if (url.indexOf('#') != -1) 
        anchor = url.split('#')[1];
    return anchor;
}

/**
 * 从当前URL或给定URL中获取指定参数值
 * @param {String} varName 参数名
 * @param {String} url Http URL
 * @return {String} 指定URL参数值
 */
function getURLVar(varName, url)
{
    var url = url || window.location.href;
    var reg = new RegExp(".*[\?|&]" + varName + "=([^&#]+).*", "gi");
    if (url.match(reg)) 
    {
        var value = url.replace(reg, "$1");
        return value;
    }
    return '';
}

/**
 * 图像预加载
 * @param {String} imgUrlList 一至多个图片地址参数串
 */
function preLoadImage()
{
    var doc = document;
    if (doc.images) 
    {
        doc.preLoadImages = new Array();
        var arg = preLoadImage.arguments;
        for (var i = 0; i < arg.length; i++) 
        {
            doc.preLoadImages[i] = new Image();
            doc.preLoadImages[i].src = arg[i];
        }
    }
}

/**
 * 在IE下添加圆角支持
 * @param {String} selecter 要添加圆角的父对象jQuery选择器
 * @param {String|Array} rounds 添加圆角样式名称，如果只指定一个请使用字符串参数，还可以这样分别指定['round1','round2',null,null]
 * @param {String} tagName 圆角窗口标签名称，默认b
 */
function ieRound(selecter, rounds, tagName)
{
    if ($.browser.msie && parseInt($.browser.version) < 9) 
    {
        var target = $(selecter).css('position', 'relative');
        if (typeof(rounds) == 'string') 
        {
            if (!$('.' + rounds).length) 
            {
                target.append($().add(getItem(rounds, 1, tagName)).add(getItem(rounds, 2, tagName)).add(getItem(rounds, 3, tagName)).add(getItem(rounds, 4, tagName)));
            }
        }
        else 
        {
            if (rounds && rounds.length == 4) 
            {
                var temp = $();
                for (var i = 0; i < 4; i++) 
                {
                    if (!rounds[i]) 
                    {
                        continue;
                    }
                    temp.add(getItem(rounds[i], i + 1, tagName));
                }
                target.append(temp);
            }
        }
        
        function getItem(roundName, index, tagName)
        {
            tagName = tagName || 'b';
            var indexClass = [null, 'round-0-0', 'round-1-0', 'round-1-1', 'round-0-1'];
            var item = $('<' + tagName + '/>').addClass(roundName).addClass(indexClass[index]);
            return item;
        }
    }
}

/**
 * 相对浏览器窗口居中图层,常用于弹出式对话框
 * @param {String} boxId 对话框DOM ID
 */
function centerDiv(boxId)
{
    var jqObj = $('#' + boxId);
    if (jqObj.length)
    {
        var mLeft = jqObj.outerWidth() / 2 * -1 + document.documentElement.scrollLeft + document.body.scrollLeft + 'px';
        var mTop = jqObj.outerHeight() / 2 * -1 + document.documentElement.scrollTop + document.body.scrollTop + 'px';
        jqObj.css(
        {
            position: 'absolute',
            left: '50%',
            top: '50%',
            marginLeft: mLeft,
            marginTop: mTop
        });
        setTimeout('centerDiv("' + boxId + '")', 200);
    }
}

var Alert = 
{
    show: function(msg, right)
    {
        this.close();
        
        var html = '<div id="dialog" class="dialog">';
        html += '<h5><a href="javascript:;" onclick="Alert.close();" title="關閉提示"></a>提示</h5>';
        html += '<div' + (right ? ' class="rightIcon"' : '') + '>' + msg + '</div>';
        html += '<p><a href="javascript:;" onclick="Alert.close();">確認</a></p>';
        html += '</div>';
        
        $('body').append(html);
        
        centerDiv('dialog');
    },
    close: function()
    {
        $('div#dialog').remove();
    }
};

/**
 * 初始化一个列表展示效果
 * @param {String} selecter jQuery选择器表达式
 */
function initListShow(selecter)
{
    var handles = $(selecter);
    handles.click(function()
    {
        handles.not(this).parent().addClass('closed');
        $(this).parent().toggleClass('closed');
        return false;
    });
}

/**
 * 自动设置当前导航高亮选中状态（header主导航）
 */
function setCurrentNav()
{
    var getIndex = function(pageName)
    {
        for (var i = 0; i < dict.length; i++) 
        {
            for (var a = 0; a < dict[i].length; a++) 
            {
                if (dict[i][a] == pageName) 
                    return i;
            }
        }
    };
    
    var page = getPageName() || 'index';
    var dict = [['index'], ['features'], ['download'], ['faq', 'faqaccount', 'faqserver', 'faqchannel', 'faqvoice', 'faqmanage', 'faqoverlay'], ['esports'], ['contactus'], ['forum']];
    $('ul.menu li').removeClass('current').eq(getIndex(page)).addClass('current');
}

/**
 * 固定回到页头按钮
 */
function stayTopBtn()
{
    var scrollTop = document.documentElement.scrollTop;
    $('#go-top-btn').css(
    {
        position: 'absolute',
        top: document.documentElement.clientHeight + scrollTop - 23 + 'px',
        right: '10px',
        display: scrollTop > 10 ? 'inline' : 'none'
    });
    setTimeout('stayTopBtn()', 100);
}

/**
 * 定时更新软件下载统计数据
 */
function getDownCount()
{
    var li = $('li.down-count');
    if (li.length) 
    {
        $.get('', function(data)
        {
            li.find('span').text(data);
        });
        setTimeout('getDownCount()', 5000);
    }
}

/**
 * 自动设置当前导航高亮选中状态（新手指南左边导航）
 */
function setCurrentHelpNav()
{
    var page = getPageName() || 'faq';
    $('ul.help-menu a').removeAttr('class').eq(arrayIndex(HELP_PAGE_LIST, page)).addClass('current');
}

/**
 * 设置FAQ帮助页面每条帮助的链接地址，主要供复制分享
 */
function setHelpNodeLink()
{
    $('div.help-node > h5').each(function(index)
    {
        var self = $(this);
        var node = index + 1;
        var url = getPageName() + '.php#' + node;
        self.html('<a href="' + url + '">' + self.text() + '</a>');
        self.click(function()
        {
            document.location.hash = node;
            $(this).find('a').blur();
        });
    });
}

/**
 * 根据URL FaqNode参数显示指定条目帮助信息
 */
function showHelpByNode()
{
    //支持 faq.php?faqnode=1 与 faq.php#1 查看方式
    var nodeNum = getURLVar('FaqNode') || getAnchor();
    if (nodeNum) 
    {
        var currentNode = $('#help-content>div').addClass('closed').eq(parseInt(nodeNum) - 1).removeClass('closed');
        if (currentNode.length) 
            $(document).scrollTop(currentNode.offset().top);
    }
}

/**
 * 邀請表單靜態類
 */
var invite = 
{
    cookieTime: 30 * 60 * 1000,
    addEmail: function()
    {
        var list = $('#send_email_list');
        var newItem = list.children(':first').clone();
        newItem.find('input:first').val('');
        list.append(newItem);
    },
    removeEmail: function(btn)
    {
        if ($('#send_email_list').children().length > 1) 
            $(btn).parent().remove();
    },
    sendEmail: function()
    {
        var title = $('#emial_title').val();
        var cont = $('#email_cont').val();
        var name = $('#user_name').val();
        if (title == '') 
        {
            Alert.show(tip_mail_title_required);
            _$('emial_title').focus();
            return false;
        }
        if (cont == '') 
        {
            Alert.show(tip_invite_content_required);
            _$('email_cont').focus();
            return false;
        }
        if (name == '') 
        {
            Alert.show(tip_your_name_required);
            _$('user_name').focus();
            return false;
        }
        
        var hasErr = false;
        var mailList = '';
        $('#send_email_list input[type=text]').each(function(i)
        {
            if (!/^\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test($.trim(this.value))) 
            {
                Alert.show(tip_invite_mail_err);
                this.focus();
                hasErr = true;
                return false;
            }
            mailList += this.value + ';';
        });
        $('#emailtxt').val(mailList);
        if (!hasErr) 
            $("#inviteform").submit();
    },
    sendFacebook: function()
    {
        var fbCont = $('#fbCont').val();
        
        if (fbCont == '') 
        {
            Alert.show(tip_invite_content_required);
            _$('fbCont').focus();
            return false;
        }
        if (fbCont.length > 140) 
        {
            Alert.show(tip_invite_content_limit);
            _$('fbCont').focus();
            return false;
        }
        
        var strid = 'sid=' + $('#sid').val();
        fbCont = /.*[\u4e00-\u9fa5]+.*$/.test(fbCont) ? escape(fbCont) : fbCont;
        setCookie('strid', strid, this.cookieTime);
        setCookie('fbCont', fbCont, this.cookieTime);
        window.open('http://www.raidcall.com/fb/home.php');
    },
    sendTwitter: function()
    {
        var twitCont = $('#twitCont').val();
        
        if (twitCont == '') 
        {
            Alert.show(tip_invite_content_required);
            _$('twitCont').focus();
            return false;
        }
        if (twitCont.length > 140) 
        {
            Alert.show(tip_invite_content_limit);
            _$('twitCont').focus();
            return false;
        }
        if (!/http:\/\/www\.raidcall\.com\.tw\/signup\.php\?sid=\d+/.test(twitCont)) 
        {
            Alert.show(tip_invite_content_url);
            _$('twitCont').focus();
            return false;
        }
        
        twitCont = /.*[\u4e00-\u9fa5]+.*$/.test(twitCont) ? escape(twitCont) : twitCont;
        setCookie('twitCont', twitCont, this.cookieTime);
        window.open('http://www.raidcall.com/twip2/redirect.php');
    }
};

/**
 * 生成語音群代碼
 */
function getCode()
{
    var channelID = $('#channelID').val();
    var channelName = $('#channelName').val();
    
    if (checkForm(channelID, channelName)) 
    {
        $('#urlcode').val('http://raidcall.com.tw/g' + channelID);
        $('#htmlcode').val('<a href="http://raidcall.com.tw/g' + channelID + '" target="_blank">' + channelName + '</a> ');
        $('#ubbcode').val('[url=http://raidcall.com.tw/g' + channelID + ']' + channelName + '[/url]');
        
        $('#previewLink').text(channelName).attr('href', 'http://raidcall.com.tw/g' + channelID);
    }
    
    function checkForm(id, name)
    {
        var txtErrorID = $('#txtErrorID');
        var txtErrorName = $('#txtErrorName');
        var msgID = '';
        var msgName = '';
        
        if (!id) 
            msgID = tip_enter_server_id;
        else if (!/^[1-9]\d{1,10}$/.test(id)) 
            msgID = tip_server_id_err;
        txtErrorID.text(msgID);
        
        if (!name) 
            msgName = tip_enter_server_name;
        txtErrorName.text(msgName);
        
        if (msgID + msgName == '') 
        {
            return true;
        }
        else 
        {
            $('#urlcode,#htmlcode,#ubbcode').val('');
            $('#previewLink').text('');
            return false;
        }
    }
}
