var global_invoice_2;
var global_invoice_3;

window.onload = function(){
    check_page_count();
    pageonload();
    check_shopping_cart();
    news_bar();
}

$(function(){
    var $member_rule = $('#member_rule'),
        _height = $member_rule.height(),
        _scrollHeight =  $member_rule.attr('scrollHeight'),
        _maxScrollHeight = _scrollHeight - _height - 20;
        _least = 0,
        $B1 = $('#B1').attr('disabled', _maxScrollHeight > _least);

    $('#member_rule').scroll(function(){
        var $this = $(this);
        if(_maxScrollHeight - $this.scrollTop() <= _least){
            $B1.attr('disabled', '');
        }
    });
});

$(function() {
    $('#titleimg a').lightBox();
});

function show_detail(){
    if($('div[name="shipment_detail"]').css('display') == 'block'){
        $('div[name="shipment_detail"]').css('display', 'none');
    }else{
        $('div[name="shipment_detail"]').css('display', '');
    }
}

function changeimg(xx, yy){
    $('#titleimg a').attr('href', xx);
    $('#titleimg img').attr('src', yy);
}

function pageonload(){
    $('#member_account').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_password').focus();
            return false;
        }
    });
    $('#member_password').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_password_check').focus();
            return false;
        }
    });
    $('#member_password_check').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_name').focus();
            return false;
        }
    });
    $('#member_name').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_nick').focus();
            return false;
        }
    });
    $('#member_nick').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_sex').focus();
            return false;
        }
    });
    $('#member_sex').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_birthday').focus();
            return false;
        }
    });
    $('#member_birthday').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_mobile').focus();
            return false;
        }
    });
    $('#member_mobile').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_tel').focus();
            return false;
        }
    });
    $('#member_tel').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_addr').focus();
            return false;
        }
    });
    $('#member_addr').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_mail').focus();
            return false;
        }
    });

    $('#member_name_d').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_mobile_d').focus();
            return false;
        }
    });
    $('#member_mobile_d').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_tel_d').focus();
            return false;
        }
    });
    $('#member_tel_d').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_mail_d').focus();
            return false;
        }
    });
    $('#member_mail_d').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#member_addr_d').focus();
            return false;
        }
    });
    $('#member_addr_d').bind('keypress', function(e) {
        if(e.keyCode==13){
            $('#psnote_d').focus();
            return false;
        }
    });
}

function scratch(){
    var S1 = $.trim($('#S1').val().toUpperCase());
    var S2 = $.trim($('#S2').val().toUpperCase());
    var S3 = $.trim($('#S3').val().toUpperCase());
    if(!S1.match(/^[\d\w]{4}$/)){
        alert('紅利序號第一欄的格式有誤');
        $('#S1').focus();
        return false;
    }
    if(!S2.match(/^[\d\w]{4}$/)){
        alert('紅利序號第二欄的格式有誤');
        $('#S2').focus();
        return false;
    }
    if(!S3.match(/^[\d\w]{4}$/)){
        alert('紅利序號第三欄的格式有誤');
        $('#S3').focus();
        return false;
    }

    if(!confirm('您輸入的紅利序號為「'+ S1 +'-'+ S2 +'-'+ S3 +'」確認送出嗎?')){
        return false;
    }

    $.post('/API/ScratchCard', { mode: 'chk_scratchcode', S1: S1, S2: S2, S3: S3 }, function(data){
        result = data.substr(0, 1);
        data = data.substr(2, data.length);
        if(result==0){
            alert(data);
            return false;
        }else{
            alert(data);
            location.href = '/Member/ViewProfile';
        }
    });
}

function login_check(xx){
    $.post('/API/Member', { mode: 'chk_login' }, function(data){
        if(data.substr(0, 1)==0){
            alert('請先登入會員');
            return false;
        }
        location.href = xx;
    });
}

function login(){
    var S1 = $.trim($('#S1').val());
    var S2 = $.trim($('#S2').val());
    if(!S1.match(/^[\d\w]{4,16}$/)){
        alert('會員帳號只能為英文或數字, 且長度需為4~16碼');
        $('#S1').focus();
        return false;
    }
    if(!S2.match(/^[[\d\w\-\=\+\)\(\*\&\^\%\$\#\@\!\~\[\]\{\}\;\'\:\"\,\.\/\<\>\?\\]{4,16}$/)){
        alert('會員密碼只能為英文、數字、特殊符號, 且長度需為4~16碼');
        $('#S2').focus();
        return false;
    }

    $.post('/API/Member', { mode: 'login', id: S1, pw: S2 }, function(data){
        if(data.substr(0, 1)==1){
            data = data.substr(2, data.length);
            alert(data);
            parent.close_popup();
            parent.location.reload();
        }else{
            alert(data);
        }
    });
}

function logout(){
    $.post('/API/Member', { mode: 'logout' }, function(data){
        alert('您已登出會員');
        location.href = '/';
    });
}

function open_popup(uri){
    $(document).keydown(function(e){
        if(e.keyCode==9 || e.keyCode==38 || e.keyCode==40){
            return false;
        }
    });
    $('#popupIFrame').attr('src', uri);
    $('html').css('overflow', 'hidden');
    $('html').css('outline', 'none');
    $('html').css('accessibility', 'none');
    $('#popupBackgrond').css('top', $('html').scrollTop());
    $('#popupBackgrond').css('display', '');
    $('#popupForm').css('top', $('html').scrollTop());
    $('#popupForm').css('display', '');
}

function close_popup(){
    $('html').css('overflow', 'auto');
    $('html').css('outline', '');
    $('#popupBackgrond').css('display', 'none');
    $('#popupForm').css('display', 'none');
}

function chk_act(){
    var S1 = $.trim($('#member_account').val());
    if(!S1.match(/^[\d\w]{4,16}$/)){
        alert('會員帳號只能為英文或數字, 且長度需為4~16碼');
        $('#member_account').focus();
        return false;
    }
    $.post('/API/Member', { mode: 'chk_act', query: S1 }, function(data){ alert(data); });
}

function ack_mail(){
    var id = $.trim($('#id').val());
    var pw = $.trim($('#pw').val());

    if(!id.match(/^[\d\w]{4,16}$/)){
        alert('會員帳號只能為英文或數字! 且長度需為4~16碼');
        $('#id').focus();
        return false;
    }
    if(!pw.match(/^[[\d\w\-\=\+\)\(\*\&\^\%\$\#\@\!\~\[\]\{\}\;\'\:\"\,\.\/\<\>\?\\]{4,16}$/)){
        alert('會員密碼只能為英文、數字、特殊符號, 且長度需為4~16碼');
        $('#pw').focus();
        return false;
    }
    $('#button').attr('disabled', true);
    $.post('/API/Member', { mode: 'ack_mail', id: id, pw: pw }, function(data){
        alert(data);
        $('#id').val('');
        $('#pw').val('');
        $('#button').attr('disabled', '');
    });
}

function get_pw(){
    var id = $.trim($('#id').val());
    var mail = $.trim($('#mail').val());

    if(!id.match(/^[\d\w]{4,16}$/)){
        alert('會員帳號只能為英文或數字! 且長度需為4~16碼');
        $('#id').focus();
        return false;
    }
    if(!mail.match(/^[\w_-]+(?:[.][\w_-]+)*@[\w-]+(?:[.][\w-]+)+$/)){
        alert('電子郵件欄位的格式有誤');
        $('#mail').focus();
        return false;
    }
    $('#button').attr('disabled', true);
    $.post('/API/Member', { mode: 'get_pw', id: id, mail: mail }, function(data){
        alert(data);
        $('#id').val('');
        $('#mail').val('');
        $('#button').attr('disabled', '');
    });
}

function ins_act(){
    var member_account = $.trim($('#member_account').val());
    var member_password = $.trim($('#member_password').val());
    var member_password_check = $.trim($('#member_password_check').val());
    var member_name = $.trim($('#member_name').val());
    var member_sex = $.trim($('input[id="member_sex"]:checked').val());
    var member_birthday = $.trim($('#member_birthday').val());
    var member_mobile = $.trim($('#member_mobile').val());
    var member_tel = $.trim($('#member_tel').val());
    var member_addr = $.trim($('#member_addr').val());
    var member_mail = $.trim($('#member_mail').val());

    if(!member_account.match(/^[\d\w]{4,16}$/)){
        alert('會員帳號只能為英文或數字, 且長度需為4~16碼');
        $('#member_account').focus();
        return false;
    }
    if(!member_password.match(/^[[\d\w\-\=\+\)\(\*\&\^\%\$\#\@\!\~\[\]\{\}\;\'\:\"\,\.\/\<\>\?\\]{4,16}$/)){
        alert('會員密碼只能為英文、數字、特殊符號, 且長度需為4~16碼');
        $('#member_password').focus();
        return false;
    }
    if(member_password!==member_password_check){
        alert('會員密碼與確認欄位不相符');
        $('#member_password_check').focus();
        return false;
    }
    if(member_name===''){
        alert('姓名欄位為空');
        $('#member_name').focus();
        return false;
    }
    if(member_sex===''){
        alert('請選擇性別');
        $('#member_sex').focus();
        return false;
    }
    if(member_birthday!==''){
        if(!member_birthday.match(/^[\d]{4}-[\d]{2}-[\d]{2}$/)){
            alert('生日欄位的格式有誤, 請使用 2010-01-01 格式填寫');
            $('#member_birthday').focus();
            return false;
        }
    }
    if(member_mobile!==''){
        if(!member_mobile.match(/^09[\d]{2}-[\d]{3}-[\d]{3}$/)){
            alert('手機欄位的格式有誤');
            $('#member_mobile').focus();
            return false;
        }
    }
    if(member_tel!==''){
        if(!member_tel.match(/^0[2-8][\d]{0,2}-[\d]{2,4}-[\d]{3,4}(#[\d]{1,10})?$/)){
            alert('電話欄位的格式有誤, 請使用 02-1234-5678 格式填寫, 有分機請加上#');
            $('#member_tel').focus();
            return false;
        }
    }
    if(member_mobile==='' && member_tel===''){
        alert('手機或電話欄位請至少填寫一個');
        $('#member_tel').focus();
        return false;
    }
    /*
    if(member_addr===''){
        alert('地點欄位為空');
        $('#member_addr').focus();
        return false;
    }
    */
    if(!member_mail.match(/^[\w_-]+(?:[.][\w_-]+)*@[\w-]+(?:[.][\w-]+)+$/)){
        alert('電子郵件欄位的格式有誤');
        $('#member_mail').focus();
        return false;
    }
    if(!confirm('請確認電子郵件無誤，將寄發認證信\n\n電子郵件: '+ member_mail)){
        $('#member_mail').focus();
        return false;
    }
    return true;
}

function fix_act(){
    var member_password = $.trim($('#member_password').val());
    var member_password_check = $.trim($('#member_password_check').val());
    var member_name = $.trim($('#member_name').val());
    var member_sex = $.trim($('input[id="member_sex"]:checked').val());
    var member_birthday = $.trim($('#member_birthday').val());
    var member_mobile = $.trim($('#member_mobile').val());
    var member_tel = $.trim($('#member_tel').val());
    var member_addr = $.trim($('#member_addr').val());
    var member_mail = $.trim($('#member_mail').val());

    if(member_password!==''){
        if(!member_password.match(/^[[\d\w\-\=\+\)\(\*\&\^\%\$\#\@\!\~\[\]\{\}\;\'\:\"\,\.\/\<\>\?\\]{4,16}$/)){
            alert('會員密碼只能為英文、數字、特殊符號, 且長度需為4~16碼');
            $('#member_password').focus();
            return false;
        }
    }
    if(member_password!==member_password_check){
        alert('會員密碼與確認欄位不相符');
        $('#member_password_check').focus();
        return false;
    }
    if(member_name===''){
        alert('姓名欄位為空');
        $('#member_name').focus();
        return false;
    }
    if(sex!='nocheck' && member_sex===''){
        alert('請選擇性別');
        $('#member_sex').focus();
        return false;
    }
    if(member_birthday!==''){
        if(!member_birthday.match(/^[\d]{4}-[\d]{2}-[\d]{2}$/)){
            alert('生日欄位的格式有誤, 請使用 2010-01-01 格式填寫');
            $('#member_birthday').focus();
            return false;
        }
    }
    if(member_mobile!==''){
        if(!member_mobile.match(/^09[\d]{2}-[\d]{3}-[\d]{3}$/)){
            alert('手機欄位的格式有誤');
            $('#member_mobile').focus();
            return false;
        }
    }
    if(member_tel!==''){
        if(!member_tel.match(/^0[2-8][\d]{0,2}-[\d]{2,4}-[\d]{3,4}(#[\d]{1,10})?$/)){
            alert('電話欄位的格式有誤, 請使用 02-1234-5678 格式填寫, 有分機請加上#');
            $('#member_tel').focus();
            return false;
        }
    }
    if(member_mobile==='' && member_tel===''){
        alert('手機或電話欄位請至少填寫一個');
        $('#member_tel').focus();
        return false;
    }
    /*
    if(member_addr===''){
        alert('地點欄位為空');
        $('#member_addr').focus();
        return false;
    }
    */
    if(!member_mail.match(/^[\w_-]+(?:[.][\w_-]+)*@[\w-]+(?:[.][\w-]+)+$/)){
        alert('電子郵件欄位的格式有誤');
        $('#member_mail').focus();
        return false;
    }
    return true;
}

function ord_chk(){
    var member_name = $.trim($('#member_name_d').val());
    var member_mobile = $.trim($('#member_mobile_d').val());
    var member_tel = $.trim($('#member_tel_d').val());
    var member_mail = $.trim($('#member_mail_d').val());
    var member_addr = $.trim($('#member_addr_d').val());
    var invoice_type = $.trim($('input[id="invoice_type"]:checked').val());
    var invoice_title = $.trim($('#invoice_title').val());
    var invoice_number = $.trim($('#invoice_number').val());

    var member_name_s = $('#member_name_s').html();
    var member_mobile_s = $('#member_mobile_s').html();
    var member_tel_s = $('#member_tel_s').html();
    var member_mail_s = $('#member_mail_s').html();
    var member_addr_s = $('#member_addr_s').html();

    if(member_name_s===''){
        alert('訂購者姓名為空, 請先回「會員資料」修改');
        return false;
    }
    if(member_mobile_s==='' && member_tel_s===''){
        alert('訂購者手機或電話欄位請至少填寫一個, 請先回「會員資料」修改');
        return false;
    }
    if(member_mail_s===''){
        alert('訂購者電子郵件為空, 請先回「會員資料」修改');
        return false;
    }
    if(member_addr_s===''){
        alert('訂購者地址為空, 請先回「會員資料」修改');
        return false;
    }

    if(member_name===''){
        alert('收件者姓名欄位為空');
        $('#member_name_d').focus();
        return false;
    }
    if(member_mobile!==''){
        if(!member_mobile.match(/^09[\d]{2}-[\d]{3}-[\d]{3}$/)){
            alert('收件者手機欄位的格式有誤');
            $('#member_mobile_d').focus();
            return false;
        }
    }
    if(member_tel!==''){
        if(!member_tel.match(/^0[2-8][\d]{0,2}-[\d]{2,4}-[\d]{3,4}(#[\d]{1,10})?$/)){
            alert('收件者電話欄位的格式有誤, 請使用 02-1234-5678 格式填寫, 有分機請加上#');
            $('#member_tel_d').focus();
            return false;
        }
    }
    if(member_mobile==='' && member_tel===''){
        alert('收件者手機或電話欄位請至少填寫一個');
        $('#member_tel').focus();
        return false;
    }
    if(!member_mail.match(/^[\w_-]+(?:[.][\w_-]+)*@[\w-]+(?:[.][\w-]+)+$/)){
        alert('收件者電子郵件欄位的格式有誤');
        $('#member_mail_d').focus();
        return false;
    }
    if(member_addr===''){
        alert('收件者地址欄位為空');
        $('#member_addr_d').focus();
        return false;
    }
    if(invoice_type===''){
        alert('請選擇發票種類');
        $('#invoice_type').focus();
        return false;
    }
    if(invoice_title===''){
        if(invoice_type == 2){
            alert('買受人欄位為空');
        }else{
            alert('公司名稱欄位為空');
        }
        $('#invoice_title').focus();
        return false;
    }
    if(invoice_type == 3 && ! invoice_number.match(/^\d{8}$/)){
        alert('統一編號欄位格式有誤');
        $('#invoice_number').focus();
        return false;
    }
    return true;
}

function ord_sed(){
    $('#button').attr('disabled', true);
    return true;
}

function invoice_check(){
    var invoice_type = $.trim($('input[id="invoice_type"]:checked').val());

    if(invoice_type == 2){
        $('#buyer').html('<em>*</em>買受人');
        $('#invoice_title_line').css('display', '');
        $('#invoice_number_line').css('display', 'none');
        $('#cpyibuton').css('display', '');
        global_invoice_2 = $('#invoice_title').val();
        $('#invoice_title').val(global_invoice_3);
    }else{
        $('#buyer').html('<em>*</em>公司名稱');
        $('#invoice_title_line').css('display', '');
        $('#invoice_number_line').css('display', '');
        $('#cpyibuton').css('display', 'none');
        global_invoice_3 = $('#invoice_title').val();
        $('#invoice_title').val(global_invoice_2);
    }
}

function mail_fix_check(){
    if($('#member_mail').val() != $('#old_mail').html()){
        $('#alert_str').css('display', '');
    }else{
        $('#alert_str').css('display', 'none');
    }
}

function feedback(){
    var member_name = $.trim($('#member_name').val());
    var member_mobile = $.trim($('#member_mobile').val());
    var member_tel = $.trim($('#member_tel').val());
    var member_mail = $.trim($('#member_mail').val());
    var fb_content = $.trim($('#fb_content').val());

    if(member_name===''){
        alert('姓名欄位為空');
        $('#member_name').focus();
        return false;
    }
    if(member_mobile!==''){
        if(!member_mobile.match(/^09[\d]{2}-[\d]{3}-[\d]{3}$/)){
            alert('手機欄位的格式有誤');
            $('#member_mobile').focus();
            return false;
        }
    }
    if(member_tel!==''){
        if(!member_tel.match(/^0[2-8][\d]{0,2}-[\d]{2,4}-[\d]{3,4}(#[\d]{1,10})?$/)){
            alert('電話欄位的格式有誤, 請使用 02-1234-5678 格式填寫, 有分機請加上#');
            $('#member_tel').focus();
            return false;
        }
    }
    if(!member_mail.match(/^[\w_-]+(?:[.][\w_-]+)*@[\w-]+(?:[.][\w-]+)+$/)){
        alert('電子郵件欄位的格式有誤');
        $('#member_mail').focus();
        return false;
    }
    if(fb_content===''){
        alert('客訴內容欄位為空');
        $('#fb_content').focus();
        return false;
    }
    return true;
}

function guestbook(){
    var gb_name = $.trim($('#gb_name').val());
    var gb_status = $.trim($('input[id="gb_status"]:checked').val());
    var gb_content = $.trim($('#gb_content').val());

    if(gb_name===''){
        alert('暱稱欄位為空');
        $('#gb_name').focus();
        return false;
    }
    if(gb_status===''){
        alert('留言狀態欄位為空');
        $('#gb_status').focus();
        return false;
    }
    if(gb_content===''){
        alert('留言內容欄位為空');
        $('#gb_content').focus();
        return false;
    }
    return true;
}

function gb_foradmin(){
    $.post('/API/Member', { mode: 'chk_login' }, function(data){
        if(data.substr(0, 1)==0){
            alert('「私密留言」功能需先登入會員');

            $('input[id^="gb_status"]').each(function(){
                if($(this).val()=='Normal'){
                    $(this).attr('checked', true);
                }
            });
            return false;
        }
    });
}

function shopping(type, item, quantity){
    var product_price       = 0;
    var product_quantity    = parseInt(quantity);
    var shopping_cart       = $.JSONCookie('ShoppingCart');
    var bonus_cart          = $.JSONCookie('BonusCart');
    var shopping_alert      = 0;

    // 檢查購物車商品
    $.each(shopping_cart, function(key, value){
        var product_id;
        if(key.match(/^(\d+)\_(quantity|price)$/)){
            product_id  = RegExp.$1;
        }

        // 若選購蛋糕系列商品時清單內已有非蛋糕商品，則跳出錯誤訊息！
        if((item == 20 || item == 21) && (product_id != 20 && product_id != 21)){
            shopping_alert = 1;
        // 若選購火腿商品時清單內已有非火腿系列商品，則跳出錯誤訊息！
        }else if((item == 28 || item == 29 || item == 30 || item == 31) && (product_id != 28 && product_id != 29 && product_id != 30 && product_id != 31)){
            shopping_alert = 1;
        // 若選購醬油商品時清單內已有蛋糕、火腿系列商品，則跳出錯誤訊息！
        }else if((item != 20 && item != 21 && item != 28 && item != 29 && item != 30 && item != 31) && (product_id == 20 || product_id == 21 || product_id == 28 ||product_id == 29 || product_id == 30 || product_id == 31)){
            shopping_alert = 1;
        }
    });

    // 檢查紅利商品
    $.each(bonus_cart, function(key, value){
        var product_id;
        if(key.match(/^(\d+)\_(quantity|price)$/)){
            product_id  = RegExp.$1;
        }

        // 若選購蛋糕系列商品時清單內已有非蛋糕商品，則跳出錯誤訊息！
        if((item == 20 || item == 21) && (product_id != 20 && product_id != 21)){
            shopping_alert = 1;
        // 若選購火腿商品時清單內已有非火腿系列商品，則跳出錯誤訊息！
        }else if((item == 28 || item == 29 || item == 30 || item == 31) && (product_id != 28 && product_id != 29 && product_id != 30 && product_id != 31)){
            shopping_alert = 1;
        // 若選購醬油商品時清單內已有蛋糕、火腿系列商品，則跳出錯誤訊息！
        }else if((item != 20 && item != 21 && item != 28 && item != 29 && item != 30 && item != 31) && (product_id == 20 || product_id == 21 || product_id == 28 ||product_id == 29 || product_id == 30 || product_id == 31)){
            shopping_alert = 1;
        }
    });
    if(shopping_alert == 1){
        alert('"蛋糕系列商品"、"豆油伯系列商品"、"阿德師洋火腿" 請分開訂單訂購！');
        return;
    }

    $.post('/API/Shopping', { mode: 'shopping', item: item }, function(data){
        if(data.match(/^(1|0)\ (.*)$/)){
            if(RegExp.$1 == 1){
                // 取得價錢及紅利
                product_price = RegExp.$2;

                if(type=='cash'){
                    // 更新 購物車 Cookie
                    if(shopping_cart[item + '_quantity'] === undefined){
                        shopping_cart[item + '_quantity'] = product_quantity;
                    }else{
                        shopping_cart[item + '_quantity'] = parseInt(shopping_cart[item + '_quantity']) + product_quantity;
                    }
                    shopping_cart[item + '_price']     = product_price;

                    $.JSONCookie('ShoppingCart', shopping_cart, {path: '/'});
                }else{
                    // 更新 紅利商品 Cookie
                    if(bonus_cart[item + '_quantity'] === undefined){
                        bonus_cart[item + '_quantity'] = product_quantity;
                    }else{
                        bonus_cart[item + '_quantity'] = parseInt(bonus_cart[item + '_quantity']) + product_quantity;
                    }
                    bonus_cart[item + '_price']     = product_price;

                    $.JSONCookie('BonusCart', bonus_cart, {path: '/'});
                }

                // 重整購物車
                check_shopping_cart();

                alert('您選購的商品已成功加入購物車');
            }else{
                alert(RegExp.$2);
            }
        }else{
            alert('選擇商品錯誤或不存在, 請重新選購');
        }
    });
}

/**
* Function : pre()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function pre(arr, level){
    var dumped_text = "";
    if(!level) level = 0;

    //The padding given at the beginning of the line.
    var level_padding = "";
    for(var j=0;j<level+1;j++) level_padding += "    ";

    //Array/Hashes/Objects
    if(typeof(arr) == 'object'){
        for(var item in arr){
            var value = arr[item];

            //If it is an array
            if(typeof(value) == 'object'){
                dumped_text += level_padding + "'" + item + "' ...\n";
                dumped_text += dump(value,level+1);
            }else{
                dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
            }
        }

    //Stings/Chars/Numbers etc.
    }else{
        dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
    }
    alert(dumped_text);
}

function check_shopping_cart(){
    var items_oil               = 0;
    var items_cok               = 0;
    var items_ham               = 0;
    var total_oil               = 0;
    var total_cok               = 0;
    var total_ham               = 0;
    var special_price           = 0;
    var shopping_cart           = $.JSONCookie('ShoppingCart');

    //alert($.cookie('ShoppingCart'));

    $.each(shopping_cart, function(key, value) {
        if(key.match(/^(\d+)\_(quantity|price)$/)){
            var product_id  = RegExp.$1;
            var cookie_item = RegExp.$2;

            if(cookie_item == 'quantity' && shopping_cart[product_id+'_quantity'] > 0){
                if(product_id == 20 || product_id == 21){
                    items_cok += parseInt(shopping_cart[product_id+'_quantity']);
                    total_cok += parseInt(shopping_cart[product_id+'_quantity']) * parseInt(shopping_cart[product_id+'_price']);
                }else if(product_id == 28 || product_id == 29 || product_id == 30 || product_id == 31){
                    items_ham += parseInt(shopping_cart[product_id+'_quantity']);
                    total_ham += parseInt(shopping_cart[product_id+'_quantity']) * parseInt(shopping_cart[product_id+'_price']);
                }else{
                    items_oil += parseInt(shopping_cart[product_id+'_quantity']);
                    total_oil += parseInt(shopping_cart[product_id+'_quantity']) * parseInt(shopping_cart[product_id+'_price']);
                }
            }
        }
    });

    // 蛋糕運費計算
    if(total_cok > 0 && total_cok < 1500){
        total_cok += 200 * Math.ceil(items_cok/2);
    }

    // 火腿運費計算
    if(total_ham > 0 && total_ham < 1500){
        total_ham += 200 * items_ham;
    }

    // 醬油運費計算
    if(total_oil > 0 && total_oil < 1200){
        total_oil += 100;
    }

    // 更新購物車資料
    $('#shopping_cart_items').html(items_oil + items_cok + items_ham);
    $('#shopping_cart_total').html(total_oil + total_cok + total_ham);
}

function clean_shopping_cart(){
    if(confirm('您確定要清空購物車嗎?\n\n按下確定後購物車內容將全部清空！')){
        $.cookie('ShoppingCart', '', { expires: -1, path: '/' });
        $.cookie('BonusCart', '', { expires: -1, path: '/' });
        check_shopping_cart();
        clean_order_list();
    }
}

function check_order_list(){
    // 變數宣告
    var cash_price          = new Array();
    var cash_quantity       = new Array();
    var bonus_price         = new Array();
    var bonus_quantity      = new Array();
    var shopping_cart       = new Object();
    var bonus_cart          = new Object();
    var oil_total           = 0;
    var cok_items           = 0;
    var cok_total           = 0;
    var ham_items           = 0;
    var ham_total           = 0;
    var special_price       = 0;
    var special_cok_price   = 0;
    var special_ham_price   = 0;
    var total_bonus         = parseInt($('#total_bonus').html());
    var use_bonus           = 0;
    var order_button_close  = 0;

    // =============================
    // 購物車商品
    // =============================
    // 取出單價
    $('td[id^="cash_price"]').each(function(){
        cash_price.push($(this).html());
    });

    // 取出數量
    var i = 0;
    $('input[id^="cash_quantity"]').each(function(){
        if($(this).val().match(/^\d+$/)){
            cash_quantity.push($(this).val());
        }else{
            cash_quantity.push(0);
            $(this).val(0);
        }
        i++;
    });

    // 寫入總價
    var i = 0;
    $('td[id^="cash_total"]').each(function(){
        var cash_total = cash_price[i]*parseInt(cash_quantity[i]);
        oil_total += cash_total;
        $(this).html(cash_total);
        i++;
    });

    // 計算蛋糕及火腿總價
    var i = 0;
    $('tr[id^="cash_data"]').each(function(){
        if($(this).attr('index') == 20 || $(this).attr('index') == 21){
            var cash_total = cash_price[i]*parseInt(cash_quantity[i]);
            cok_items += parseInt(cash_quantity[i]);
            cok_total += cash_total;
            oil_total -= cash_total;
        }else if($(this).attr('index') == 28 || $(this).attr('index') == 29 || $(this).attr('index') == 30 || $(this).attr('index') == 31){
            var cash_total = cash_price[i]*parseInt(cash_quantity[i]);
            ham_items += parseInt(cash_quantity[i]);
            ham_total += cash_total;
            oil_total -= cash_total;
        }
        i++;
    });

    // =============================
    // 紅利商品
    // =============================
    // 取出單價
    $('span[id^="bonus_price"]').each(function(){
        bonus_price.push($(this).html());
    });

    // 取出數量
    var i = 0;
    $('input[id^="bonus_quantity"]').each(function(){
        if($(this).val().match(/^\d+$/)){
            bonus_quantity.push($(this).val());
        }else{
            bonus_quantity.push(0);
            $(this).val(0);
        }
        i++;
    });

    // 寫入總價
    var i = 0;
    $('td[id^="bonus_total"]').each(function(){
        var bonus_total = bonus_price[i]*parseInt(bonus_quantity[i]);
        $(this).html(bonus_total+' 點');
        //計算使用紅利點數
        use_bonus += bonus_total;
        i++;
    });

    // =============================
    // 運費計算
    // =============================
    // 計算蛋糕運費
    if(cok_total > 0 && cok_total < 1500){
        special_cok_price = 200;
        cok_total += special_cok_price * Math.ceil(cok_items/2);
        $('#special_cok_price').css('display', '');
        $('#special_cok_price_string').html('低溫宅配（單筆運費最高 2 盒蛋糕）');
        $('#special_cok_price_cost').html(special_cok_price);
        $('#special_cok_price_quantity').html(Math.ceil(cok_items/2));
        $('#special_cok_price_total').html(special_cok_price * Math.ceil(cok_items/2));
    }else{
        $('#special_cok_price').css('display', 'none');
    }

    // 計算火腿運費
    if(ham_total > 0 && ham_total < 1500){
        special_ham_price = 200;
        ham_total += special_ham_price * ham_items;
        $('#special_ham_price').css('display', '');
        $('#special_ham_price_string').html('低溫宅配');
        $('#special_ham_price_cost').html(special_ham_price);
        $('#special_ham_price_quantity').html(ham_items);
        $('#special_ham_price_total').html(special_ham_price * ham_items);
    }else{
        $('#special_ham_price').css('display', 'none');
    }

    // 計算醬油折扣
    if(oil_total > 0 && oil_total < 1200){
        special_price = 100;
        oil_total += special_price;
        $('#special_price').css('display', '');
        $('#special_price_string').html('運費（購物滿 1,200 元可享免運費）');
        $('#special_price_cost').html(special_price);
        $('#special_price_total').html(special_price);
    }else if(oil_total >= 200000){
        $('#special_price').css('display', 'none');
        order_button_close = 1;
        $('#order_button').attr('disabled', 1);
        $('#order_button').attr('title', '購買金額超過宅配代收付上限, 請分筆訂購！');
        alert('購買金額超過宅配代收付上限, 請分筆訂購！');
    }else{
        $('#special_price').css('display', 'none');
    }

    // 處理合計計算
    if((oil_total + cok_total + ham_total) == 0){
        $('#special_cok_price').css('display', 'none');
        $('#special_ham_price').css('display', 'none');
        $('#special_price').css('display', 'none');
        if(order_button_close == 0){
            order_button_close = 1;
            $('#order_button').attr('disabled', 1);
            $('#order_button').attr('title', '您尚未選購商品！');
        }
    }else{
        // 處理使用紅利點數判斷
        if(use_bonus > total_bonus){
            if(order_button_close == 0){
                order_button_close = 1;
                $('#order_button').attr('disabled', 1);
                $('#order_button').attr('title', '您已使用超過所累積紅利點數，請重新調整您的購買清單！');
                alert('您已使用超過所累積紅利點數，請重新調整您的購買清單！');
            }
        }
    }
    $('#use_bonus').html(use_bonus);
    $('#sum_total').html(oil_total + cok_total + ham_total);

    if(order_button_close == 0){
        $('#order_button').attr('disabled', 0);
        $('#order_button').attr('title', '');
    }

    // =============================
    // 寫入 Cookie
    // =============================
    // 購物車商品
    i = 0;
    $('tr[id^="cash_data"]').each(function(){
        var cash_id = $(this).attr('index');

        if(parseInt(cash_quantity[i]) > 0){
            shopping_cart[cash_id + '_quantity'] = parseInt(cash_quantity[i]);
            shopping_cart[cash_id + '_price']    = cash_price[i];
        }
        i++;
    });

    // 紅利商品
    i = 0;
    $('tr[id^="bonus_data"]').each(function(){
        var bonus_id = $(this).attr('index');

        if(parseInt(bonus_quantity[i]) > 0){
            bonus_cart[bonus_id + '_quantity'] = parseInt(bonus_quantity[i]);
            bonus_cart[bonus_id + '_price']    = bonus_price[i];
        }
        i++;
    });
    $.JSONCookie('ShoppingCart', shopping_cart, {path: '/'});
    $.JSONCookie('BonusCart', bonus_cart, {path: '/'});

    // 重整購物車
    check_shopping_cart();
}

function clean_order_list(){

    // 清空數量
    $('input[id^="cash_quantity"]').each(function(){
        $(this).val(0);
    });
    // 清空數量
    $('td[id^="cash_quantity"]').each(function(){
        $(this).html(0);
    });
    // 清空總價
    $('td[id^="cash_total"]').each(function(){
        $(this).html(0);
    });
    // 清空數量
    $('input[id^="bonus_quantity"]').each(function(){
        $(this).val(0);
    });
    // 清空數量
    $('td[id^="bonus_quantity"]').each(function(){
        $(this).html(0);
    });
    // 清空總價
    $('td[id^="bonus_total"]').each(function(){
        $(this).html(0);
    });
    $('#sum_total').html(0);
    $('#special_price').css('display', 'none');
    $('#special_cok_price').css('display', 'none');
    $('#special_ham_price').css('display', 'none');
    $('#order_button').attr('disabled', 1);
    $('#order_button').attr('title', '您尚未選購商品！');
    $.cookie('ShoppingCart', '', { expires: -1, path: '/' });
}

function float(value,num){
    return parseInt(value * Math.pow(10,num) + 0.5) / Math.pow(10,num);
}

function news_bar(){
    var news            = Object();
    var link_base       = '/News/';
    var time_counter    = 0;
    var speed_line      = 5000;
    var speed_char      = 100;

    // 取得最新消息
    var data = $.ajax({
        type:   "POST",
        url:    "/API/News",
        data:   "mode=getnews&news_cat=all&limit=10",
        async: false
    }).responseText;

    var json_decode = jQuery.parseJSON(data);

    // 執行跑馬燈
    if(json_decode.length > 0){
        for(var x = 0; x<10; x++) {
            $.each(json_decode, function(key, value) {
                var news_date = '';
                if(value['display_date'] === null){
                    news_date = value['news_date'];
                }else{
                    news_date = value['display_date'];
                }
                var title_str = news_date+" "+value['news_title'];
                var response = setTimeout("news_bar_DisplayMsg('"+title_str+"', '"+(link_base+value['news_id'])+"', "+speed_char+")", time_counter);
                time_counter += title_str.length*speed_char+speed_line;
            });
        }
    }
}

function news_bar_DisplayMsg(title, link, speed_char){
    var title_str = '';
    var time_counter = 0;
    $('#news_display').attr('href', link);

    for(var x = 0; x<title.length; x++) {
        title_str += title.charAt(x);
        setTimeout("$('#news_display').html('"+title_str+"')", time_counter);
        time_counter += speed_char;
    }
    return time_counter;
}

function cpy_data(type){
    var member_name = $.trim($('#member_name_s').html());
    var member_mobile = $.trim($('#member_mobile_s').html());
    var member_tel = $.trim($('#member_tel_s').html());
    var member_mail = $.trim($('#member_mail_s').html());
    var member_addr = $.trim($('#member_addr_s').html());

    if(type == 'member'){
        $('#member_name_d').attr('value', func_htmlspecialchars_decode(member_name));
        $('#member_mobile_d').attr('value', member_mobile);
        $('#member_tel_d').attr('value', member_tel);
        $('#member_mail_d').attr('value', member_mail);
        $('#member_addr_d').attr('value', func_htmlspecialchars_decode(member_addr));
    }

    if(type == 'invoice'){
        $('#invoice_title').attr('value', func_htmlspecialchars_decode(member_name));
    }
}

function htmlspecialchars(string){
    return $('<span>').text(string).html();
}
function func_htmlspecialchars(string, quote_style){
    if(quote_style === undefined){
        quote_style = 'ENT_NOQUOTES';
    }
    string = string.toString();
    string = string.replace(/&/g, '&amp;');
    string = string.replace(/</g, '&lt;');
    string = string.replace(/>/g, '&gt;');
    if(quote_style == 'ENT_QUOTES'){
        string = string.replace(/"/g, '&quot;');
        string = string.replace(/\'/g, '&#039;');
    }else if(quote_style != 'ENT_NOQUOTES'){
        string = string.replace(/"/g, '&quot;');
    }
    return string;
}

function func_htmlspecialchars_decode(string, quote_style){
    string = string.toString();
    string = string.replace(/&amp;/g, '&');
    string = string.replace(/&lt;/g, '<');
    string = string.replace(/&gt;/g, '>');
    if(quote_style == 'ENT_QUOTES'){
        string = string.replace(/&quot;/g, '"');
        string = string.replace(/&#039;/g, '\'');
    }else if(quote_style != 'ENT_NOQUOTES'){
        string = string.replace(/&quot;/g, '"');
    }
    return string;
}

function check_page_count(){
    var width_total = 0;
    var page_width = 436;

    if($('li[id^="page_b"]').length > 0){
        $('li[id^="page_b"]').each(function(){
            width_total += $(this).width();
        });
    }
    if($('li[id^="page_a"]').length > 0){
        $('li[id^="page_a"]').each(function(){
            width_total += $(this).width();
        });
    }
    if(width_total > 0){
        $('#page').css('margin-left',((page_width-width_total)/2)+'px');
    }
}

function float_refresh(){
    var screenHight     = 0;
    var scrollTop       = document.documentElement.scrollTop + document.body.scrollTop;
    var item            = document.getElementById('shopping_cart_view').style;
    var itemHight       = 88;
    var body_height     = document.body.clientHeight;

    if(navigator.appName!='Netscape'){
        screenHight = document.documentElement.clientHeight;
    }else{
        screenHight = window.innerHeight;
    }
    if(scrollTop + screenHight >= body_height){
        item.top = body_height + 'px';
    }else{
        item.top = (scrollTop + screenHight - itemHight) + 'px';
    }
}
if ($.browser.msie && $.browser.version == "6.0") {
    window.onscroll = float_refresh;
}
