﻿function convertToTime(str) {
    var re = /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/gi;
    var dt = str.replace(re, function() {
        var args = arguments;
        return new Date(parseInt(args[1], 10), parseInt(args[2], 10) - 1, parseInt(args[3], 10), parseInt(args[4], 10), parseInt(args[5], 10), parseInt(args[6], 10)).getTime()
    });
    return parseInt(dt, 10);
}
var interDelay = 1000;
$.post("timer/NowTime.aspx", function(res) {
    var now = convertToTime(res);
    var start = convertToTime(GM.s);
    var end = convertToTime(GM.e);
    var intval = setInterval(function() {
        now += interDelay;
        if (now < start) {
            $("#imgSub").hide();
            var ctime = start - now;
            var hour = Math.floor(ctime / 60 / 60 / 1000);
            var minute = Math.floor(ctime / 60 / 1000 % 60);
            var second = Math.floor(ctime / 1000 % 60);
            if (hour > 99) {
                $("#sph").html(hour);
            } else if(hour > 9) {
                $("#sph").html("0" + hour);
            }else {
                $("#sph").html("00" + hour);
            }
            if (minute > 9) {
                $("#spm").html(minute);
            } else {
                $("#spm").html("0" + minute);
            }
            if (second > 9) {
                $("#sps").html(second);
            } else {
                $("#sps").html("0" + second);
            }
            return;
        }
        if (now >= start && now <= end) {
            clearInterval(intval);
            $("#imgSub").hide();
            $("#divMath").show();
            $("#divTimer0").hide();
            $("#divTimer1").hide();
            $("#divTimer2").hide();
            $("#sph").html("000");
            $("#spm").html("00");
            $("#sps").html("00");
            var bm = setInterval(function() {
                now += interDelay;
                if (now >= end) {
                    clearInterval(bm);
                    $("#divMath").hide();
                    $("#imgSub").attr("src", "timer/over.gif").unbind("click").show();
                }
            }, interDelay);
            return;
        }
        if (now > end) {
            $("#divMath").hide();
            $("#imgSub").attr("src", "timer/over.gif").unbind("click").show();
            $("#divTimer1").hide();
            $("#divTimer2").hide();
            $("#sph").html("000");
            $("#spm").html("00");
            $("#sps").html("00");
            clearInterval(intval);
            return;
        }
    }, interDelay);
});
