﻿var errCount = 0;
jQuery.createXMLDocument = function(string) {
    var browserName = navigator.appName;
    var doc;
    if (browserName == 'Microsoft Internet Explorer') {
        doc = new ActiveXObject('Microsoft.XMLDOM');
        doc.async = 'false'
        doc.loadXML(string);
    } else {
        doc = (new DOMParser()).parseFromString(string, 'text/xml');
    }
    return doc;
}

$(document).ready(function() {
    $.each($('div.btn'), function() {
        $(this).find("span.ui-icon").css("float", "left");
        $(this).removeClass('btn');
        $(this).addClass('ui-state-default ui-corner-all');
        $(this).hover(
            function() { $(this).addClass('ui-state-hover'); },
            function() { $(this).removeClass('ui-state-hover'); }
        );
    });

    $.each($('button.btn'), function() {
        $(this).find("span.ui-icon").css("float", "left");
        $(this).removeClass('btn');
        $(this).addClass('ui-state-default ui-corner-all');
        $(this).hover(
            function() { $(this).addClass('ui-state-hover'); },
            function() { $(this).removeClass('ui-state-hover'); }
        );
    });
});

function ShowAlertDialog(title, msg, cssClass, afterUrl) {
    setTimeout("ShowAlertDialog1('" + title + "','" + msg + "','" + cssClass + "','" + afterUrl + "');", 1);
}

function ShowAlertDialog1(title, msg, cssClass, afterUrl) {
    $("#msgDialog").dialog('destroy');
    $("#msgDialog").attr("title", title);
    $("#dialogContent").html(msg);
    $("#msgDialog").dialog({
        bgiframe: true,
        modal: true,
        resizable: false,
        dialogClass: cssClass,
        buttons: {
            "確定": function() {
                $(this).dialog('close');
                if (afterUrl != "")
                    window.location = afterUrl;
            }
        },
        close: function(event, ui) {
            if (afterUrl != "")
                window.location = afterUrl;
        }

    });
}

function ErrHandling() {
    errCount++;
    if (errCount > 3)
        ShowAlertDialog("網路存取異常", "因網路異常造成網頁存取錯誤，請稍後重試。", "ui-state-error", "");
}

//設定版位
function SetShowCase(blockID, caseID, rootCate, className, showStyle, showTime, showGoodsName, showPrice, imgStyle, imgSize, imgWidth, imgHeight) {
    $.ajax({
        async: false,
        type: "POST",
        url: "SrvProxyPage.aspx",
        data: "SrvName=GetShowCase&argCaseID=" + caseID + "&argRootCat=" + rootCate,
        success: function(xml) {
            errCount = 0;
            ParseShowCaseXML(xml, blockID, className, showStyle, showTime, showGoodsName, showPrice, imgStyle, imgSize, imgWidth, imgHeight);
        },
        error: function() {
            if (ErrHandling() <= 3)
                SetShowCase(blockID, caseID, rootCate, className, showStyle, showTime, showGoodsName, showPrice, imgStyle, imgSize, imgWidth, imgHeight);
        }
    });
}

//解析版位XML
function ParseShowCaseXML(xml, blockID, className, showStyle, showTime, showGoodsName, showPrice, imgStyle, imgSize, imgWidth, imgHeight) {
    var html = "";
    var showType = $(xml).find("SHOWTYPE").text();
    switch (showType) {
        case "1":
            //廣告
            $(xml).find("ADLIST").each(function() {
                if (html == "")
                    $("#" + blockID).html(html);
                $("#" + blockID).show();
                var $adList = $(this);
                var adType = $adList.find("ADTYPE").text();
                var adTitle = $adList.find("TITLE").text();
                var adDesc = $adList.find("DESC").text();
                var subTitle = $adList.find("SUBTITLE1").text();
                var imgDefault = $adList.find("DEFAULTIMG").text();
                var imgOnMouse = $adList.find("ONMOUSEIMG").text();
                var linkURL = $adList.find("LINKURL").text();
                var linkTarget = ($adList.find("TARGET").text() == "N") ? "_blank" : "_self";

                switch (adType) {
                    case "F":
                        //Flash
                        html = "<script type='text/javascript'>";
                        html += "AC_FL_RunContent( 'codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0','width','" + imgWidth + "','height','" + imgHeight + "','src','http://benefit.ilohas24.com.tw/Backend/AdsImg/" + imgDefault + "','quality','high','pluginspage','http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash','movie','http://benefit.ilohas24.com.tw/Backend/AdsImg/" + imgDefault + "' );";
                        html += "</script>";
                        html += "<noscript>";
                        html = "<div style='" + showStyle + "'>";
                        html += "<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0' width='" + imgWidth + "' height='" + imgHeight + "'>";
                        html += "<param name='movie' value='http://benefit.ilohas24.com.tw/Backend/AdsImg/" + imgDefault + "' />";
                        html += "<param name='quality' value='high' />";
                        html += "<embed src='http://benefit.ilohas24.com.tw/Backend/AdsImg/" + imgDefault + "' quality='high' pluginspage='http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash' type='application/x-shockwave-flash' width='" + imgWidth + "' height='" + imgHeight + "'></embed>";
                        html += "</object>";
                        html += "</div>";
                        html += "</noscript>";
                        break;
                    case "T":
                        //純文字
                        html = "<div style='" + showStyle + "'>";
                        html += "<a href='" + linkURL + "' target='" + linkTarget + "'>" + adTitle + "</a>";
                        html += "</div>";
                    case "V":
                        //Flv
                        break;
                    default:
                        html = "<div style='" + showStyle + "'>";
                        html += "<a href='" + linkURL + "' target='" + linkTarget + "'><img src='" + imgDefault + "' style='" + imgStyle + "' border='0' alt='" + adTitle + "' width='" + imgWidth + "' height='" + imgHeight + "' /></a>";
                        if (showGoodsName) {
                            html += "<div style='text-align:center;font-size:19px;padding-top:4px;height:32px;font-weight:bold;color:#333333;overflow:hidden;word-break:break-all;'>" + adTitle + "</div>";
                            html += "<div style='text-align:center;font-size:15px;padding-top:4px;height:18px;font-weight:bold;color:#ee4875;overflow:hidden;word-break:break-all;'>" + subTitle + "</div>";
                            html += "<div style='padding-top:4px;height:32px;overflow:hidden;word-break:break-all;'><a href='" + linkURL + "' target='" + linkTarget + "'>" + adDesc + "</a></div>";
                        }
                        html += "</div>";
                        break;
                }

                $("#" + blockID).append(html);
            });

            break;
        case "2":
            //商家
            break;
        case "3":
            //商品
            $(xml).find("GOODS_INF").each(function() {
                $("#" + blockID).show();
                var $goodsList = $(this);
                var goodsID = $goodsList.find("GOODSID").text();
                var goodsName = $goodsList.find("GOODSNAME").text();
                var subTitle = $goodsList.find("SUBTITLE1").text();
                var sellingPrice = $goodsList.find("SELLINGPRICE").text();
                var wsid = $goodsList.find("WSID").text();
                var dtStart = $goodsList.find("PUBDTSTART").text();
                var dtEnd = $goodsList.find("PUBDTEND").text();

                html = "<div style='" + showStyle + "' class='" + className + "'>";
                html += "<div>";
                html += "<a href='Goods.aspx?gid=" + goodsID + "&wsid=" + wsid + "'><img src='http://benefit.ilohas24.com.tw/Backend/ImgGoods.aspx?no=1&gid=" + goodsID + "&size=" + imgSize + "' style='" + imgStyle + "' class='pic' border='0' alt='" + goodsName + "' width='" + imgWidth + "' height='" + imgHeight + "' /></a>";
                html += "</div>";
                if (showTime) {
                    html += "<div style='font-size:13px; font-family:Arial;font-weight:bold;padding-top:6px;'>";
                    html += dtStart + " ~ " + dtEnd;
                    html += "</div>";
                }
                if (showGoodsName) {
                    html += "<div style='height:1.4em;overflow:hidden;word-break:break-all;'>";
                    html += "<h5 class='red'>" + subTitle + "</h5>";
                    html += "</div>";
                    html += "<div style='height:2.8em;overflow:hidden;word-break:break-all;'>";
                    html += "<a href='Goods.aspx?gid=" + goodsID + "&wsid=" + wsid + "'>" + goodsName + "</a>";
                    html += "</div>";
                }
                if (showPrice) {
                    if (sellingPrice != "-")
                        html += "<div>福利價:<span class='cnt'>$" + DollarFormat(sellingPrice) + "</span></div>";
                }
                html += "</div>";
                $("#" + blockID + " .block").append(html);
            });
            break;
    }
}

//設定分類
function SetCategory(blockID, level1, level2) {
    $.ajax({
        async: false,
        type: "POST",
        url: "SrvProxyPage.aspx",
        data: "SrvName=GetCategory&argLevel1=" + level1 + "&argLevel2=" + level2,
        timeout: 3000,
        success: function(xml) {
            errCount = 0;
            ParseCategoryXML(xml, blockID);
        },
        error: function() {
            if (ErrHandling() <= 3)
                SetCategory(blockID, level1, level2);
        }
    });
}

//解析分類XML
function ParseCategoryXML(xml, blockID) {
    if ($(xml).find("RTNCODE").text() == "000") {
        var imgCount = 8;
        var i = 0;
        $(xml).find("LEVEL1").each(function() {
            $("#" + blockID).show();
            i++;
            var imgNo = (i % imgCount);
            if (imgNo == 0) imgNo = imgCount;

            var $lv1List = $(this);
            var lv1ID = $lv1List.find("LEVELID")[0].childNodes[0].nodeValue;
            var lv1Desc = $lv1List.find("LEVELDESC")[0].childNodes[0].nodeValue

            //分類目錄第一層
            html = "<div id='" + lv1ID + "' class='menu_lv1' onclick='DisplayCategory(1,\"" + lv1ID + "\",\"" + lv1Desc + "\")'>";
            html += "<div style='float:left;'><img src='App_Themes/Theme1/Images/pt" + imgNo + ".gif' border='0'></div><div style='float:left;margin-top:10px;'>" + lv1Desc + "</div><div class='clear'></div>";
            html += "</div>";

            //分類目錄第二層
            html += "<div class='menu_lv2'>";
            $lv1List.find("LEVEL2").each(function() {
                var $lv2List = $(this);
                var lv2ID = $lv2List.find("LEVELID")[0].childNodes[0].nodeValue;
                var lv2Desc = $lv2List.find("LEVELDESC")[0].childNodes[0].nodeValue;
                html += "<div id='" + lv2ID + "'><a href='javascript:DisplayCategory(2,\"" + lv2ID + "\",\"" + lv1Desc + "_" + lv2Desc + "\");'>" + lv2Desc + "</a></div>";

                //分類目錄第三層
                html += "<div class='menu_lv3'>";
                $lv2List.find("LEVEL3").each(function() {
                    var $lv3List = $(this);
                    var lv3ID = $lv3List.find("LEVELID")[0].childNodes[0].nodeValue;
                    var lv3Desc = $lv3List.find("LEVELDESC")[0].childNodes[0].nodeValue;
                    var url = encodeURI("GoodsList.aspx?CategoryId=" + lv3ID + "&Level=3&SearchTitle=" + lv1Desc + "_" + lv2Desc + "_" + lv3Desc);
                    html += "<div id='" + lv3ID + "'><li><a href='" + url + "'>" + lv3Desc + "</a></li></div>";
                });
                html += "</div>";
            });
            html += "</div>";

            $("#" + blockID).append(html);
        });

        //團購分類
        i++;
        html = "<div class='menu_lv1' onclick='javascript:window.location=\"GBCate.aspx\"'>";
        html += "<div style='float:left;'><img src='App_Themes/Theme1/Images/pt" + (((i % imgCount) == 0) ? imgCount : (i % imgCount)) + ".gif' border='0'></div><div style='float:left;margin-top:10px;'>團購專區</div><div class='clear'></div>";
        html += "</div>";

        $("#" + blockID).append(html);
    }
}

//顯示分類
function DisplayCategory(selfLevel, cid, cdesc) {
    window.location =  encodeURI("GoodsList.aspx?CategoryId=" + cid + "&Level=" + selfLevel + "&SearchTitle=" + cdesc);
}

function ExpandCategory(selfLevel, cid) {
    if (parseInt(selfLevel).toString() != "NaN" && cid != "" && $("#" + cid).length != 0) {
        var nextLevel = (parseInt(selfLevel) + 1).toString();
        $("#" + cid).parent().parent().show(300);
        $("#" + cid).parent().show(300);
        $("#" + cid).next().show(300);
    }
}

//切換版塊內容
function SwapBlockContent(sURL, sMethod, sData, sBlockID, bShowRight) {
    $.ajax({
        async: true,
        type: sMethod,
        url: sURL,
        data: sData,
        success: function(html) {
            errCount = 0;
            var startIndex = html.indexOf("<form");
            var lastIndex = html.indexOf("</form>", startIndex) + 7;
            var formPart = html.substring(startIndex, lastIndex);
            $("#" + sBlockID).html(formPart);
            (bShowRight) ? $("#right").show() : $("#right").hide();
            ScrollTop();
            IFrameResize();

            //設定商品分類
            var regex = /gid=(\w)+&/;
            if (regex.test(sData)) {
                var gid = regex.exec(sData)[0].substring(4, regex.exec(sData).lastIndex - 1);
                GetGoodsCate(true, gid);
            }
            else {
                GetGoodsCate(false, "");
            }
        },
        error: function() {
            if (ErrHandling() <= 3)
                SwapBlockContent(sURL, sMethod, sData, sBlockID, bShowRight);
        }
    });
}

function IFrameResize() {
    if (parent.document.getElementById("iframe") != null) {
        parent.document.getElementById("iframe").width = document.body.scrollWidth;
        parent.document.getElementById("iframe").height = document.body.scrollHeight + 200;
    }
}

//頁面捲動到最上
function ScrollTop() {
    var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body')
    $body.animate({ scrollTop: 0 }, 0);
}

//數字3位逗點分隔
function DollarFormat(number) {
    if (typeof (number) != "undefined") {
        number = number.toString();
        if (number.length <= 3)
            return (number == '' ? '0' : number);
        else {
            var mod = number.length % 3;
            var output = (mod == 0 ? '' : (number.substring(0, mod)));
            for (i = 0; i < Math.floor(number.length / 3); i++) {
                if ((mod == 0) && (i == 0))
                    output += number.substring(mod + 3 * i, mod + 3 * i + 3);
                else
                    output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
            }
            return (output);
        }
    }
}

//搜尋
function Search() {
    switch ($("#SearchType").val()) {
        case "GN":
            $("#srhGoodsName").show();
            $("#srhPriceRange").hide();
            if ($.trim($("#srhGoodsName").val()) != "")
                window.location = encodeURI("GoodsList.aspx?SearchString=" + $("#srhGoodsName").val() + "&SearchTitle=商品名稱 [" + $("#srhGoodsName").val() + "] 搜尋結果");
            break;
        case "PR":
            $("#srhGoodsName").hide();
            $("#srhPriceRange").show();
            var price = $("#srhPriceRange").val().split("_");
            var priceRangeS = "";
            var priceRangeE = "";
            priceRangeS = price[0];
            if (price.length > 1)
                priceRangeE = price[1];
            window.location = encodeURI("GoodsList.aspx?PriceRangeS=" + priceRangeS + "&PriceRangeE=" + priceRangeE + "&OrderBy=PS&SearchTitle=點數區間 [" + priceRangeS + " - " + priceRangeE + "] 搜尋結果");
            break;
    }
}

function SetHotKeys() {
    var html = "";
    $.ajax({
        async: false,
        type: "POST",
        url: "SrvProxyPage.aspx",
        data: "SrvName=GetHotKeys&HotKeyType=",
        success: function(xml) {
            errCount = 0;
            if ($(xml).find("RTNCODE").text() == "000") {
                $(xml).find("HOTKEY_INF").each(function() {
                    var hotkeyID = $(this).find("HOTKEYID").text();
                    var hotkeyDesc = $(this).find("HOTKEYDESC").text();
                    html += "<a href='javascript:SearchHotKeys(\"" + hotkeyDesc + "\");' class='yw'>" + hotkeyDesc + "</a>&nbsp;";
                });
                if (html != "") {
                    $("#HotKeys").append(html);
                    $("#HotKeys").show();
                }
                else {
                    $("#HotKeys").hide();
                }

            }
        },
        error: function() {
            if (ErrHandling() <= 3)
                SetHotKeys();
        }
    });
}

function SearchHotKeys(hotkey) {
    window.location = encodeURI("GoodsList.aspx?SearchString=" + hotkey + "&SearchTitle=商品名稱 [" + hotkey + "] 搜尋結果");
}

function SetMemberInfo() {
    $.ajax({
        async: false,
        type: "POST",
        url: "SrvProxyPage.aspx",
        data: "SrvName=MemberData&",
        success: function(xml) {
            errCount = 0;
            if ($(xml).find("RTNCODE").text() == "000") {
                var memName = ($(xml).find("NICKNAME").text() == "") ? $(xml).find("REALNAME").text() : $(xml).find("NICKNAME").text();
                $("#MemName").text(memName);
            }
        },
        error: function() {
            if (ErrHandling() <= 3)
                SetMemberInfo();
        }
    });
}

//更新剩餘點數
function SetLeftEmoney() {
    $("#Emoney").text(DollarFormat(GetLeftEmoney()));
}

function GetLeftEmoney() {
    var usedAmt = 0;
    var totalAmt = 0;
    var leftAmt = 0;
    $.ajax({
        async: false,
        type: "POST",
        url: "SrvProxyPage.aspx",
        data: "SrvName=MemberEWallet",
        success: function(xml) {
            errCount = 0;
            if ($(xml).find("RTNCODE").text() == "000") {
                $(xml).find("TRANS_INF").each(function() {
                    var $transInfo = $(this);
                    if ($transInfo.find("TRANSMK").text() == "-") {
                        usedAmt += parseInt($transInfo.find("TRANSAMT").text());
                    }
                    else if ($transInfo.find("TRANSMK").text() == "+") {
                        totalAmt += parseInt($transInfo.find("TRANSAMT").text());
                    }
                });
                leftAmt = totalAmt - usedAmt;
            }
        },
        error: function() {
            if (ErrHandling() <= 3)
                SetLeftEmoney();
        }
    });
    return (leftAmt);
}

function checkKeycode(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    if (keycode == 13) {
        if (typeof (loginAPI) != "undefined" && loginAPI.isOpened())
            Login();
        else
            Search();

    }
}

function Login() {
    $("#tip").text("");
    var MemberID = $("#txtMemberID").val();
    var CmpAccount = $("#txtCmpAccount").val();
    var MemberPWD = $("#txtMemberPWD").val();
    var ImgCode = $("#txtImgCode").val();
    var gid = $("#hidGoodsID").val();
    $.ajax({
        async: true,
        type: "POST",
        url: "Login.aspx",
        data: "argMemberID=" + MemberID + "&argCmpAccount=" + CmpAccount + "&argPWD=" + MemberPWD + "&ImgCode=" + ImgCode,
        success: function(data) {
            errCount = 0;
            var rtnCode = $(data).find("#hidRtnCode").val();
            var errDesc = $(data).find("#hidErrDesc").val()
            var MemberStatus = $(data).find("#hidMemberStatus").val();
            if (rtnCode == "000") {
                loginAPI.close();
                if (MemberStatus == "0") {
                    if (gid != "")
                        location.replace("MemberIdentify.aspx?gid=" + gid);
                    else
                        location.replace("MemberIdentify.aspx");
                }
                else {
                    var goodsID = $("#hidGoodsID").val();
                    var wsid = $("#hidWSID").val();

                    if (typeof (goodsID) != "undefined")
                        location.replace("Index.aspx?gid=" + goodsID);
                    else
                        location.replace("Index.aspx");
                }
            }
            else {
                $("#ImgCode").attr("src", "ImgCode.aspx?" + new Date().getMilliseconds());
                $("#tip").text(errDesc);
            }
        },
        error: function() {
            if (ErrHandling() <= 3)
                Login();
        }
    });
}

function ForgetPWD() {
    var MemberID = $("#txtMemberID").val();
    var CmpAccount = $("#txtCmpAccount").val();
    if ($('#txtMemberID').is(':visible') && $("#txtMemberID").val() == "") {
        ShowAlertDialog("輸入錯誤", "請輸入身分證字號以取得新密碼。", "ui-state-error", "");
    }
    else if ($('#txtCmpAccount').is(':visible') && $("#txtCmpAccount").val() == "") {
        ShowAlertDialog("輸入錯誤", "請輸入員工編號以取得新密碼。", "ui-state-error", "");
    }
    else {
        $.ajax({
            async: false,
            type: "POST",
            url: "SrvProxyPage.aspx",
            data: "SrvName=MemberApplPWD&argMemberID=" + MemberID + "&argCmpAccount=" + CmpAccount,
            success: function(xml) {
                errCount = 0;
                if ($(xml).find("RTNCODE").text() == "000") {
                    ShowAlertDialog("密碼申請成功", "密碼通知信已寄送到您的電子信箱囉，<br/>請依信件內容重新設定您的密碼", "", "");
                }
                else {
                    ShowAlertDialog("密碼申請失敗", $(xml).find("ERRDESC").text(), "ui-state-error", "");
                }
            },
            error: function() {
                if (ErrHandling() <= 3)
                    ForgetPWD();
            }
        });
    }
}

function GetGoodsCate(isShow, GoodsID) {
    if (isShow) {
        $.ajax({
            async: false,
            type: "POST",
            url: "SrvProxyPage.aspx",
            data: "SrvName=GetGoodsCate&argGoodsID=" + GoodsID,
            success: function(xml) {
                errCount = 0;
                var i = 3;
                if ($(xml).find("RTNCODE").text() == "000") {
                    var cate = "";
                    $(xml).find("CATE_INF").each(function() {
                        var $cateInfo = $(this);
                        var cateID = ($cateInfo.find("CATEID").text() + "000000000000000000").substring(0, 18);
                        var cateDesc = $cateInfo.find("CATEDESC").text();
                        if (i == 3) {
                            cate = "<span class='tt8'>" + cateDesc + "</span>";
                        }
                        else {
                            cate = "<a href='javascript:DisplayCategory(" + i + ", \"" + cateID + "\", \"" + cateDesc + "\");'>" + cateDesc + "</a> > " + cate;
                        }
                        i--;
                    });
                    $("#GoodsCate").html(cate);
                }
                else {
                    $("#GoodsCate").html("");
                }
            },
            error: function() {
                if (ErrHandling() <= 3)
                    GetGoodsCate();
            }
        });
    }
    else {
        $("#GoodsCate").html("");
    }
}

function B2CReturn() {
    location.replace("http://benefit.ilohas24.com.tw/MemberProfile.aspx?showtype=transaction&page=1");
}

