<%
-- 系统信息js
local XQSysUtil = require "xiaoqiang.util.XQSysUtil"
local XQBackup = require("xiaoqiang.module.XQBackup")
local romVersion = XQSysUtil.getRomVersion()
local uploadUrl = luci.dispatcher.build_url("api", "xqsystem","upload_rom")
local backupKeys = XQBackup.defaultKeys()
%>

<script type="tmpl/text" id="uploadform">
<p><%:路由器正常工作情况下建议使用系统升级检测进行升级，在当系统无法升级或需要降级到前一版本时使用手动上传rom包进行升级。%></p>
<div class="uploadprogress" id="uploadprogress" style="display:none;">
    <div class="progress-text">0%</div>
    <div class="progress"><div class="value"></div></div>
</div>
<div class="uploadloading" id="uploadloading" style="display:none;">
    <div class="loading-bar"></div>
</div>
<form class="form form-upload" name="uploadForm" id="uploadForm" method="post" enctype="multipart/form-data" >
    <div class="item">
        <label class="k"><%:请选择固件:%></label>
        <span class="v">
            <input type="file" name="image" id="image" />
        </span>
        <em class="t"></em>
    </div>
    <div class="item item-contral">
        <button type="button" class="btn btn-block btn-primary-disabled" id="uploadFormBtn" disabled><span><%:开始升级%></span></button>
    </div>
</form>
</script>

<script type="tmpl/text" id="selectBackupList">
<div class="dialog-select-list">
    <p class="gray"><%:可选备份%></p>
    <ul>
    <%for k,v in pairs(backupKeys) do%>
        <li><label><input type="checkbox" name="item" data-key="<%=k%>" checked="true" /> <span class="name"><%=v%></span></label></li>
    <%end%>
    </ul>
    <a href="#" id="btnstartbackup" class="btn btn-primary btn-l"><span><%:开始备份%></span></a>
</div>
</script>
<script type="tmpl/text" id="backupFail">
<div class="dialog-backup-tips">
    <img src="<%=resource%>/web/img/ico_warn.png?v=<%=ver%>">
    <p ><%:由于%> <span></span> <%:原因，路由器设置备份失败！%></p>
    <a href="#" class="btn btn-primary btn-l"><span><%:重试%></span></a>
</div>
</script>
<script type="tmpl/text" id="configUpload">
<div class="config-upload">
    <img src="<%=resource%>/web/img/ico_back.png?v=<%=ver%>">
    <form class="form form-upload" name="configuploadForm" id="configuploadForm" method="post" enctype="multipart/form-data" >
    <div class="item">
        <label class="k"><%:请选择备份文件%></label>
        <span class="v">
            <input type="file" name="image" id="configimage" />
        </span>
        <em class="t"></em>
    </div>
    <div class="item item-contral">
        <button type="button" class="btn btn-block btn-primary-disabled" id="configuploadFormBtn" disabled><span><%:开始恢复%></span></button>
    </div>
    </form>
</div>
</script>
<script type="tmpl/text" id="selectRestoreList">
<div class="dialog-select-list">
    <p class="gray"><%:可选恢复的项目%></p>
    <ul>

    </ul>
    <a href="#" id="btnstartrestore" class="btn btn-primary btn-l"><span><%:恢复%></span></a>
</div>
</script>
<script type="tmpl/text" id="restoresucc">
<div class="dialog-backup-tips">
    <img src="<%=resource%>/web/img/ico_ok.png?v=<%=ver%>">
    <p ><%:路由器设置恢复成功，重启路由器即可生效！%> </p>
    <a href="#" class="btn btn-primary btn-l"><span><%:重启路由器%></span></a>
</div>
</script>
<script type="tmpl/text" id="restorefail">
<div class="dialog-backup-tips">
    <img src="<%=resource%>/web/img/ico_warn.png?v=<%=ver%>">
    <p ><%:由于%> <span></span> <%:原因，路由器设置备份失败！%></p>
    <a href="#" class="btn btn-primary btn-l"><span><%:重试%></span></a>
</div>
</script>
<script type="tmpl/text" id="resettip">
<div class="dialog-reset-tips">
    <img src="<%=resource%>/web/img/ico_warn.png?v=<%=ver%>">
    <p ><%:恢复出厂设置操作会抹掉当前路由器的所有设置，建议您先进行配置备份再恢复出厂设置。%></p>
    <div class="btns">
        <a href="#" id="toconfigbackup" class="btn btn-primary btn-m"><span><%:备份路由器设置%></span></a>
        <a href="#" id="toresetwindow" class="btn btn-primary btn-m"><span><%:直接恢复出厂设置%></span></a>
    </div>
</div>
</script>
<script type="tmpl/text" id="tpltimezone">
<div class="dialog-timezone">
    <div class="clearfix">
        <div class="form-item-select">
            <label class="k"></label>
            <span class="v"><select name="timezone" id="timezone" class="beautify"></select></span>
        </div>
    </div>

    <div>
        <button type="button" id="btnTimezoneSubmit" class="btn btn-primary btn-l"><span><%:确定%></span></button>
    </div>
</div>
</script>
<script type="tmpl/text" id="tpldatetime">
<div class="dialog-datetime">
    <div>
        <span><select name="year" id="year" style="width:80px;"></select> <%:年%></span>
        <span><select name="month" id="month" style="width:80px;"></select> <%:月%></span>
        <span><select name="day" id="day" style="width:80px;"></select> <%:日%></span>
    </div>
    <div>
        <span><select name="hour" id="hour" style="width:80px;"></select> <%:时%></span>
        <span><select name="minute" id="minute" style="width:80px;"></select> <%:分%></span>
        <span><select name="second" id="second" style="width:80px;"></select> <%:秒%></span>
    </div>
    <p><button type="button" id="btnGetNowDate" class="btn btn-dft btn-l"><span><%:当前时间%></span></button></p>
    <p><button type="button" id="btnDatetimeSubmit" class="btn btn-primary btn-l"><span><%:确定%></span></button></p>
</div>
</script>
<script>
// upload method
(function( $ ){
    $.fn.ajaxUpload = function(options){

        var that = this,
            uploadbyiframe = function( options ){
                var d = new Date().getTime(),
                    iframeName = 'iframeUpload' + d,
                    iframeContents,
                    iframe = $('<iframe name="'+iframeName+'" id="'+iframeName+'" style="display: none" />');
                $("body").append(iframe);

                var form = $(that);
                form.attr("action", options.url);
                form.attr("method", "post");
                form.attr("enctype", "multipart/form-data");
                form.attr("encoding", "multipart/form-data");
                form.attr("target", iframeName);
                form.submit();

                form.hide();
                $('#uploadloading').show();
                $(document.getElementById(iframeName))
                    .load(function () {
                        try{
                            iframeContents = document.getElementById(iframeName).contentWindow.document.body.innerHTML;
                            var rsp = iframeContents.match(/^\{.*?\}/);
                            if ( rsp ) {
                                rsp = $.parseJSON(rsp[0]);
                                options.success(rsp);
                            } else {
                                options.error();
                                form.show();
                                $('#uploadloading').hide();
                            }
                        } catch( e ) {
                            options.error();
                            form.show();
                            $('#uploadloading').hide();
                        }
                    })
                    .error(function(){
                        options.error();
                        form.show();
                        $('#uploadloading').hide();
                    });
                return false;

            },
            uploadbyajax = function( options ) {
                var form = $(that);
                var formData = new FormData( form[0] );
                var progressBar = form.find( '.progress' );
                var progressBar = $('#uploadprogress');
                var progressBarVal = progressBar.find( '.progress .value' );
                var progressBarText = progressBar.find( '.progress-text' );

                var xhr = new XMLHttpRequest();
                xhr.open('POST', options.url, true);
                xhr.onload = function(e) {
                    if ( xhr.status === 200) {
                        var rsp = $.parseJSON(e.target.responseText);
                        options.success(rsp);
                    } else {
                        options.error();
                        form.show();
                        progressBar.hide();
                    }
                };
                xhr.onerror = function(e) {
                    options.error();
                    form.show();
                    progressBar.hide();
                };
                xhr.upload.onprogress = function ( e ) {
                    console.log( e, progressBar );
                    if (e.lengthComputable) {
                        form.hide();
                        progressBar.show();
                        var pct = (e.loaded / e.total) * 100;
                        progressBarVal.css({
                            width: pct + '%'
                        });
                        progressBarText.text( parseInt(pct, 10) + '%' );
                    }
                }
                xhr.send(formData);  // multipart/form-data

            };

        if ( window.FormData ) {
            uploadbyajax( options );
        } else {
            uploadbyiframe( options );
        }
    };
})(jQuery);
//check ota
$.sub( 'upgrade:check', function() {
    var requestData = {},
        requestURL = '<%=luci.dispatcher.build_url("api","xqsystem","check_rom_update")%>',
        tplChecking = '<%:当前版本{$romVersion}，{$ret}%>',
        tplHasnew = '<%:发现新版本,升级包大小为{$size}，请立即升级。%>';

    $( '#upgradeinfo' ).html( tplChecking.tmpl( {
        romVersion: '<em class="em"><%=romVersion%></em>',
        ret: '<%:正在检测更新，请稍候...%>'
    } ) );

    $.getJSON( requestURL, requestData, function(rsp) {
        if(rsp.code == 0){
            if( rsp.needUpdate == 1 ){
                $( '#upgradeinfo' ).html( tplHasnew.tmpl( {
                    size: '<em class="em">' + byteFormat( rsp.fileSize ) + '</em>'
                } ) );
                $( '.hasnewver' ).show();
                $( '.logs' ).show();
            } else {
                $( '#upgradeinfo' ).html( tplChecking.tmpl( {
                    romVersion: '<em class="em"><%=romVersion%></em>',
                    ret: '<%:你的版本是最新的，无需升级。%>'
                } ) );
                $(".hasnewver").hide();
            }

            // if ( rsp.changeLog && rsp.changeLog != "" ){
            //     $( '#changelog' ).html( rsp.changeLog );
            // }
            if (rsp.changelogUrl && rsp.changelogUrl != ""){
                $('#changelogUrl').attr('src', rsp.changelogUrl);
                $('#changelogUrl').load(function(){
                    $('#changelog').show();
                });
            }
        } else {
            $( '#upgradeinfo' ).html( tplChecking.tmpl( {
                romVersion: '<em class="em"><%=romVersion%></em>',
                ret: '<%:检查失败，网络繁忙请刷新页面重试。%>'
            } ) );
        }
    })
});

$.sub( 'upgrade:download', function() {

    $( '#btnUpgread' ).on( 'click', function( e ){
        e.preventDefault();
        var url = $(this).attr('href');
        var getUsb = function(){
            return $.ajax({
                url: '<%=luci.dispatcher.build_url("api", "xqsystem", "usbmode")%>',
                type: 'POST',
                dataType: 'json'
            });
        };
        var dlgUpgradeConfirm = $.confirm(
            '<div class="mod-downflash"><%:请注意：升级将会使所有已连接设备的网络中断，升级过程中请勿断开路由器电源或关闭本页面！%></div>',
            function() {
                window.location.href = url;
            }
        );
    });
});

$.sub( 'upgrade:upload', function() {

    function usbservice(enbale) {
        if ( parseInt(G_FEATURES['hardware']['disk'], 10) == 1) {
            return {
                done: function( f ){ f(); }
            };
        }
        var requestURL = '<%=luci.dispatcher.build_url("api", "xqsystem","usbservice")%>',
            requestData = {'enable': enbale};

        return $.ajax({
            url: requestURL,
            type: 'get',
            dataType: 'json',
            data: requestData
        });
    }

    function uploadfile(){
        var apiUpload = '<%=uploadUrl%>',
            options;
        var useInfileUpload = G_FEATURES['system']['infileupload'] === '1';
        if ( useInfileUpload ) {
            apiUpload = '/uploadfile' + apiUpload;
        }

        options = {
            type: 'post',
            dataType: "json",
            url: apiUpload,
            success: function( rsp ) {
                if ( rsp.code == 0 ) {
                    var redirectUrl = '<%=luci.dispatcher.build_url("web", "syslock")%>?flashtype=upload';
                    if ( rsp.downgrade ) {
                        redirectUrl += '&downgrade=1';
                    }
                    window.location.href = redirectUrl;
                } else {
                    $('#uploadprogress, #uploadloading').hide();
                    $( '#uploadForm' ).show();
                    $.alert( rsp.msg ).lock();
                    usbservice(1);
                }
                $('#uploadFormBtn').show();
            },
            error: function() {
                $.alert( '<%:升级失败，系统错误或路由硬盘已满。%>' ).lock();
                $('#uploadFormBtn').show();
            }
        };
        $('#uploadFormBtn').hide();
        usbservice(0).done(function(){
            $( '#uploadForm' ).ajaxUpload( options );
        });
    }

    $( 'body' ).delegate( '#image', 'change', function( e ){

        $( '#uploadFormBtn' ).on( 'enable', function( e, data ) {
            if ( data.disabled ) {
                this.className = 'btn btn-primary-disabled btn-block';
                this.disabled = true;
            } else {
                this.className = 'btn btn-primary btn-block';
                this.disabled = false;
            }
        });

        var image = $( '#image' );
        var err = $( '#uploadForm .t' );
        var item = $( '#uploadForm .item' ).eq( 0 );
        if ( image.val() == '' ) {
            err.html( '<%:你未选择文件，请重新选择%>' ).show();
            item.addClass( 'item-err' );
            $( '#uploadFormBtn' ).trigger( 'enable', {disabled: true} );
            return false;
        }
        var val = image.val();
        var ext = val.substring( val.lastIndexOf( '.' ) + 1 );
        ext = $.trim( ext );
        var validExt = ext == 'bin' || ext == 'BIN';
        if ( !validExt ) {
            err.html( '<%:文件格式错误，请重新选择%>' ).show();
            item.addClass( 'item-err' );
            $( '#uploadFormBtn' ).trigger( 'enable', {disabled: true} );
            return false;
        }
        err.hide();
        item.removeClass( 'item-err' );
        $( '#uploadFormBtn' ).trigger( 'enable', {disabled: false} );
    } );

    var uploadHander = $.throttle(function( e ) {
        e.preventDefault();
        var uploadform = $( '#uploadform' ).html();
        $.dialog({
            id: 'usbcheck_upload',
            width: 390,
            title: '<%:手动升级%>',
            content: '<div class="mod-uploadflash">' + uploadform + '</div>'
        }).lock();
    }, 1000);

    $( '#btnUpload' ).on( 'click', uploadHander);

    $( 'body' ).delegate( '#uploadFormBtn', 'click', function( e ){
        e.preventDefault();
        uploadfile();
        return false;
    });

    $.sub( 'uploadlog', function(){
        // upload logs
        $( '#btnUploadlog' ).on( 'click', function( e ){
            e.preventDefault();
            var requestURL = '<%=luci.dispatcher.build_url("api", "xqsystem","upload_log")%>',
                requestData = {};

            $.pub( 'wait', {id: '#btnUploadlog'} );

            $.getJSON( requestURL, requestData, function( rsp ){
                if( rsp.code===0 ){
                    $.alert( '<%:日志上传成功%>');
                } else {
                    $.alert( rsp.msg );
                }
                $.pub( 'done', {id: '#btnUploadlog'} );
            })
        } );

        // download log
        $( '#btnDownloadlog' ).on( 'click', function( e ){
            e.preventDefault();
            var requestURL = '<%=luci.dispatcher.build_url("api", "misystem","sys_log")%>',
                requestData = {};

            $.pub( 'wait', {id: '#btnDownloadlog'} );

            $.getJSON( requestURL, requestData, function( rsp ){
                if( rsp.code===0 ){
                    window.top.location.href = 'http://' + rsp.path;
                } else {
                    $.alert( rsp.msg );
                }
                $.pub( 'done', {id: '#btnDownloadlog'} );
            })
        });
    } );

    $.sub( 'reset', function(){
        // reset
        $( '#btnReset' ).on( 'click', function( e ){
            e.preventDefault();
            // reset_window();
            $.pub( 'reset:tip' )
        } );
    } );

    $.sub( 'langset', function(){
        $.i18nSet('#lang').done(function(){
            $.selectBeautify();
        });
    } );
});

$.sub( 'reset:tip', function(){
    var tipDialog = $.dialog({
        title: '<%:提示%>',
        content: $('#resettip').html(),
        lock: true,
        width: 390,
        initialize: function(){
            $('#toconfigbackup').on('click', function(e){
                e.preventDefault();
                tipDialog.close();
                $.pub( 'config:backup' );
            });
            $('#toresetwindow').on('click', function(e){
                e.preventDefault();
                tipDialog.close();
                reset_window();
            });
        }
    });
} );

$.sub( 'config:backup', function(){
    var showList = $.dialog({
        title: '<%:备份路由器设置%>',
        content: $('#selectBackupList').html(),
        lock: true,
        width: 390
    });

    $('#btnstartbackup').on('click', function(e){
        e.preventDefault();
        var requestURL = '<%=luci.dispatcher.build_url("api", "misystem","c_backup")%>';
        var requestData = {};
        var keys = [];
        var inputed = $('.dialog-select-list input:checked');
        if( inputed.length > 0 ){
            $( inputed ).each(function(index, item){
                keys.push( $(item).attr('data-key') );
            });
            keys = keys.join(',');
            requestData.keys = keys;
            $.getJSON( requestURL, requestData, function( rsp ){
                showList.close();
                if( rsp.code==0 ){
                    // download
                    window.location.href = 'http://' + rsp.url;
                } else {
                    $.pub( 'config:backupfail', {msg: rsp.msg} );
                }
            });
        }else{
            $.alert('<%:至少选择1个%>');
        }
    });
});

$.sub( 'config:backupfail', function(evt, data){
    var msg = data.msg;
    var failDialog = $.dialog({
        title: '<%:备份路由器设置%>',
        content: $('#backupFail').html(),
        lock: true,
        width: 390,
        initialize: function(){
            $('.dialog-backup-tips p span').text( msg );
            $('.dialog-backup-tips .btn').on('click', function(e){
                e.preventDefault();
                failDialog.close();
                $.pub( 'config:backup' );
            });
        }
    });
});

$.sub( 'config:restore', function(evt, data){
    var keys = data.keys;
    var tpl = '<li><label><input type="checkbox" name="item" data-key="{$k}" checked="true" /> <span class="name">{$v}</span></label></li>';
    var html = [];
    var li = '';
    for(var key in keys ){
        li = StringH.tmpl(tpl, {
            k: key,
            v: keys[key]
        });
        html.push( li );
    }

    var showRestoreList = $.dialog({
        title: '<%:从备份恢复路由器设置%>',
        content: $('#selectRestoreList').html(),
        lock: true,
        width: 390,
        initialize: function(){
            $('.dialog-select-list ul').html( html.join('') );
        }
    });

    $('#btnstartrestore').on('click', function(e){
        e.preventDefault();
        var requestURL = '<%=luci.dispatcher.build_url("api", "misystem","c_restore")%>';
        var requestData = {};
        var keys = [];
        var inputed = $('.dialog-select-list input:checked');
        if( inputed.length > 0 ){
            $( inputed ).each(function(index, item){
                keys.push( $(item).attr('data-key') );
            });
            keys = keys.join(',');
            requestData.keys = keys;
            $.getJSON( requestURL, requestData, function( rsp ){
                showRestoreList.close();
                if( rsp.code==0 ){
                    $.pub( 'config:restoresucc' );
                } else {
                    $.pub( 'config:restorefail', {msg: rsp.msg} );
                }
            });
        }else{
            $.alert('<%:至少选择1个%>');
        }
    });
});

$.sub( 'config:restoresucc', function(evt, data){

    var succDialog = $.dialog({
        title: '<%:从备份恢复路由器设置%>',
        content: $('#restoresucc').html(),
        lock: true,
        width: 390,
        initialize: function(){
            $('.dialog-backup-tips .btn').on('click', function(e){
                e.preventDefault();
                succDialog.close();
                reboot_window();
            });
        }
    });
});

$.sub( 'config:restorefail', function(evt, data){
    var msg = data.msg;
    var failDialog = $.dialog({
        title: '<%:从备份恢复路由器设置%>',
        content: $('#restorefail').html(),
        lock: true,
        width: 390,
        initialize: function(){
            $('.dialog-backup-tips p span').text( msg );
            $('.dialog-backup-tips .btn').on('click', function(e){
                e.preventDefault();
                failDialog.close();
                $.pub( 'config:upload' );
            });
        }
    });
});

$.sub( 'config:upload', function(){
    var showUpload = $.dialog({
        title: '<%:从备份恢复路由器设置%>',
        content: $('#configUpload').html(),
        lock: true,
        width: 390
    });
    function uploadfile(){

        var options = {
            type: 'post',
            dataType: "json",
            url: '<%=luci.dispatcher.build_url("api", "misystem","c_upload")%>',
            success: function( rsp ) {
                console.log( rsp );
                if( rsp.code == 0 ){
                    showUpload.close();
                    $.pub( 'config:restore', rsp.des );
                }else{
                    $.alert( rsp.msg );
                }
            },
            error: function() {
                $.alert( '<%:系统错误，请重试。%>' ).lock();
                $('#configuploadFormBtn').show();
            }
        };
        $('#configuploadFormBtn').hide();
        $( '#configuploadForm' ).ajaxUpload( options );
    }
    $( 'body' ).delegate( '#configimage', 'change', function( e ){
        $( '#configuploadFormBtn' ).on( 'enable', function( e, data ) {
            if ( data.disabled ) {
                this.className = 'btn btn-primary-disabled btn-block';
                this.disabled = true;
            } else {
                this.className = 'btn btn-primary btn-block';
                this.disabled = false;
            }
        });

        var image = $( '#configimage' );
        var err = $( '#configuploadForm .t' );
        var item = $( '#configuploadForm .item' ).eq( 0 );
        if ( image.val() == '' ) {
            err.html( '<%:你未选择文件，请重新选择%>' ).show();
            item.addClass( 'item-err' );
            $( '#configuploadFormBtn' ).trigger( 'enable', {disabled: true} );
            return false;
        }
        var val = image.val();
        var ext = val.substring( val.lastIndexOf( '.' ) + 1 );
        ext = $.trim( ext );
        var validExt = ext == 'gz' || ext == 'GZ';
        if ( !validExt ) {
            err.html( '<%:文件格式错误，请重新选择%>' ).show();
            item.addClass( 'item-err' );
            $( '#configuploadFormBtn' ).trigger( 'enable', {disabled: true} );
            return false;
        }
        err.html('');
        item.removeClass( 'item-err' );
        $( '#configuploadFormBtn' ).trigger( 'enable', {disabled: false} );
    } );
    $( 'body' ).undelegate( '#configuploadFormBtn', 'click' );
    $( 'body' ).delegate( '#configuploadFormBtn', 'click', function( e ){
        e.preventDefault();
        uploadfile();
        return false;
    });
});

$.sub( 'config:init', function(){
    $('#btnBackupconfig').on('click', function(e){
        e.preventDefault();
        $.pub( 'config:backup' );
    });
    $('#btnUploadconfig').on('click', function(e){
        e.preventDefault();
        $.pub( 'config:upload' );
    });
});

$.sub('datetime', function(){
    var TIMEZONES =  [
    ['CST+12', '<%:(UTC-12)国际日期变更线西%>'],
    ['CST+11', '<%:(UTC-11)萨摩亚群岛%>'],
    ['CST+11', '<%:(UTC-11)协调世界时%>'],
    ['CST+10', '<%:(UTC-10)夏威夷%>'],
    ['CST+9:30', '<%:(UTC-9:30)马克萨斯群岛标准时间%>'],
    ['CST+9', '<%:(UTC-9)阿拉斯加%>'],
    ['CST+8', '<%:(UTC-8)太平洋时间(美国和加拿大)%>'],
    ['CST+8', '<%:(UTC-8)下加利福尼亚州%>'],
    ['CST+7', '<%:(UTC-7)奇瓦瓦,拉巴斯,马萨特兰%>'],
    ['CST+7', '<%:(UTC-7)山地时间(美国和加拿大)%>'],
    ['CST+7', '<%:(UTC-7)亚利桑那%>'],
    ['CST+6', '<%:(UTC-6)瓜达拉哈拉,墨西哥城,蒙特雷%>'],
    ['CST+6', '<%:(UTC-6)萨斯克彻温%>'],
    ['CST+6', '<%:(UTC-6)中部时间(美国和加拿大)%>'],
    ['CST+6', '<%:(UTC-6)中美洲%>'],
    ['CST+5', '<%:(UTC-5)波哥大,利马,基多%>'],
    ['CST+5', '<%:(UTC-5)东部时间(美国和加拿大)%>'],
    ['CST+5', '<%:(UTC-5)印第安纳州(东部)%>'],
    ['CST+4:30', '<%:(UTC-4:30)加拉加斯%>'],
    ['CST+4', '<%:(UTC-4)大西洋时间(加拿大)%>'],
    ['CST+4', '<%:(UTC-4)库亚巴%>'],
    ['CST+4', '<%:(UTC-4)乔治敦,拉巴斯,马瑙斯,圣湖安%>'],
    ['CST+4', '<%:(UTC-4)圣地亚哥%>'],
    ['CST+4', '<%:(UTC-4)亚松森%>'],
    ['CST+3:30', '<%:(UTC-3:30)纽芬兰%>'],
    ['CST+3', '<%:(UTC-3)巴西利亚%>'],
    ['CST+3', '<%:(UTC-3)布宜诺斯艾利斯%>'],
    ['CST+3', '<%:(UTC-3)格陵兰%>'],
    ['CST+3', '<%:(UTC-3)卡宴,福塔雷萨%>'],
    ['CST+3', '<%:(UTC-3)蒙得维的亚%>'],
    ['CST+2', '<%:(UTC-2)协调世界时-02%>'],
    ['CST+2', '<%:(UTC-2)中大西洋%>'],
    ['CST+1', '<%:(UTC-1)佛得角群岛%>'],
    ['CST+1', '<%:(UTC-1)亚速尔群岛%>'],
    ['CST', '<%:(UTC)都柏林,爱丁堡,里斯本,伦敦%>'],
    ['CST', '<%:(UTC)卡萨布兰卡%>'],
    ['CST', '<%:(UTC)蒙罗维亚,雷克雅未克%>'],
    ['CST', '<%:(UTC)协调世界时%>'],
    ['CST-1', '<%:(UTC+1)阿姆斯特丹,柏林,伯尔尼,罗马,斯德歌尔摩,维也纳%>'],
    ['CST-1', '<%:(UTC+1)贝尔格莱德,布拉迪斯拉发,布达佩斯,卢布尔雅那%>'],
    ['CST-1', '<%:(UTC+1)布鲁塞尔,哥本哈根,马德里,巴黎%>'],
    ['CST-1', '<%:(UTC+1)萨拉热窝,斯科普里,华沙,萨格勒布%>'],
    ['CST-1', '<%:(UTC+1)温得和克%>'],
    ['CST-1', '<%:(UTC+1)中非西部%>'],
    ['CST-2', '<%:(UTC+2)安曼%>'],
    ['CST-2', '<%:(UTC+2)贝鲁特%>'],
    ['CST-2', '<%:(UTC+2)大马士革%>'],
    ['CST-2', '<%:(UTC+2)哈拉雷,比勒陀利亚%>'],
    ['CST-2', '<%:(UTC+2)赫尔辛基,基辅,里加,索非亚,塔林,维尔纽斯%>'],
    ['CST-2', '<%:(UTC+2)开罗%>'],
    ['CST-2', '<%:(UTC+2)明斯克%>'],
    ['CST-2', '<%:(UTC+2)雅典,布加勒斯特%>'],
    ['CST-2', '<%:(UTC+2)耶路撒冷%>'],
    ['CST-2', '<%:(UTC+2)伊斯坦布尔%>'],
    ['CST-3', '<%:(UTC+3)巴格达%>'],
    ['CST-3', '<%:(UTC+3)加里宁格勒%>'],
    ['CST-3', '<%:(UTC+3)科威特,利雅得%>'],
    ['CST-3', '<%:(UTC+3)内罗毕%>'],
    ['CST-3:30', '<%:(UTC+3:30)德黑兰%>'],
    ['CST-4', '<%:(UTC+4)阿布扎比,马斯喀特%>'],
    ['CST-4', '<%:(UTC+4)埃里温%>'],
    ['CST-4', '<%:(UTC+4)巴库%>'],
    ['CST-4', '<%:(UTC+4)第比利斯%>'],
    ['CST-4', '<%:(UTC+4)路易港%>'],
    ['CST-4', '<%:(UTC+4)莫斯科,圣彼得堡,伏尔加格勒%>'],
    ['CST-4:30', '<%:(UTC+4:30)喀布尔%>'],
    ['CST-5', '<%:(UTC+5)塔什干%>'],
    ['CST-5', '<%:(UTC+5)伊斯兰堡,卡拉奇%>'],
    ['CST-5:30', '<%:(UTC+5:30)钦奈,加尔各答,孟买,新德里%>'],
    ['CST-5:30', '<%:(UTC+5:30)斯里加亚渥登普拉%>'],
    ['CST-5:45', '<%:(UTC+5:45)加德满都%>'],
    ['CST-6', '<%:(UTC+6)阿斯塔纳%>'],
    ['CST-6', '<%:(UTC+6)达卡%>'],
    ['CST-6', '<%:(UTC+6)叶卡捷琳堡%>'],
    ['CST-6:30', '<%:(UTC+6:30)仰光%>'],
    ['CST-7', '<%:(UTC+7)曼谷,河内,雅加达%>'],
    ['CST-7', '<%:(UTC+7)新西伯利亚%>'],
    ['CST-8', '<%:(UTC+8)北京,重庆,香港特别行政区,乌鲁木齐%>'],
    ['CST-8', '<%:(UTC+8)吉隆坡,新加坡%>'],
    ['CST-8', '<%:(UTC+8)克拉斯诺亚尔斯克%>'],
    ['CST-8', '<%:(UTC+8)珀斯%>'],
    ['CST-8', '<%:(UTC+8)台北%>'],
    ['CST-8', '<%:(UTC+8)乌兰巴托%>'],
    ['CST-8:30', '<%:(UTC+8:30)朝鲜标准时间%>'],
    ['CST-9', '<%:(UTC+9)大阪,札幌,东京%>'],
    ['CST-9', '<%:(UTC+9)首尔%>'],
    ['CST-9', '<%:(UTC+9)伊尔库茨克%>'],
    ['CST-9:30', '<%:(UTC+9:30)阿德莱德%>'],
    ['CST-9:30', '<%:(UTC+9:30)达尔文%>'],
    ['CST-10', '<%:(UTC+10)布里斯班%>'],
    ['CST-10', '<%:(UTC+10)关岛,莫尔兹比港%>'],
    ['CST-10', '<%:(UTC+10)霍巴特%>'],
    ['CST-10', '<%:(UTC+10)堪培拉,墨尔本,悉尼%>'],
    ['CST-10', '<%:(UTC+10)雅库茨克%>'],
    ['CST-10:30', '<%:(UTC+10:30)澳大利亚远东标准时间%>'],
    ['CST-11', '<%:(UTC+11)符拉迪沃斯托克%>'],
    ['CST-11', '<%:(UTC+11)所罗门群岛,新喀里多尼亚%>'],
    ['CST-11:30', '<%:(UTC+11:30)诺福克岛标准时间%>'],
    ['CST-12', '<%:(UTC+12)奥克兰,惠灵顿%>'],
    ['CST-12', '<%:(UTC+12)斐济%>'],
    ['CST-12', '<%:(UTC+12)马加丹%>'],
    ['CST-12', '<%:(UTC+12)协调世界时+12%>'],
    ['CST-12:45', '<%:(UTC+12:45)查塔姆群岛标准时间%>'],
    ['CST-13', '<%:(UTC+13)努库阿洛法%>'],
    ['CST-14', '<%:(UTC+14)基里巴斯%>']
],indexDict = {
    "CST+3:30": [
        24
    ],
    "CST-6": [
        71,
        72,
        73
    ],
    "CST-12:45": [
        102
    ],
    "CST+6": [
        11,
        12,
        13,
        14
    ],
    "CST+11": [
        1,
        2
    ],
    "CST": [
        34,
        35,
        36,
        37
    ],
    "CST-8": [
        77,
        78,
        79,
        80,
        81,
        82
    ],
    "CST-9": [
        84,
        85,
        86
    ],
    "CST-5:30": [
        68,
        69
    ],
    "CST-9:30": [
        87,
        88
    ],
    "CST-4:30": [
        65
    ],
    "CST+10": [
        3
    ],
    "CST+3": [
        25,
        26,
        27,
        28,
        29
    ],
    "CST-8:30": [
        83
    ],
    "CST-10": [
        89,
        90,
        91,
        92,
        93
    ],
    "CST-10:30": [
        94
    ],
    "CST-2": [
        44,
        45,
        46,
        47,
        48,
        49,
        50,
        51,
        52,
        53
    ],
    "CST+12": [
        0
    ],
    "CST-14": [
        104
    ],
    "CST-12": [
        98,
        99,
        100,
        101
    ],
    "CST-5": [
        66,
        67
    ],
    "CST+4:30": [
        18
    ],
    "CST-1": [
        38,
        39,
        40,
        41,
        42,
        43
    ],
    "CST-3": [
        54,
        55,
        56,
        57
    ],
    "CST+9": [
        5
    ],
    "CST-7": [
        75,
        76
    ],
    "CST-4": [
        59,
        60,
        61,
        62,
        63,
        64
    ],
    "CST-13": [
        103
    ],
    "CST-11:30": [
        97
    ],
    "CST-11": [
        95,
        96
    ],
    "CST-3:30": [
        58
    ],
    "CST-5:45": [
        70
    ],
    "CST+8": [
        6,
        7
    ],
    "CST+1": [
        32,
        33
    ],
    "CST+9:30": [
        4
    ],
    "CST+2": [
        30,
        31
    ],
    "CST+7": [
        8,
        9,
        10
    ],
    "CST-6:30": [
        74
    ],
    "CST+4": [
        19,
        20,
        21,
        22,
        23
    ],
    "CST+5": [
        15,
        16,
        17
    ]
},
        getMaxDays = function(year, month) {
            var tmpDate = new Date(year, month-1, 1),
                d = 28, m;
            m = tmpDate.getMonth();
            d = 28;
            while (tmpDate.getMonth() == m) {
                d ++;
                tmpDate.setDate(d);
            }
            return d - 1;
        },
        randerYear = function(y){
            var min = y - 10,
                max = y + 10;
            var options = [];
            for (var i = min; i <= max; i++) {
                if (y === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerMonth = function(m){
            var options = [];
            for (var i = 1; i <= 12; i++) {
                if (m === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerDay = function(year, month, day){
            var days = getMaxDays(year, month);
            var options = [];
            for (var i = 1; i <= days; i++) {
                if (day === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerHour = function(h){
            var options = [];
            for (var i = 0; i <= 23; i++) {
                if (h === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerMin = function(m){
            var options = [];
            for (var i = 0; i <= 59; i++) {
                if (m === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerSec = function(s){
            var options = [];
            for (var i = 0; i <= 59; i++) {
                if (s === i) {
                    options.push('<option value="'+ i +'" selected="selected">'+ i +'</option>');
                } else {
                    options.push('<option value="'+ i +'">'+ i +'</option>');
                }
            }
            return options.join('');
        },
        randerTimezone = function(now,index){
            var options = [],val;
             for(var attr in indexDict){   
                    if(attr === now ) {
                         val = indexDict[attr][index];

                    }
            }
            for (var i = 0; i < TIMEZONES.length; i++) {
                if ( i === val) {
                    options.push('<option value="'+ TIMEZONES[i][0] +'" selected="selected">'+ TIMEZONES[i][1] +'</option>');
                } else {
                    options.push('<option value="'+ TIMEZONES[i][0] +'">'+ TIMEZONES[i][1] +'</option>');
                }
            }
            return options.join('');
        },
        getTimezone = function(now,index){
            var val;
            for(var attr in indexDict){   
                    if(attr === now ) {
                         val = TIMEZONES[indexDict[attr][index]][1];

                    }
            }
            return val;
        };

    var routerDatetime;
    $.getJSON('<%=luci.dispatcher.build_url("api","misystem","sys_time")%>', function(rsp){
        if (rsp.code === 0) {
            var timezone = rsp.time.timezone;
            var index = rsp.time.index;
            var tpldatetime = '<%:{$year}年{$month}月{$day}日 {$hour}:{$min}:{$sec}%>';
            var datetiem = StringH.tmpl(tpldatetime, rsp.time);

            routerDatetime = rsp.time;

            var roterDate = new Date(rsp.time.year, rsp.time.month - 1, rsp.time.day, rsp.time.hour, rsp.time.min, rsp.time.sec).getTime();
            var clientDate = new Date().getTime();
            var dateDiff = clientDate - roterDate;
            $('#timezoneval').html(getTimezone(timezone,index));

            setInterval(function(){
                var d = new Date(new Date().getTime() - dateDiff);
                var dStr = DateH.format(d,"<%:yyyy年M月d日 hh:mm:ss%>");
                $('#datetiemval').html(dStr);
            }, 1000);
            $('#datetiemval').html(datetiem);
        }
    });

    var dlgTimezone, dlgDatetime, updateDatetime;
    updateDatetime = function(d){
        var optionsYear = randerYear(d.year);
        $('#year').html(optionsYear);
        var optionsMonth = randerMonth(d.month);
        $('#month').html(optionsMonth);
        var optionsDay = randerDay(d.year, d.month, d.day);
        $('#day').html(optionsDay);

        var optionsHour = randerHour(d.hour);
        $('#hour').html(optionsHour);
        var optionsMin = randerMin(d.min);
        $('#minute').html(optionsMin);
        var optionsSec = randerSec(d.sec);
        $('#second').html(optionsSec);
    };

    $('#btnTimezone').click(function(e){
        e.preventDefault();
        dlgTimezone = $.dialog({
            width: 390,
            title: '<%:更改时区%>',
            content: $('#tpltimezone').html(),
            lock: true
        });

        setTimeout(function(){
            var options = randerTimezone(routerDatetime.timezone,routerDatetime.index);
            console.log(options);
            $('#timezone').html(options);
            $.selectBeautify({container: '.dialog-timezone'});
        }, 200);
    });

    $('#btnDatetime').click(function(e){
        e.preventDefault();
        dlgDatetime = $.dialog({
            width: 390,
            title: '<%:更改时间%>',
            content: $('#tpldatetime').html(),
            lock: true
        });
        setTimeout(function(){

            updateDatetime(routerDatetime);

            var updateDays = function(){
                var y = $('#year').val(),
                    m = $('#month').val(),
                    d = new Date().getDate();
                var optionsDay = randerDay(y, m, d);
                $('#day').html(optionsDay);
            }
            $('#year').on('change', updateDays);
            $('#month').on('change', updateDays);
        }, 200);
    });

    $('body').delegate('#btnGetNowDate', 'click', function(e){
        e.preventDefault();
        var dObj = {},
            d = new Date();
        dObj.year = d.getFullYear();
        dObj.month = d.getMonth() + 1;
        dObj.day = d.getDate();
        dObj.hour = d.getHours();
        dObj.min = d.getMinutes();
        dObj.sec = d.getSeconds();
        updateDatetime(dObj);
    });

    $('body').delegate('#btnTimezoneSubmit', 'click', function(e){
        e.preventDefault();
        var timezone = $('#timezone').val();
        var index;
        $('#timezone option').each(function(i){
            if (this.selected == true) {
                for(var j = 0; j < indexDict[timezone].length; j++){
                    if (indexDict[timezone][j] == i) {
                        index = j;
                    }
                 }
                
            }
        })
        $.post('<%=luci.dispatcher.build_url("api","misystem","set_sys_time")%>', {timezone: timezone,index: index}, function(rsp){
            rsp = $.parseJSON(rsp);
            if (rsp.code === 0) {
                dlgTimezone.close();
                location.reload();
            } else {
                $.alert(rsp.msg);
            }
        });
    });

    $('body').delegate('#btnDatetimeSubmit', 'click', function(e){
        e.preventDefault();
        var time = $('#year').val() + '-' + $('#month').val() + '-' + $('#day').val() + ' ' + $('#hour').val() + ':' + $('#minute').val() + ':' + $('#second').val();
        $.post('<%=luci.dispatcher.build_url("api","misystem","set_sys_time")%>', {time: time}, function(rsp){
            rsp = $.parseJSON(rsp);
            if (rsp.code === 0) {
                dlgDatetime.close();
                $.alert('<%:设置成功，稍后生效，请等待一会刷新。%>');
            } else {
                $.alert(rsp.msg);
            }
        });
    });

});

$(function(){
    $.pub( 'upgrade:check' );
    $.pub( 'upgrade:download' );
    $.pub( 'upgrade:upload' );
    $.pub( 'uploadlog' );
    $.pub( 'reset' );
    if (document.getElementById('lang')) {
        $.pub( 'langset' );
    }
    $.pub( 'config:init' );
    $.pub('datetime');
});
</script>
