var minwidth;
var orderData;
var ErrField;

var output;
var OID;

function ChangeTotalMoney() {
    var total_money = 0;

    for(var i = 0; i < item.length; i++) {
        total_money += $('#PayCount' + i).val() * item[i].price;
    }

    $('#TotalMoney').html(total_money);

    if(total_money > 0) {
        $('#PayMoney').val(total_money);
    } else {
        $('#PayMoney').val('');
    }
}

function showField() {
    if($('#PayMethodT').attr('checked')) {
        $('.AccountIDField').show();
    } else {
        $('.AccountIDField').hide();
    }

    if($('#PayMethodR').attr('checked')) {
        $('.RemitNameField').show();
    } else {
        $('.RemitNameField').hide();
    }

    if($('#PayMethodP').attr('checked')) {
        $('.TransactionSNField').show();
    } else {
        $('.TransactionSNField').hide();
    }
}

function showInvoiceField() {
    if($('#InvoiceType3').attr('checked')) {
        $('.onlyInvoice3').show();
    } else {
        $('.onlyInvoice3').hide();
        /* $('#MsgInvoiceTitle').html(''); */
        $('#MsgInvoiceID').html('');
    }
}

function previewShow() {
    var arrPageSizes = getPageSize();
    if(arrPageSizes[0] < minwidth) arrPageSizes[0] = minwidth;

    if($.browser.msie && $.browser.version < 7) {
        $('embed, object, select').css({ 'visibility' : 'hidden' });
    }

    $('.stepblock').hide();
    $('#step1').show();

    $('#jquery-overlay').css({
        opacity:    0.7,
        width:      arrPageSizes[0],
        height:     arrPageSizes[1]
    }).show();

    var arrPageScroll = getPageScroll();

    $('#jquery-lightbox').css({
        top:        arrPageScroll[1] + (arrPageSizes[3] / 10),
        left:       arrPageScroll[0]
    }).show();

    $(window).bind('resize', previewResize);
}

function previewCancel() {
    $('#jquery-overlay').hide();
    $('#jquery-lightbox').hide();

    $(window).unbind('resize', previewResize);

    if($.browser.msie && $.browser.version < 7) {
        $('embed, object, select').css({ 'visibility' : 'visible' });
    }
}

function previewResize() {
    var arrPageSizes = getPageSize();
    if(arrPageSizes[0] < minwidth) arrPageSizes[0] = minwidth;

    $('#jquery-overlay').css({
        width:      arrPageSizes[0],
        height:     arrPageSizes[1]
    });

    var arrPageScroll = getPageScroll();

    $('#jquery-lightbox').css({
        top:        arrPageScroll[1] + (arrPageSizes[3] / 10),
        left:       arrPageScroll[0]
    });
}

function checkForm() {
    var itemcnt = 0;

    ErrField = '';

    for(var i = 0; i < item.length; i++) {
        itemcnt += $('#PayCount' + i).val() * 1;
    }

    if(! itemcnt) {
        alert('請先選擇您要訂購的產品！');
        return;
    }

    checkfield('Name', 0);
    checkfield('Address', 0);
    checkfield('TelNo', 0);

    if($('#Email').val() != '' && ! RegEmail.test($('#Email').val())) {
        $('#MsgEmail').html('Email 格式錯誤');
        if(! ErrField) ErrField = "Email";
    } else {
        $('#MsgEmail').html('');
    }

    if(checkfield('PayDate', 0, new RegExp('^[0-9]{4}/[0-9]{1,2}/[0-9]{1,2}$', ''))) {
        var PayDate = new Date($('#PayDate').val());
        if(isNaN(PayDate) || ! checkDate(PayDate.getYear(), PayDate.getMonth() + 1, PayDate.getDate())) {
            $('#PayDate').val(todayStr);
        }
    }

    if($('#PayMethodT').attr('checked')) {
        checkfield('AccountID', 0, new RegExp('^[0-9]{5}$', ''));
    } else if($('#PayMethodR').attr('checked')) {
        checkfield('RemitName', 0);
    } else {
        checkfield('TransactionSN', 0, new RegExp('^[0-9]{8}$', ''));
    }

    checkfield('PayMoney', 0, new RegExp('^[0-9]+$', ''));

    if($('#InvoiceType3').attr('checked')) {
								/*checkfield('InvoiceTitle', 0);*/
        checkfield('InvoiceID', 0, new RegExp('^[0-9]{8}$', ''));
    }

    if(ErrField) {
        $('#' + ErrField).get(0).focus();
        return false;
    }

    return true;
}

function Preview() {
    if(! checkForm()) return;

    var tmp;

    output = new Array();

    orderData = {};

    output.push('<table><tr><th style="width:10em">品名</th><th>單價</th><th>數量</th><th>總價</th></tr>');

    orderData.PayItem = '';

    for(var i = 0; i < item.length; i++) {
        var cnt = $('#PayCount' + i).val() * 1;

        if(cnt) {
            if(orderData.PayItem) orderData.PayItem += ';';
            orderData.PayItem += item[i].name + "|" + cnt + "|" + item[i].price;

            output.push('<tr><td>' + item[i].name + '</td><td style="text-align:right">' + item[i].price + ' 元</td><td style="text-align:right">' + cnt + ' 份</td><td style="text-align:right">' + (cnt * item[i].price) + ' 元</td></tr>');
        }
    }

    output.push('</table><br /><table>');

    if($('#GenderM').attr('checked')) {
        orderData.Gender = 'M';
        tmp = " 先生";
    } else if($('#GenderF').attr('checked')) {
        orderData.Gender = 'F';
        tmp = " 小姐";
    } else {
        orderData.Gender = 'N';
        tmp = "";
    }

    orderData.Name = $('#Name').val();
    output.push('<tr><th>收件人</th><td>' + htmlspecialchars(orderData.Name) + tmp + '</td></tr>');

    orderData.PostCode = $('#PostCodeShow').html();
    orderData.Address = $('#City').val() + $('#Canton').val() + $('#Address').val();
    output.push('<tr><th>收件地址</th><td>(' + orderData.PostCode + ') ' + htmlspecialchars(orderData.Address) + '</td></tr>');

    orderData.TelNo = $('#TelNo').val();
    output.push('<tr><th>聯絡電話</th><td>' + htmlspecialchars(orderData.TelNo) + '</td></tr>');

    orderData.Email = $('#Email').val();
    output.push('<tr><th>Email</th><td>' + htmlspecialchars(orderData.Email) + '</td></tr>');

    orderData.PayDate = $('#PayDate').val();
    orderData.PayMoney = $('#PayMoney').val();

    if($('#PayMethodT').attr('checked')) { // ATM 轉帳
        orderData.PayMethod = 'T';
        orderData.TransactionID = $('#AccountID').val();

        tmp = 'ATM 轉帳 (帳號末五碼: ' + orderData.TransactionID + ')';
    } else if($('#PayMethodR').attr('checked')) { // 匯款
        orderData.PayMethod = 'R';
        orderData.TransactionID = $('#RemitName').val();

        tmp = '臨櫃匯款 (匯款人: ' + orderData.TransactionID + ')';
    } else { // 劃撥
        orderData.PayMethod = 'P';
        orderData.TransactionID = $('#TransactionSN').val();

        tmp = '郵局劃撥 (交易序號 : ' + orderData.TransactionID + ')';
    }

    output.push('<tr><th>付款資訊</th><td>' + orderData.PayDate + '；' + htmlspecialchars(tmp) + '；金額: ' + orderData.PayMoney + '</td></tr>');

    orderData.InvoiceTitle = $('#InvoiceTitle').val();

    if($('#InvoiceType3').attr('checked')) {

        orderData.InvoiceType = '3';
        orderData.InvoiceID = $('#InvoiceID').val();

        tmp = "三聯式 (抬頭: " + htmlspecialchars(orderData.InvoiceTitle) + "、統編: " + orderData.InvoiceID + ")";

    } else {
        orderData.InvoiceType = '2';
        orderData.InvoiceID = '';

        if(orderData.InvoiceTitle != '') {
            tmp = "二聯式 (抬頭: " + htmlspecialchars(orderData.InvoiceTitle) + ")";
        } else {
            tmp = "二聯式";
        }
    }

    output.push('<tr><th>發票</th><td>' + tmp + '</td></tr>');

    orderData.Comment = $('#Comment').val();
    output.push('<tr><th>備註</th><td>' + htmlspecialchars(orderData.Comment).replace(/\n/g, "<br />") + '</td></tr>');

    output.push('</table>');

    $('#previewList').html(output.join(''));

    previewShow();
    $('#submitButton').get(0).focus();
}

function submitOrder() {
    $('.stepblock').height($('#step1').height() + 26);

    $('#step1').hide();
    $('#step2').show();

    ajax = $.ajax({
        url: "./orderform_proc.php",
        type: "POST",
        data: orderData,
        cache: false,
        dataType: "json",
        timeout: 30000,

        success: function(data) {
            $('#step2').hide();

            switch(data[0]) {
            case 0:
                OID = data[1];

                $('#orderID').text(OID);
                $('#step3').show();
                break;
            case 1:
                $('#returnMessage').text(data[1]);
                $('#step5').show();
                break;
            default:
                $('#step4').show();
                break;
            }

            return;
        },

        error: function() {
            $('#step2').hide();
            $('#step4').show();
        }
    });
}

function printOrder() {
    var wid = window.open('about:blank','_blank','width=660,height=500,resizable=no,scrollbars=yes');

    wid.document.open();
    wid.document.write(
        '<html><head><title>行易有限公司 線上訂購表格 訂單編號: ' + OID + '</title>' +
        '<meta http-equiv="content-type" content="text/html; charset=utf-8">' +
        '<link rel="stylesheet" href="liu.css" type="text/css" />' +
        '<style>' +
        '   body{background:none white; margin:1em}' +
        '   table{width: 100%}' +
        '   th, td{padding: 3px 5px}' +
        '</style>' +
        '</head><body onload="print();">' +
        '<h2>訂單編號: ' + OID + '</h2>' +
        '<div class="sgltable"><center>'
    );

    wid.document.write(output.join(''));

    wid.document.write(
        '</center></div>'+
        '<div style="text-align: center; margin-top:1em">' +
        '<input type="button" value="列印" onclick="print();" style="width: 7em; font-weight: bold" />　　' +
        '<input type="button" value="關閉視窗" onclick="window.close();" style="width: 7em" />　' +
        '</div>'+
        '</body></html>'
    );

    wid.document.close();
}

function PrintEULA() {
    var eula_win = window.open("", "EULAWin", "width=640,height=480");
    var EULAsub = $("#EULA").val().replace(/\n/g, "<br />");

    eula_win.document.open();
    eula_win.document.write(EULAsub);
    eula_win.document.write("<script>print();</script>");
    eula_win.document.close();

    window.event.returnValue=false;
}

