﻿if (window.location.href.indexOf("character") <= 0) {
    window.location = "http://www.pedaily.cn/en/";
}

var nowUrl = window.location.href;
var currentTime = new Date();


//Index TopPromotion
var topPromotionImg;
var topPromotionThumbnailImg;
var topPromotionWeight;
var topPromotionLink;
var randomNum;
var CloseTopPromotion = new Image();
var t; //setTimeout

//ImageCarousel
//var imageCarouselImg;
//var imageCarouselLink;
//var carouselNum = 0;
//var carouseT; //setTimeout

//NewImageCarousel
var timer = null;
var offset = 5000;
var index = 0;
var target = ["ic-01","ic-02","ic-03","ic-04"];


$(document).ready(function () {
    //Fix IE css background image reload problem.
    if ($.browser.msie)
        document.execCommand("BackgroundImageCache", false, true);

    //take out the dashed box above <a>
    $("a").bind("focus", function () {
        if (this.blur) {
            this.blur();
        }
    });

    //$("a[href='#']").click(function() { return false; });
    //$("a[href='#']").css("text-decoration", "none");

    //Disable the Enter key
    $(window.document.body).keydown(function (event) {
        if (event.keyCode == 13) {
            return false;
        }
    });

    //auto direct to anchor
    if (nowUrl.indexOf("locationhash") > 0) {
        window.location.hash = decodeURIComponent(nowUrl.substring(nowUrl.indexOf("locationhash") + 13));
    }

    //    $("input[type=text]").addClass("defaultInput");
    //    $("input[type=text]").focus(function() {
    //        $(":text").removeClass("focus");
    //        $(this).addClass("focus");
    //    });

    if ($("#sponsors").length != 0) {
        var s = $("#ScrollPics").html();
        $("#CloneScroll").html(s);
        var HiddenScroll = document.getElementById("HiddenScroll");
        var ScrollPics = document.getElementById("ScrollPics");
        var CloneScroll = document.getElementById("CloneScroll");
        scrollPic();
    }

    /************Top Start************/

    //Search
    $("#normalsearch").focus(function () {
        if ($.trim($("#normalsearch").val()) == "" || $.trim($("#normalsearch").val()) == "Try valid keywords.")
            $("#normalsearch").val("");
    }).blur(function () {
        if ($("#normalsearch").val() == "")
            $("#normalsearch").val("Try valid keywords.");
    });

    $("#btnSearch").click(function () {
        if ($.trim($("#normalsearch").val()) == "" || $.trim($("#normalsearch").val()) == "Try valid keywords.") {
            alert("Try valid keywords.");
            return false;
            $("#normalsearch").focus();
        }
        else if ($.trim($("#normalsearch").val()).length < 2) {
            alert("Keywords must be more than two letter!");
            return false;
            $("#normalsearch").focus();
        }
        else {
            if (window.document.forms[0]) {
                window.document.forms[0].action = "/en/index/" + escape($("#normalsearch").val());
                window.document.forms[0].submit();
            }
            else
                window.location = "/en/index/" + escape($("#normalsearch").val());
        }
    });

    $("#normalsearch").keydown(function (event) {
        if (event.keyCode == 13) {
            $("#btnSearch").trigger("click");
        }
    });

    /************Top Start************/
    /************Top End************/

    /************Index Start************/
    //Error!$("#currentTime").text(currentTime.toDateString() + " " + currentTime.toTimeString());

    //if ($("#ImageCarousel").length != 0) {
    //  ImageCarousel();
    //}

    $("#LanguageChange").click(function () {
        if (nowUrl.indexOf("research") > 0)
            window.location = "http://www.pedaily.cn/report/28/Index.aspx";
        else if (nowUrl.indexOf("ibanking") > 0)
            window.location = "http://ibanking.zero2ipo.com.cn/";
        else if (nowUrl.indexOf("events") > 0)
            window.location = "http://www.pedaily.cn/events/29/Index.aspx";
        else if (nowUrl.indexOf("club") > 0)
            window.location = "http://www.zero2ipogroup.com/en/member/";
        else
            window.location = "http://www.pedaily.cn/";
    });

    /************Index End**************/

    /************News Start************/
    //Access Record
    if (nowUrl.indexOf("/en/n/") > 0) {
        var page = encodeURIComponent(nowUrl.substring(nowUrl.indexOf("/en/n/20")));
        $.ajax({
            type: "GET",
            url: "/news/AccessLog.aspx?lan=false&page=" + page
        });
    }

    //Paging Beginning
    $("#pageDirect").keyup(function () {
        document.getElementById("pageDirect").value = document.getElementById("pageDirect").value.replace(/\D/g, '');
    });


    $("input[name='btnPageDirect']").click(function () {
        var pageDirect = $.trim($("#pageDirect").val());

        var pagesCount = $("#pagesCount").text();

        var reNum = /^\d*$/;
        if (reNum.test(pageDirect) == false || (parseInt(pageDirect) > parseInt(pagesCount)) || parseInt(pageDirect) <= 0 || pageDirect == "") {
            $("#pageDirect").empty();
            alert("The max page is " + pagesCount + ",please input 1-" + pagesCount + "。");
            $("#pageDirect").focus();
            return false;
        }

        var isFirsePage = nowUrl.indexOf("_");
        var strPos;
        var directUrl;
        if (isFirsePage < 0)
            strPos = nowUrl.indexOf(".shtml");
        else
            strPos = nowUrl.indexOf("_");

        if (pageDirect != '1')
            directUrl = nowUrl.substring(0, strPos) + "_" + pageDirect + ".shtml";
        else
            directUrl = nowUrl.substring(0, strPos) + ".shtml";

        window.location.href = directUrl;
    });
    //Paging End


    //Print Email
    $("#printContent").click(function () {
        if ($("#articleContent").length != 0) {
            document.write($("#articleContent").html());
            window.print();
        }
    });
    $("#editFeedback").unbind().attr({ href: "mailto:Zero2IPONews@zero2ipo.com.cn?subject=Zero2IPO WebSite Feedback&body=Hello,I would like to make a comment on this news: " + nowUrl });
    $("#closeWindow").click(function () {
        window.close();
    });
    $("#backToTop").click(function () {
        window.scrollTo(0, 0);
    });
    /************News End**************/


    /************Events Start**************/
    $("#pastEventsContent div:first").show();
    $("#pastEvents ul:first li").mouseover(function () { switchColumn("pastEvents", "pastEventsContent", "mouseOver", $(this)) });
    /************Events End**************/


    /************Research Start**************/
    //eWeekly

    /************Eweekly Start***********/
    if ($(".pdfdownloadCounter").length != 0) {
        $(".pdfdownloadCounter").each(function (i) {
            if ($(this).prev("a").attr('rel') != "") {
                var pdf = $(this).prev("a").attr('rel');
                var pdf_download;
                $.get("/eweekly/eweekly-counter.aspx", { id: pdf }, function (data) { $(".pdfdownloadCounter").eq(i).html(data); });
            }
        });
    }
    /************Eweekly End*************/


    $("#btnSubscription").click(function () {
        window.location = "/eweekly/subscription_en.aspx";
    });


    $("#latestReportsContent div:first").show();
    $("#latestReports ul:first li").mouseover(function () { switchColumn("latestReports", "latestReportsContent", "latestReportsOver", $(this)) });

    $("#researchContent div:first").show();
    $("#research ul:first li").mouseover(function () { switchColumn("research", "researchContent", "researchOver", $(this)) });

    //Payment
    var validator = $("#orderForm").validate({
        rules: {
            txtConsigneeName: { required: true, minlength: 2 },
            txtMemberCompany: { required: true, minlength: 2 },
            txtConsigneeAddress: { required: true, minlength: 10 },
            txtConsigneePost: { required: true, maxlength: 30 },
            txtConsigneeTel: { required: true, maxlength: 30 },
            txtConsigneeCellphone: { required: true, maxlength: 30 },
            txtConsigneeEmail: { required: true, email: true }
        },
        messages: {
            txtConsigneeName: "Please provide your name for us to check your register information.",
            txtMemberCompany: "Please provide your company for us to check your register information.",
            txtConsigneeAddress: "Your address requires a minimum of 10 characters.",
            txtConsigneePost: "Required.",
            txtConsigneeTel: "Required.",
            txtConsigneeCellphone: "Required.",
            txtConsigneeEmail: "Please input a valid email address."
        }
    });

    $("input[name='needInvoice']").click(function () {
        if ($('input:checked[name=needInvoice]').val() == "true") {
            $("#invoice").show();
            $.blockUI({ message: $('#invoiceMsg'), css: { width: '450px'} });

            $('#VOK').click(function () {
                $.unblockUI();
                return false;
            });
        }
        else {
            $("#invoice").hide();
        }
    });

    $("#reportDataMining input[type=checkbox]").click(function () {
        calculateMoney();
    });

    $("#postage").change(function () {
        calculateMoney();
    });

    function calculateMoney() {
        var amount = 0;
        var products = $("#ProductName").text();
        amount += parseFloat($("#Money").text());


        var txtProductsHeight = 15;

        //Research Product Data Mining
        if ($("#reportDataMining").length != 0) {
            var reportDM;
            $("#reportDataMining input:checked[type=checkbox]").each(function () {
                reportDM = $(this).attr("name");
                amount += parseFloat($('#' + reportDM).text());
                products += "\r\n" + $(this).next("a").text();
                txtProductsHeight += 15;
            });
            $("#txtProducts").height(txtProductsHeight);
        }
        //Postage
        if (document.getElementById("haspostage").style.display == "" || document.getElementById("haspostage").style.display == "block") {
            amount += parseInt($("#postage").val());
        }
        $("#txtProducts").empty().val(products);
        $("#txtSum").animate({ opacity: "toggle" }, "slow").empty().val(amount).animate({ opacity: "toggle" }, "slow");
    }

    //Reset and Initialize
    $("#btnPaymentReset").click(function () {
        $("#txtProducts").empty().val($("#ProductName").text());
        $("#txtSum").empty().val(parseFloat($("#Money").text()));
        $("#txtProducts").height(15);
    });

    if ($("#question").length != 0) {
        $.blockUI({ message: $('#question'), css: { width: '450px'} });

        $('#OK').click(function () {
            $.unblockUI();
            return false;
        });
    }


    /************Research End**************/



    /************Zclub Start************/
    //btnRegister
    $("#btnRegister").click(function () {
        window.location = "http://club.zero2ipo.com.cn/en/club/memberregister.aspx";
    });
    //ParticipantsList
    $(".ParticipantsList").click(function () {
        alert("Please Login！");
        return false;
    });

    $(".ViewVideo").click(function () {
        alert("Please Login！");
        return false;
    });


    if ($("#signupform").length != 0) {

        $("#txtRemark1").blur(function () { signupMoney(); });

        var validator = $("#signupform").validate({
            rules: {
                txtMemberName: { required: true, minlength: 2 },
                txtMemberCompany: { required: true, minlength: 2 },
                txtMemberAddress: { required: true, minlength: 10 },
                txtRemark1: { required: true, minlength: 1, maxlength: 3, digits: true },
                txtMemberTitle: { required: true, minlength: 2 },
                txtMemberTel: { required: true, minlength: 6, maxlength: 60 },
                txtMemberCellPhone: { required: true, minlength: 10, maxlength: 30 },
                txtMemberEmail: { required: true, email: true }
            },
            messages: {
                txtMemberName: "Please provide your name for us to check your register information.",
                txtMemberCompany: "Please provide your company name.",
                txtMemberAddress: "Your address requires a minimum of 10 characters.",
                txtRemark1: "Required. It should be confined from ones digit to hundreds digit.",
                txtMemberTitle: "Please provide your title.",
                txtMemberTel: "Required.",
                txtMemberCellPhone: "Required.",
                txtMemberEmail: "Please input a valid email address."
            }
        });
    }

    function signupMoney() {
        var attendance = parseInt($("#txtRemark1").val());
        if (isNaN(attendance)) {
            $("#txtSum").animate({ opacity: "toggle" }, "slow").empty().val(0).animate({ opacity: "toggle" }, "slow");
            return false;
        }
        else
            $("#txtSum").animate({ opacity: "toggle" }, "slow").empty().val(attendance * 40).animate({ opacity: "toggle" }, "slow");
    }

    if ($("#memberregisterform").length != 0 || $("#eweeklysubscriptionform").length != 0) {
        //Reset
        $("#reset").click(function () {
            $("#selectMemberCompanyTypeTwo").hide();
        });

        if ($("#memberregisterform").length != 0) {
        
        $("#ddlMemberSort").change(function () {
                if ($("#ddlMemberSort").val() == "8999") {
                    $("input[name='EweeklyLanguage']").attr("checked", 1);
                }
                else if ($("#ddlMemberSort").val() == "739") {
                    $("input[name='EweeklyLanguage']").attr("checked", 0);
                }
                else {
                    $("input[name='EweeklyLanguage']").attr("checked", 0);
                    $("input[name='EweeklyLanguage'][value='0']").attr("checked", 1);
                }
            });

        $("input[name='EweeklyLanguage']").change(function () {
            if ($("#ddlMemberSort").val() == "8999") {
                $("input[name='EweeklyLanguage']").attr("checked", 1);
            }
            else if ($("#ddlMemberSort").val() == "7399") {
                $("input[name='EweeklyLanguage']").attr("checked", 0);
                $(this).attr("checked", 1);
            }
            else if ($("#ddlMemberSort").val() == "2999") {
                $("input[name='EweeklyLanguage']").attr("checked", 0);
                $(this).attr("checked", 1);
            }
            else if ($("#ddlMemberSort").val() == "1499") {
                $("input[name='EweeklyLanguage']").attr("checked", 0);
                $("input[name='EweeklyLanguage'][value='0']").attr("checked", 1);
            }
            else {
                $("input[name='EweeklyLanguage']").attr("checked", 0);
            }
        });

        }

        //MemberCompanyType
        if ($("#selectMemberCompanyTypeOne").val() == "企业")
            $("#selectMemberCompanyTypeTwo").show();
        else
            $("#selectMemberCompanyTypeTwo").hide();

        $("#selectMemberCompanyTypeOne").change(function () {
            if ($("#selectMemberCompanyTypeOne").val() == "企业")
                $("#selectMemberCompanyTypeTwo").show();
            else
                $("#selectMemberCompanyTypeTwo").hide();
        });

        //MemberZone
        if ($("#selectMemberZoneOne").val() == "中国-大陆")
            $("#selectMemberZoneTwo").show();
        else
            $("#selectMemberZoneTwo").hide();
        $("#selectMemberZoneOne").change(function () {
            if ($("#selectMemberZoneOne").val() == "中国-大陆")
                $("#selectMemberZoneTwo").show();
            else
                $("#selectMemberZoneTwo").hide();
        });

        //eWeekly Subscription
        var validator = $("#eweeklysubscriptionform").validate({
            rules: {
                txtMemberName: { required: true, minlength: 2 },
                txtMemberCompany: { required: true, minlength: 2 },
                txtMemberAddress: { required: true },
                txtMemberTitle: { required: true, minlength: 2 },
                txtMemberTel: { required: true, minlength: 2, maxlength: 60 },
                txtMemberFax: { required: true, minlength: 2, maxlength: 60 },
                txtMemberCompanyEmployeesNum: { required: true, maxlength: 20 },
                txtMemberEmail: { required: true, email: true },
                txtMemberZipcode: { required: true, minlength: 2, maxlength: 40 },
                EweeklyLanguage: { required: true, minlength: 1 }
            },
            messages: {
                txtMemberName: "Please provide your name for us to check your register information.",
                txtMemberCompany: "Please provide your company name.",
                txtMemberAddress: "Required.",
                txtMemberTitle: "Please provide your title.",
                txtMemberTel: "Required.",
                txtMemberFax: "Required.",
                txtMemberCompanyEmployeesNum: "Please provide the number of employee in your company.",
                txtMemberEmail: "Please input a valid email address.",
                txtMemberZipcode: "Required.",
                EweeklyLanguage: "Please input a valid version."
            }
        });
    }

    if ($("#memberregisterform").length != 0) {
        $("#ddlMemberSort").change(function () {
            memberregisterMoney();
        });
        $("input[name='MemberPeriod'][type=radio]").change(function () {
            memberregisterMoney();
        });

        //MemberSource
        $("#txtOtherSource").hide();
        $("input[name^='rblMemberSource'][type=radio]").focus(function () {
            if ($(this).val() == "其他")
                $("#txtOtherSource").show();
            else
                $("#txtOtherSource").hide();
        });
        //registerMode
        $("#registerMode").click(function () {
            $(".advRegister").toggle();
            if ($("#registerMode").text() == "Quick Register") {
                $("#registerMode").empty().text("Common Register");
                $("#hfRegisterMode").val(0);
            }
            else {
                $("#registerMode").empty().text("Quick Register");
                $("#hfRegisterMode").val(1);
            }
        });

        var validator = $("#memberregisterform").validate({
            rules: {
                txtMemberName: { required: true, minlength: 2 },
                txtMemberCompany: { required: true, minlength: 2 },
                txtMemberAddress: { required: true, minlength: 10 },
                txtMemberTitle: { minlength: 2 },
                txtMemberTel: { required: true, minlength: 6, maxlength: 60 },
                txtMemberFax: { required: true, minlength: 6, maxlength: 60 },
                txtMemberCellPhone: { minlength: 10, maxlength: 20, digits: true },
                txtMemberEmail: { required: true, email: true },
                txtMemberZipcode: { required: true, minlength: 6, maxlength: 20 }
            },
            messages: {
                txtMemberName: "Please provide your name for us to check your register information.",
                txtMemberCompany: "Please provide your company name.",
                txtMemberAddress: "Your address requires a minimum of 10 characters.",
                txtMemberTitle: "Please provide your title.",
                txtMemberTel: "Required.",
                txtMemberFax: "Required.",
                txtMemberCellPhone: "Required.",
                txtMemberEmail: "Please input a valid email address.",
                txtMemberZipcode: "Required."
            }
        });

        function memberregisterMoney() {
            var memberSort = parseInt($("#ddlMemberSort").val());
            var memberPeriod = $("input[name='MemberPeriod']:checked").val();
            if (isNaN(memberSort)) {
                $("#txtSum").animate({ opacity: "toggle" }, "slow").empty().val(0).animate({ opacity: "toggle" }, "slow");
                return false;
            }
            else
                $("#txtSum").animate({ opacity: "toggle" }, "slow").empty().val(memberSort * memberPeriod).animate({ opacity: "toggle" }, "slow");
        }
    }

    if ($("#sceneVideo").length != 0) {
        $("#EventsVideo").html($("#sceneVideo ul li a:first").attr('rel'));
        //EventsVideo
        $("#sceneVideo ul li a").click(function () {
            $("#EventsVideo").html($(this).attr('rel'));
        });
    }

    /************Zclub End**************/


    /************Module Start************/
    //Table Sort
    //$(".eventsTable").tablesorter({ sortList: [[0, 0]], widgets: ['zebra'], headers: { 1: { sorter: false }, 2: { sorter: false}} });
    $(".reportTable").tablesorter({ sortList: [[2, 1]], widgets: ['zebra'], headers: { 0: { sorter: false }, 1: { sorter: false }, 4: { sorter: false}} });
    $(".reportTablePager").tablesorter({ sortList: [[2, 1]], widthFixed: true, widgets: ['zebra'], headers: { 0: { sorter: false }, 1: { sorter: false }, 4: { sorter: false}} }).tablesorterPager({ container: $("#pager") });
    $(".rankingTable").tablesorter({ sortList: [[1, 1]], widgets: ['zebra'], headers: { 0: { sorter: false}} });
    $(".rankingTablePager").tablesorter({ sortList: [[1, 1]], widthFixed: true, widgets: ['zebra'], headers: { 0: { sorter: false}} }).tablesorterPager({ container: $("#pager") });

    //Calendar Start
    if ($("#activityCalendar").length != 0) {
        var currentMonth = getCookie("currentMonth");
        if (currentMonth == null || currentMonth == "") {
            currentMonth = parseInt(currentTime.getMonth().toString()) + 1;
            setCookie("currentMonth", currentMonth);
        }

        getEventsCalendar(currentMonth);

        $("#viewMonth").empty().text(MonthString(currentMonth));

        $("#prevMonth").click(function () {
            if (1 < currentMonth && currentMonth <= 12) {
                currentMonth--;
                getEventsCalendar(currentMonth);
                $("#viewMonth").empty().text(MonthString(currentMonth));
                setCookie("currentMonth", currentMonth);
                return false;
            }
        });

        $("#nextMonth").click(function () {
            if (1 <= currentMonth && currentMonth < 12) {
                currentMonth++;
                getEventsCalendar(currentMonth);
                $("#viewMonth").empty().text(MonthString(currentMonth));
                setCookie("currentMonth", currentMonth);
                return false;
            }
        });
    }

    //HotArticle
    if ($(".hotArticleWithDateTime").length != 0 || $(".hotArticleWithoutDateTime").length != 0) {
        var WithDateTimeValue;
        var hotarticle;

        if ($(".hotArticleWithDateTime").length != 0) {
            hotarticle = $(".hotArticleWithDateTime");
            WithDateTimeValue = true;
        }
        else if ($(".hotArticleWithoutDateTime").length != 0) {
            hotarticle = $(".hotArticleWithoutDateTime");
            WithDateTimeValue = false;
        }

        var hotarticleCookie = getCookie("hotArticle" + WithDateTimeValue + "false");

        if (hotarticleCookie != null && hotarticleCookie != "") {
            hotarticle.append(hotarticleCookie);
        }
        else {
            $.ajax({
                type: "get",
                url: "/news/hotarticle.aspx",
                data: "lan=false&WithDateTime=" + WithDateTimeValue,
                timeout: "600000",
                beforeSend: function (XMLHttpRequest) {
                    hotarticle.append("<div class=\"ajaxloading\"><em>Loading……</em></div>");
                },
                success: function (data, textStatus) {
                    hotarticle.append(data);
                    setCookie("hotArticle" + WithDateTimeValue + "false", data);
                },
                complete: function (XMLHttpRequest, textStatus) {
                    if (textStatus != "error")
                        $(".ajaxloading").remove();
                },
                error: function () {
                    hotarticle.append("<div class=\"ajaxloading\"><em>Loading failed……</em></div>");
                }
            });
        }
    }
    //Calendar End

    //ScrollPic Start

    function marqueeTop() {
        if (CloneScroll.offsetTop - HiddenScroll.scrollTop <= 0) {
            HiddenScroll.scrollTop -= ScrollPics.offsetHeight;
        }
        else {
            HiddenScroll.scrollTop++;
        }
    }

    function scrollPic() {
        var intervalTime = setInterval(marqueeTop, 100);
        $("#ScrollPics").mouseover(function () { clearInterval(intervalTime); }).mouseout(function () { intervalTime = setInterval(marqueeTop, 100); });
    }


    //ScrollPic End

    //ScrollPic Module Start

    function marqueeTopModule() {
        if (CloneScrollModule.offsetTop - HiddenScrollModule.scrollTop <= 0) {
            HiddenScrollModule.scrollTop -= ScrollPicsModule.offsetHeight;
        }
        else {
            HiddenScrollModule.scrollTop++;
        }
    }

    function scrollPicModule() {
        var intervalTimeModule = setInterval(marqueeTopModule, 100);
        $("#ScrollPicsModule").mouseover(function () { clearInterval(intervalTimeModule); }).mouseout(function () { intervalTimeModule = setInterval(marqueeTopModule, 100); });
    }

    if ($(".ScrollModule").length != 0) {
        var s = $("#ScrollPicsModule").html();
        $("#CloneScrollModule").html(s);
        var HiddenScrollModule = document.getElementById("HiddenScrollModule");
        var ScrollPicsModule = document.getElementById("ScrollPicsModule");
        var CloneScrollModule = document.getElementById("CloneScrollModule");
        scrollPicModule();
    }
    //ScrollPic Module End

    /************Module End**************/
});

/************Function Start**************/

//Payment
function checkpostage() {
    if ($("#hfReportType").val() == "year" && $("#postage").val() == "0") {
        alert("Postage required"); return false;
    }
}

function switchColumn(parentDiv, contentDiv, overClassName, thisPoint) {
    $('#' + parentDiv + " ul li").removeClass(overClassName);
    thisPoint.addClass(overClassName);
    $('#' + contentDiv + " div:visible").hide();
    $('#' + thisPoint.find("a").attr('rel')).show();
}

//ImageCarousel
/*
var imageCarouselImg;
var imageCarouselWeight;
var imageCarouselLink;
var randomNumCarousel;

function ImageCarousel() {
    imageCarouselImg = new Array("http://www.zero2ipo.com.cn/en/images/ImageCarousel/1.jpg", "http://www.zero2ipo.com.cn/en/images/ImageCarousel/2.gif");
    imageCarouselLink = new Array("http://events.zero2ipo.com.cn/2008vcranking/en/", "http://www.zero2ipo.com.hk/cvcf/bj2008/Overview.asp");
    ImageCarouselChange();
}
function ImageCarouselChange() {
    carouselNum++;
    if (carouselNum > imageCarouselImg.length - 1)
        carouselNum = 0;
    $("#imageCarouselLink").attr("href", imageCarouselLink[carouselNum]);
    $("#imageCarouselImg").attr("src", imageCarouselImg[carouselNum]);
    carouseT = setTimeout("ImageCarouselChange()", 5000);
}
*/

//TopPromotion
function hideTopPromotion() {
    $("#TopPromotion").slideUp("5000");
    clearTimeout(t);
}

function TopPromotion() {
    topPromotionImg = new Array("http://www.zero2ipo.com.cn/images/toppromotion/TopPromotion_2.JPG");
    topPromotionThumbnailImg = new Array("http://www.zero2ipo.com.cn/images/toppromotion/TopPromotionThumbnail_2.JPG");
    topPromotionLink = new Array("http://www.milestones-china.com/cn/default.asp");
    topPromotionWeight = new Array("100");
    var sumWeight = 0;
    for (var i = 0; i < topPromotionWeight.length; i++) {
        sumWeight += parseInt(topPromotionWeight[i]);
    }
    randomNum = Math.floor((Math.random() * sumWeight));
    if (randomNum >= 0 && randomNum <= parseInt(topPromotionWeight[0])) {
        randomNum = 0;
    }
    else if (randomNum >= parseInt(topPromotionWeight[0]) && randomNum <= parseInt(topPromotionWeight[0]) + parseInt(topPromotionWeight[1])) {
        randomNum = 1;
    }
    CloseTopPromotion.src = "http://www.zero2ipo.com.cn/images/closeTopPromotion.gif";

    $("#topPromotionLink").attr("href", topPromotionLink[randomNum]);
    $("#TopPromotion").show().attr("src", topPromotionImg[randomNum]);
    $("#TopPromotionThumbnail").show().attr("src", topPromotionThumbnailImg[randomNum]);
    $("#CloseTopPromotion").show().attr("src", CloseTopPromotion.src);

    $("#CloseTopPromotion").click(function() {
        $("#TopPromotion").hide();
        $("#TopPromotionThumbnail").hide();
        $("#CloseTopPromotion").hide();
    });

    t = setTimeout("hideTopPromotion()", 7000);
}

function getCookie(cookieName) {
    var cookie = document.cookie;
    var first = cookie.indexOf(cookieName + "=");
    // cookie exists
    if (first >= 0) {
        var str = cookie.substring(first, cookie.length);
        var last = str.indexOf(";");
        // if last cookie
        if (last < 0) last = str.length;
        // get cookie value
        str = str.substring(0, last).split("=");
        return unescape(str[1]);
    }
    else {
        return null;
    }
}

function setCookie(cookieName, cookieValue) {
    var expireDate = new Date();
    expireDate.setMinutes(expireDate.getMinutes() + 30);
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; expires=" + expireDate.toUTCString() + "; path=/";
}

function eraseCookie(key) {
    var cookieDate = new Date(2000, 20, 20, 20, 20, 20);
    document.cookie = key + "= ; expires=" + cookieDate.toGMTString() + "; path=/";
}

function getEventsCalendar(getMonth) {
    $.ajax({
        type: "get",
        url: "/en/events/EventsCalendar.aspx?Month=" + getMonth,
        timeout: "600000",
        beforeSend: function(XMLHttpRequest) {
            $("#activityCalendar").empty().append("<div class=\"ajaxloading\"><em>Loading……</em></div>");
        },
        success: function(data, textStatus) {
            var i = data.indexOf("<table id");
            var j = data.indexOf("</table>");
            var calData = data.substring(0, j - i)
            $("#activityCalendar").empty().append(calData);

            //Remove the title of table(.Net Calendar control autogeneration) "EventsCalendar" is the control id
            $("#EventsCalendar").removeAttr("title");

            if (2 <= getMonth && getMonth <= 11) {
                $("#prevMonth").attr({ title: MonthString(parseInt(getMonth) - 1) + "" });
                $("#nextMonth").attr({ title: MonthString(parseInt(getMonth) + 1) + "" });
            }
            else if (getMonth == 1) {
                $("#prevMonth").attr({ title: currentTime.getFullYear().toString() + "" });
                $("#nextMonth").attr({ title: "February" });
            }
            else if (getMonth == 12) {
                $("#prevMonth").attr({ title: "November" });
                $("#nextMonth").attr({ title: currentTime.getFullYear().toString() + "" });
            }
        },
        complete: function(XMLHttpRequest, textStatus) {
            //$(".ajaxloading").remove(); 
        },
        error: function() {
            $("#activityCalendar").append("<div class=\"ajaxloading\"><em>Loading failure......</em></div>");
        }
    });
}

function MonthString(i) {
    var months = new Array("", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return months[i];
}

//NewImageCarousel Start
function slideImage(i) {
    var id = 'image_' + target[i];
    $('#' + id)
        .animate({ opacity: 1 }, 800, function() {
            $(this).find('.word').animate({ height: 'show' }, 'slow');
        }).show()
        .siblings(':visible')
        .find('.word').animate({ height: 'hide' }, 'fast', function() {
            $(this).parent().animate({ opacity: 0 }, 800).hide();
        });
}
function hookThumb() {
    $('#thumbs li a')
        .bind('click', function() {
            if (timer) {
                clearTimeout(timer);
            }
            var id = this.id;
            index = getIndex(id.substr(6));
            rechange(index);
            slideImage(index);
            timer = window.setTimeout(auto, offset);
            this.blur();
            return false;
        });
}
function hookBtn() {
    $('#thumbs li img').filter('#play_prev,#play_next')
        .bind('click', function() {
            if (timer) {
                clearTimeout(timer);
            }
            var id = this.id;
            if (id == 'play_prev') {
                index--;
                if (index < 0) index = 6;
            } else {
                index++;
                if (index > 6) index = 0;
            }
            rechange(index);
            slideImage(index);
            timer = window.setTimeout(auto, offset);
        });
}
function getIndex(v) {
    for (var i = 0; i < target.length; i++) {
        if (target[i] == v) return i;
    }
}
function rechange(loop) {
    var id = 'thumb_' + target[loop];
    $('#thumbs li a.current').removeClass('current');
    $('#' + id).addClass('current');
}
function auto() {
    index++;
    if (index > 3) {
        index = 0;
    }
    rechange(index);
    slideImage(index);
    timer = window.setTimeout(auto, offset);
}
$(function() {
    $('div.word').css({ opacity: 0.85 });
    auto();
    hookThumb();
    hookBtn();

});
//NewImageCarousel End

/************Function End**************/

