﻿/// <reference path="jquery-1.3.2-vsdoc.js" />
/// <reference path="jquery.timers-1.1.3.js" />

$j = jQuery;

//判断一个字符串的字节数
String.prototype.lenB = function() { return this.replace(/[^\x00-\xff]/g, "**").length; }

jQuery.IsAuthenticated = false;

var avatarTool = $('<p></p>');
jQuery.addAvatarButton = function(button) {
    avatarTool.addClass("four-button");
    avatarTool.append(button);
}

var btnSendMail = $('<a class="icon-mail" href="#" title="发送邮件"></a>');
btnSendMail.click(function() {
    if (jQuery.IsAuthenticated) {
        var avatarID = jQuery(this).parent("p").prev("img").attr("title");
        var id = avatarID.substr(avatarID.indexOf("-") + 1, avatarID.length);
        GB_show('写邮件', '/Mails.mvc/MiniWrite?v=' + Math.random() + '&ids=' + id, 310, 520, null);
        //GB_info("站内信功能暂停使用，给您带来不便，请见谅！");
    } else {
        GB_show("请先登录", "/Accounts.mvc/MiniLogin?ReturnUrl=javascript:void(0)", 140, 360, null);
    }
    return false;
});
avatarTool.append(btnSendMail);
var btnAddFriend = $('<a class="icon-add" href="#" title="加为好友"></a>');
btnAddFriend.click(function() {
    if (jQuery.IsAuthenticated) {
        var avatarID = jQuery(this).parent("p").prev("img").attr("title");
        var id = avatarID.substr(avatarID.indexOf("-") + 1, avatarID.length);
        jQuery.post("/Friends.mvc/Add/" + id, null, function(data) {
            GB_info(data);
        });
    } else {
        GB_show("请先登录", "/Accounts.mvc/MiniLogin?ReturnUrl=javascript:void(0)", 140, 360, null);
    }
    return false;
});
avatarTool.append(btnAddFriend);

jQuery(document).ready(function() {
    menuHover();
    avatarHover();
    buttonHover();

    jQuery.getJSON("/Accounts.mvc/IsAuthenticated?d=" + Math.random(), function(data) {
        jQuery.IsAuthenticated = data;
        requestLogin();
        requestRegist();
    });
    jQuery.ajaxButton();

    jQuery("span.Female").attr("title", "女");
    jQuery("span.Male").attr("title", "男");


    //在初次登录时执行googleAnalystics脚本用于数据统计
    //googleAnalystics();
    //初始化轮播广告
    InitAD();
    //初始化首页TAB
    InitTab();
    //处理新邮件ICON
    //changeMailCOIN("messageICON");

    // checkMail();

    jQuery('.new-post .btn').mouseover(function() {
        if (jQuery('.new-post ul').length > 0)
            jQuery('.new-post ul').show();
    });
    jQuery('.new-post').mouseleave(function() {
        if (jQuery('.new-post ul').length > 0)
            jQuery('.new-post ul').hide();
    });
});

function checkMail() {
    try {
        var mailInterval = 20000;
        var zeroTime = 0;
        $(document).everyTime(mailInterval, "checkMail", function(i) {
            jQuery.get("/Mails.mvc/GetMailCount?d=" + Math.random(), function(data) {
                if (data == 0)
                    zeroTime++;
                else
                    zeroTime = 0;

                if (zeroTime >= 5)
                    $(document).stopTime("checkMail");

                $("#mailCount").text(data);
            });
        }, 100);
    } catch (e) { }
}

//function googleAnalystics() {
//        if(googleFlag)
//            alert("I did it,KaKa");
//}

function menuHover() {

    var defaultObj;
    if (ctrl == undefined || (ctrl != "forums" && ctrl != "campaigns")) {
        defaultObj = $j("#home-menu");
    }
    else {
        defaultObj = $j("#forums_" + menuID);
    }
   
    defaultObj.addClass("selected");
    
    $j("#menu a").hover(
        function() {
            $j(this).addClass("selected");
        },
        function() {
            $j(this).removeClass("selected");
            defaultObj.addClass("selected");
        }
    )

//    if ($("#Menu_" + ctrl).length == 0)
//        $("#Menu_profiles").addClass("selected");
//    else
//        $("#Menu_" + ctrl).addClass("selected");

//    jQuery("#menu dt").mouseover(function() {
//        jQuery("#menu dt,#menu dd").attr("class", "");
//        jQuery(this).attr("class", "selected");
//        jQuery(this).next("dd").attr("class", "selected");
//    });
//    jQuery("#menu").mouseleave(function() {
//        if (ctrl != null) {
//            jQuery("#menu dt,#menu dd").attr("class", "");
//            jQuery("#Menu_" + ctrl).addClass("selected");
//        }
//    });
}

function avatarHover() {
    jQuery("div.avatar").mouseover(function() {
        var userID = jQuery("img", this).attr("title");
        if (userID != $j.UserID) {
            jQuery("img", this).hide();
            if (jQuery("p", this).length == 0) {
                avatarTool.insertAfter(jQuery("img", this));
                avatarTool.show();
            } else { jQuery("p", this).show() };
        }
    });

    jQuery("div.avatar").mouseout(function() {
        jQuery("p", this).hide();
        jQuery("img", this).show();
    });
}

function buttonHover() {
    jQuery(".orange-button").mousemove(function() {
        jQuery(this).addClass("orange-button-focus");
    });
    jQuery(".orange-button").mouseout(function() {
        jQuery(this).removeClass("orange-button-focus");
    });

    jQuery(".gray-button").mousemove(function() {
        jQuery(this).addClass("gray-button-focus");
    });
    jQuery(".gray-button").mouseout(function() {
        jQuery(this).removeClass("gray-button-focus");
    });


}

jQuery.ajaxButton = function() {
    jQuery(".ajax").live("click", function(event) {

        $a = jQuery(this);
        var confirmMsg = $a.attr("confirm");

        if (confirmMsg != null && confirmMsg.length > 0) {
            if (!confirm(confirmMsg))
                return;
        }

        var url = $a.attr("ref");
        var act = $a.attr("callback");
        var method = $a.attr("method");
        if (method == null || method == "")
            method = "post";

        var dataNameStr = $a.attr("params");
        var datas = {};
        if (dataNameStr != null) {
            var dataNames = dataNameStr.toString().split(',');

            for (var i = 0; i < dataNames.length; i++) {
                datas[dataNames[i]] = jQuery("[name='" + dataNames[i] + "']").val();
            }
        }

        var acts = [''];
        if (act != null && act.length > 0)
            acts = act.toString().split(' ');

        jQuery.ajax({
            type: method,
            url: url,
            data: datas,
            success: function(data) {
                for (var i = 0; i < acts.length; i++) {
                    switch (acts[i]) {
                        case "tip":
                            QuickTips(data);
                            break;
                        case "alert":
                            alert(data);
                            break;
                        case "refresh":
                            window.location.reload();
                            break;
                        case "redirect":
                            window.location = $a.attr("redirect");
                            break;
                        case "hide":
                            $a.hide();
                            break;
                        default:
                            eval(acts[i] + "(data)");
                            break;
                    }
                }
            }
        });
        return false;
    });
    jQuery(".ajax").show();
}

function requestRegist() {
    if (jQuery.IsAuthenticated) {
        //jQuery(".Authorize").show();
        return;
    }

    //新增注册于登录一起页面
    jQuery(".MiniRegist").each(function(i, item) {
        if (item.tagName == "A" || item.tagName == "AREA") {
            $a = jQuery(item);
            $a.removeClass("ajax");
            var url = $a.attr("href");
            var registUrl = $a.attr("ref");
            url = registUrl + "?returnUrl=" + url.replace("&", "$");
            $a.attr("href", url);
            $a.attr("onclick", "");
            $a.unbind("click");
        }
    });
}

function requestLogin() {
    if (jQuery.IsAuthenticated) {
        //jQuery(".Authorize").show();
        return;
    }
    
    jQuery(".Authorize").each(function(i, item) {
        jQuery(item).show();
        if (item.tagName == "A" || item.tagName == "AREA") {
            $a = jQuery(item);
            $a.removeClass("ajax");
            var url = $a.attr("href");
            var registUrl = $a.attr("ref");
            url = "/Accounts.mvc/MiniLogin?ReturnUrl=" + url.replace("&","$");
            if (registUrl != undefined)
                url += "&RegistUrl=" + registUrl;
            $a.attr("href", "javascript:GB_show( '请先登录','" + url + "',140,360, null );");
            $a.attr("target", "");
            $a.attr("onclick", "");
            $a.unbind("click");
        }
        else if (item.tagName == "FORM") {
            $form = jQuery(item);
            var action = "/Accounts.mvc/MiniLogin?ReturnUrl=javascript:void(0)";
            $('input,textarea,select', $form).bind("focus", function(event) {
                GB_show("请先登录", action, 140, 350, null);
                return false;
            });
        }
        else {
            //alert(item.tagName);
            $input = jQuery(item);
            $input.attr("onclick", "");
            $input.unbind("click");
            var link = "/Accounts.mvc/MiniLogin?ReturnUrl=javascript:void(0)";
            //alert(link);
            $input.bind("click", function() { GB_show("请先登录", link, 140, 360, null); });
        }
    });
}

function SelectAll(name) {
    $j("input[name='" + name + "']").attr("checked", "checked");
}

function InvertAll(name) {
    $j("input[name='" + name + "']").click();
}


function ReadUnReadMail() {
    var mailCount = $j("#mailCount").html();
    if (mailCount > 0 && jQuery.IsAuthenticated) {
        $j("#mailCount").html("读取...");
        $j.post("/Mails.mvc/Read", null, function(data) {
            if (data != "0") {
                var Url = "/Mails.mvc/ReadMail/" + data+"?isReply=false";
                $j("#mailCount").html(mailCount - 1);
                GB_show("优惠多-查看邮件", Url, 500, 700, null);
                if (mailCount == 1) {
                    $j("#messageICON").removeClass();
                }
            } else {
                window.location.href="/Profiles.mvc/Mails";
                //window.location.reload();
            }
        });
    }
}
//==========================================有新邮件图标处理
//function changeMailCOIN(id) {
//    var index = $("#" + id).attr("class");
//    try {
//        index = index.substr(12);
//    } catch (e) {
//        index = 0;
//    }
//    ++index;
//    if (index >= 4) {
//        index = 0;
//    }
//    $("#" + id).attr("class", "messageICON_" + index);
//    setTimeout(function() {
//        changeMailCOIN(id);
//    }, 100)
//}

//==========================================广告轮播
/*
* 初始化广告轮播
*/
function InitAD() {
    $(".main-ad").each(
        function(i) {
           var id = "main-ad" + i;
           $(this).attr("id", id);
           var advert = new jQuery.Advert(id);
           advert.Run();
        }
    );
}

jQuery.Advert = function(id){
    this.id = id;
    //轮播周期，以秒表示
    var time = 5;
    this.index = 0;
    var length = 0;
    var curIndex = 0;
    var tempTimer = time;
    var curAdvert = this;
    $("#" + id + " .adIndex").html("");
    length = $("#" + id + " ol li").length;
    if(length == 0){
        alert("此轮播广告没有内容：ID=" + id);
        return;
    }
    
    $("#" + id + " .adIndex .selected").removeClass("selected");
    $("#" + id + " ol li").each(
        function(j) {
            if(j==0){
                $j(this).addClass("selected");
            }
            $("#" + id + " .adIndex").append("<li index=\""+j+"\">" + (j + 1) + "</li>");
            $(this).hover(
                function(){
                    //鼠标在上面时
                    Stop();
                },
                function(){
                    //鼠标离开时
                    Start();
                }
            );
        }
    );
    $("#" + id + " .adIndex li").each(
        function(k){
            $j(this).each(
                function(){
                    $j(this).click(
                        function(){
                            tempTimer = 0;
                            curIndex = $j(this).attr("index");
                            ShowTabContent();
                        }
                    );
                }
            );
        }
    );
    var available = true;
    
    //开始轮播
    Start = function(){
        tempTimer = 0;
        available = true;
    };
    
    //暂停轮播
    Stop = function(){
        available = false;
    };
    
    this.Run = function(){
        if(available && tempTimer == time){
            //显示
            ShowTabContent();
        }
        ++tempTimer;
        setTimeout(function(){
            curAdvert.Run();
        },1000);
    };
    
    ShowTabContent = function(){
        var showIndex = GetIndex();
        $("#" + id + " ol .selected").fadeOut(500,function(){
            $("#" + id + " .adIndex .selected").removeClass("selected");
        $("#" + id + " ol .selected").removeClass("selected");
        $("#" + id + " ol li").hide();
        //淡出
        $("#" + id + " .adIndex li:eq(" + showIndex + ")").addClass("selected");
        $("#" + id + " ol li:eq(" + showIndex + ")").fadeIn(0,
		    function() {
		        $("#" + id + " ol li:eq(" + showIndex + ")").addClass("selected");
		        tempTimer = 0;
		    }
	    );
        });
        
        ++curIndex;
    };
    
    GetIndex = function(){
        if(length == curIndex)
            //如果是最后一页，则返回到第一页
            curIndex = 0;
        return curIndex;
    };
}

/*
* 显示TAB
*/
function showTabContent(id, obj) {
    var index = $("#" + id + " .center-tab-title .selected").attr("index");
    $("#" + id + " .center-tab-title .selected").removeClass("selected");
    $("#" + id + " .center-box-content[index='" + index + "']").removeClass("selected");
    $("#" + id + " .center-box-content[index='" + index + "']").hide();
    index = $(obj).attr("index");
    $(obj).addClass("selected");
    $("#" + id + " .center-box-content[index='" + index + "']").addClass("selected");
    $("#" + id + " .center-box-content[index='" + index + "']").show();
}

/*
* 初始化TAB
*/
function InitTab() {
    $(".main-tab").each(
        function(k) {
            var id = "main-tab" + k;
            $(this).attr("id", id);
            $("#" + id + " .center-box-content").hide();
            $("#" + id + " .center-tab-title li").bind("mouseover", function() {
                showTabContent(id, $(this));
            });
            showTabContent(id, $("#" + id + " .center-tab-title li:eq(0)"));
        }
    );

}

function submitSearch() {
    var searchContent = $j.trim($j('#searchForm #q').val());
    $(".bt-submit").css({ color: '#505050' });
    if (searchContent == '' || searchContent == '请输入您想搜索的内容') {
        $(".bt-submit").css({ color: 'white' });
        return;
    }
    window.location.href = "/Forums.mvc/Search?t=0&q=" + searchContent;
    
}