var avatar_id = 1;
var sex = 'male';
var memberSex = 'male';
var paymentState = 0;
var iOwnAccount = 0;
var iOwnTicket = 0;
var iOwnToken = 0;
var offset_x = 95;
var offset_y = 122;

var LOBBY_MODE = 0;
var SHOP_MODE = 1;


function wardrobeHelp()
{
    window.open('http://cycgame.com/actions/2010/bulletin/web1005/wardrobei.html', 'ebankManual' , 'resizable=1, scrollbars=1, status=0,location=0,  width=1200, height=800');
}
function showItemList(id, colorID, expDate, bWardrobe)
{
    doReloadShop();
    if(typeof(colorID) != "undefined")
    {
        changeWardrobeColor(id + ',' + colorID + ',' + expDate);
    }
    // 處理性別不同
    if(sex != memberSex && id)
    {
        alert('性別不符，無法選購此商品!');
        return;
    }
    var aItem = null;
    if(id && typeof(aAvatar[id]) != "undefined")
    {
        var colorID = parseInt(aAvatar[id]['colorID']);
        if(colorID == 0 && aAvatar[id]['color'] instanceof Array && aAvatar[id]['color'].length) colorID = aAvatar[id]['color'][0];
        aItem = addData(id, colorID);
    }
    if(getParameter('i') =="wardrobe")
    {
        var aBuyListWardrobe = getItemList("buyListWardrobe");
        aBuyListWardrobe = processItemList(aBuyListWardrobe, aItem);
        saveList("buyListWardrobe", aBuyListWardrobe);
        _showItemList(aBuyListWardrobe);
        var aDefaultList = getItemList("default");
        if(typeof(id) == "undefined")
        {
            makeItems(_toCookie(getWholeBody()));
        }
//        else if(typeof(id) == "undefined")
//        {
//            makeItems(_toCookie(getWholeBody()));
//        }
//        makeItems(_toCookie(getWholeBody()));
        paint(aBuyListWardrobe, SHOP_MODE);
    }
    else
    {
        var aBuyList = getItemList("buyList");
        aBuyList = processItemList(aBuyList, aItem);
        saveList("buyList", aBuyList);
        _showItemList(aBuyList);
        paint(aBuyList, SHOP_MODE);
    }
      var aDoffList = getItemList("doffList");
     saveList("doffList", aDoffList);
     _showRemoveList(aDoffList);

    // 清除要移除的商品
    var aRemove = getItemList('remove');
    aRemove.removeSameIDAndColor(aItem);
    saveList("remove", aRemove);
    //
    var aEquip = getItemList('equip');
    aEquip.removeSameType(aItem);
    saveList("equip", aEquip);
    var aPaint = getItemList("default");
    if(id && typeof(aAvatar[id]) != "undefined")
    {
      if(aAvatar[id]['map'] == 'suit')
        {
            takeOffBySuit('overcoat', false);
            takeOffBySuit('pantsOuter', false);
            takeOffBySuit('shirtOuter', false);
        }
        else if(aAvatar[id]['map'] == 'overcoat' || aAvatar[id]['map'] == 'shirtOuter' || aAvatar[id]['map'] == 'pantsOuter')
         {
            takeOffBySuit('suit', false);
         }
    }
}

function getSameType(aList, sMap)
{
    if(!(aList instanceof Array)) return null;
    //
    for(var i=0; i<aList.length; ++i)
    {
        if(aAvatar[aList[i]['id']]['map'] == sMap)
            return aList[i];
    }
    return null;
}
function originalAva(sOriginal)
{
//    var defaultList = get_cookie('doSave');
//    if(typeof(defaultList) != "undefined" && defaultList != null)
//    {
//        sOriginal = defaultList;
//        if(defaultList != sOriginal)
//        {
            window.location.reload();
//        }
//    }
    saveAvatar("buyList", 0);
    saveAvatar("buyListWardrobe", sOriginal);
    saveAvatar("equip", sOriginal);
    saveAvatar("default", sOriginal);
    saveAvatar("doffList", "0");
    paint("", SHOP_MODE);
    clearList();
    if(typeof(removeList) != "undefined") removeList.innerHTML = "";
    doRecoverImage();
    makeItems(sOriginal);
}

function makeItems(sAvatar)
{
    if(typeof(arrImage) == "undefined")   return;
    var bBreak = false;
    var aTmp = sAvatar.split(',');
    for(var i=0; i<aTmp.length; i++)
    {
        var aData = aTmp[i].split('-');
        for(var j=0; j<arrImage.length; j++)
        {
            if(arrImage[j].id == aData[0]  && arrImage[j].color == aData[1])
            {
                var changeImage = document.getElementById(arrImage[j].title);
                changeImage.src = "images/wardrobe/" + memberSex + "/" + memberSex +"_use_over.gif";
                bBreak = true;
                break;
            }
             if(bBreak) break;
        }
    }
}

//脫光光
function clearListAll(sAvatar, noEyesAndMouth, bWardrobeMode)
{
    saveAvatar("buyList", "0");
//    saveAvatar("equip", sAvatar);
    saveAvatar("remove", noEyesAndMouth);
    if(bWardrobeMode)
    {
        saveAvatar("default", sAvatar);
    }

    paint("", SHOP_MODE);

    if(typeof(list) != "undefined") list.innerHTML = "";
    if(typeof(removeList) != "undefined") removeList.innerHTML = "";
    var aDoffList = getItemList("doffList");
    var aDefaultList = getItemList("default");

    for(var i=0; i<aDefaultList.length; i++)
    {
        if(aAvatar[aDefaultList[i]['id']]['map'] != 'eyes' && aAvatar[aDefaultList[i]['id']]['map'] != 'mouth' )
        {
            aDoffList = addItemList(aDoffList, aDefaultList[i]);
        }
    }
    saveList("doffList", aDoffList);
    _showRemoveList(aDoffList);
//    var aList = getItemList("default");
//    saveList("default", aWholeBody);

//    doRecoverImage();
//    makeItems(sAvatar);
}

function takeOffBySuit(sMap, bSuitMode)
{
    if(getParameter('i') =="wardrobe")
    {
        var aBuyList = getItemList("buyListWardrobe");
    }
    else
    {
        var aBuyList = getItemList("buyList");
    }
    var aRemove = getItemList('remove');
    var aEquip = getItemList('equip');
    var aDoffList = getItemList("doffList");
    //  bFlag=true:穿上最後購買的商品
    var bFlag = false;
    var aTakeOff = getSameType(aEquip, sMap);
    if(aTakeOff != null)
    {
        aAvatar[aTakeOff['id']]['colorID'] = aTakeOff['colorID'];
        if(bSuitMode)
        {
            showItemList(aTakeOff['id']);
        }
        aEquip.removeSameType(aTakeOff);
        bFlag = true;
    }
    saveList("equip", aEquip);
    if(bSuitMode)
    {
      if(bFlag) return;
    }
    var aTakeOffDefault = getSameType(aDefault, sMap);
    if(aTakeOffDefault != null)
    {
        if(aRemove.hasSameID(aTakeOffDefault) < 0)
        {
            aRemove.push(aTakeOffDefault);
            aDoffList = addItemList(aDoffList, aTakeOffDefault);
        }
    }
    saveList("remove", aRemove);
    //更新左下角的itemlist
    var aTakeOffBuy = getSameType(aBuyList, sMap);
    if(aTakeOffBuy != null) aBuyList.removeSameType(aTakeOffBuy);
    //
    aTakeOff = aTakeOffBuy;
    if(aTakeOff == null) aTakeOff = aTakeOffDefault;
    if(aTakeOff != null) aEquip.push(aTakeOff);
    if(getParameter('i') =="wardrobe")
    {
        saveList("buyListWardrobe", aBuyList);
    }
    else
    {
        saveList("buyList", aBuyList);
    }
    saveList("equip", aEquip);
    saveList("buyList", aBuyList);
    _showItemList(aBuyList);
    saveList("doffList", aDoffList);
    _showRemoveList(aDoffList);
    paint("", SHOP_MODE);
    sMapRevers = getReverseMap(sMap);
    if(getParameter('top') == sMapRevers  || (getParameter('top') == 'null' && sMap == 'hair'))
    {
         doRecoverImage();
    }
}
function getReverseMap(sItem)
{
    if(sItem == null) return;
    var x = new Array();
    x['hair'] = "hair";
    x['shoes'] = "shoes";
    x['shirtOuter'] = "shirt";
    x['overcoat'] = "coat";
    x['pantsOuter'] = "pants";
    x['suit'] = "suit";
    x['adorn'] = "adorn";
    x['eyes'] = "eyes";
    x['mouth'] = "mouth";
    x['pet'] = "pet";
    x['pantsInner'] = "drawers";
    x['underwear'] = "shirtInner";
    for (i in x)
    {
         if (i == sItem)
        {
            return x[i];
        }
    }
}
function takeOff(sMap)
{
    var aBuyList = getItemList("buyList");
    var aRemove = getItemList('remove');
    var aEquip = getItemList('equip');
    var aDoffList = getItemList("doffList");
    //  bFlag=true:穿上最後購買的商品
    var bFlag = false;
    var aTakeOff = getSameType(aEquip, sMap);
    if(aTakeOff != null)
    {
        aAvatar[aTakeOff['id']]['colorID'] = aTakeOff['colorID'];
        showItemList(aTakeOff['id']);
        aEquip.removeSameType(aTakeOff);
        bFlag = true;
    }
    saveList("equip", aEquip);
    if(bFlag) return;
    var aTakeOffDefault = getSameType(aDefault, sMap);
    if(aTakeOffDefault != null)
    {
        if(aRemove.hasSameID(aTakeOffDefault) < 0)
        {
            aRemove.push(aTakeOffDefault);
            aDoffList = addItemList(aDoffList, aTakeOffDefault);
        }
    }
    saveList("remove", aRemove);
    //更新左下角的itemlist
    var aTakeOffBuy = getSameType(aBuyList, sMap);
    if(aTakeOffBuy != null) aBuyList.removeSameType(aTakeOffBuy);
    //
    aTakeOff = aTakeOffBuy;
    if(aTakeOff == null) aTakeOff = aTakeOffDefault;
    if(aTakeOff != null) aEquip.push(aTakeOff);
    saveList("equip", aEquip);
    saveList("buyList", aBuyList);
    _showItemList(aBuyList);
    saveList("doffList", aDoffList);
    _showRemoveList(aDoffList);
    paint("", SHOP_MODE);
}

function initPaint(aPaint, mode, noCookie)
{
    if(!(aPaint instanceof Array)) aPaint = new Array();
    //
    if(!noCookie)
    {
        var aList = getItemList("default");
    }
    else
    {
        var aList = getItemList(noCookie, "no_use_cookie");
    }
    // 補上臉和身體和新購買的商品
    aList.push(addData('-1', 0)); // face
    aList.push(addData('-2', 0)); // body
    for(var i=0; i<aPaint.length; i++)
    {
        aList = processItemList(aList, aPaint[i]);
    }
    // 商店模式可脫掉預設服裝
    if(mode == SHOP_MODE)
    {
        var aRemove = getItemList('remove');
        for(var i=0; i<aRemove.length; i++)
        {
            aList.removeSameIDAndColor(aRemove[i]);
        }
    }
    return aList;
}


// mode = 0(大廳), mode = 1(商店)
//h  設定圖片高度
//noCookie  不從cookie拿avatar資料
function paint(aPaint, mode, h, noCookie)
{
    if (!h) h = 190;
    if(typeof(mode) == "undefined") mode = LOBBY_MODE;
    //
    if(!(aPaint instanceof Array) && mode == SHOP_MODE)
    {
        if(getParameter('i') =="wardrobe")
        {
            aPaint = getItemList("buyListWardrobe");
        }
        else
        {
            aPaint = getItemList("buyList");
        }
    }
    if(!(aPaint instanceof Array)) aPaint = new Array();
    //
    var div_avatar = document.getElementById("avatar" + avatar_id);
    //
    if(!noCookie)
    {
        aPaint = initPaint(aPaint, mode);
    }
    else
    {
        aPaint = initPaint(aPaint, mode, noCookie);
    }
    //
    var mainFrame = '<div id="cycAvatar" style="position:relative; width:100px; height:'+h+'px; z-index:10; overflow: hidden; clip: rect(auto 0 0 auto);">';
    var rate = 200;
    var nonVipPrice = 0;
    var vipPrice = 0;
    var discount = 1;
    var iTickets = 0;
    for(var i=0; i<aPaint.length; ++i)
    {
        var aData = aAvatar[aPaint[i]['id']];
        aData['mID'] = mIDFormat(aData['mID']);
        //
        _showWholeBodyList(aPaint);
        var type = 0;
        if(aData['id'] != "undefined" && aData['id'])
        {
            if(aData['hasBack'] == '1' || aData['map'] == 'hair' || aData['map'] == 'overcoat')
            {
                type = 2;
                if(aData['hasBack'] == '0') type = 1;
            }
        }
        //
        var sColor = "";
        if(parseInt(aPaint[i]['colorID']) > 0) sColor = aColorMap[parseInt(aPaint[i]['colorID'])]['name'].toLowerCase();
        var iSn = aData['sn'][parseInt(aPaint[i]['colorID'])];
        //
        if(type == 0)
        {
            var info = new AvatarInfo(aData['sex'].toUpperCase(), aData['map'].toUpperCase());
            mainFrame += '<div id="layer'+info.z+'" style="position:absolute; left:'+info.x+'px; top:'+info.y+'px; width:'+info.w+'px; height:'+info.h+'px; z-index:'+info.z+'">';
            mainFrame += '<img src="'+ 'images/newAvatar/'+aData['sex']+'/wholeBody/'+aData['map']+'/'+aData['map']+'_'+iSn+'_'+aData['mID']+sColor+'.gif' +'" name="image'+info.z+'"></div>';
        }
        else if(type == 1)
        {
            var info = new AvatarInfo(aData['sex'].toUpperCase(), aData['map'].toUpperCase()+'_F');
            mainFrame += '<div id="layer'+info.z+'" style="position:absolute; left:'+info.x+'px; top:'+info.y+'px; width:'+info.w+'px; height:'+info.h+'px; z-index:'+info.z+'">';
            mainFrame += '<img src="'+ 'images/newAvatar/'+aData['sex']+'/wholeBody/'+aData['map']+'/'+aData['map']+'_'+iSn+'_'+aData['mID']+sColor+'_F.gif' +'" name="image'+info.z+'"></div>';
        }
        else if(type == 2)
        {
            var info = new AvatarInfo(aData['sex'].toUpperCase(), aData['map'].toUpperCase()+'_F');
            mainFrame += '<div id="layer'+info.z+'" style="position:absolute; left:'+info.x+'px; top:'+info.y+'px; width:'+info.w+'px; height:'+info.h+'px; z-index:'+info.z+'">';
            mainFrame += '<img src="'+ 'images/newAvatar/'+aData['sex']+'/wholeBody/'+aData['map']+'/'+aData['map']+'_'+iSn+'_'+aData['mID']+sColor+'_F.gif' +'" name="image'+info.z+'"></div>';
            //
            var info = new AvatarInfo(aData['sex'].toUpperCase(), aData['map'].toUpperCase()+'_B');
            mainFrame += '<div id="layer'+info.z+'" style="position:absolute; left:'+info.x+'px; top:'+info.y+'px; width:'+info.w+'px; height:'+info.h+'px; z-index:'+info.z+'">';
            mainFrame += '<img src="'+ 'images/newAvatar/'+aData['sex']+'/wholeBody/'+aData['map']+'/'+aData['map']+'_'+iSn+'_'+aData['mID']+sColor+'_B.gif' +'" name="image'+info.z+'"></div>';
        }
        if(aDefault.hasSameIDAndColor(aPaint[i]) < 0)
        {
            if(paymentState == 2)  // 2 is vip
            {
                if(isDuringDiscount())
                {
                    discount = 0.5;
                }
                vipPrice += Math.round(parseInt(aData['price']) * discount) / 1;
            }
            else
            {
                nonVipPrice += parseInt(aData['nonVipPrice']);
            }
            iTickets += parseInt(aData['ticket']);
        }
    }
    mainFrame += '</div>';
    //
    if(mode == LOBBY_MODE)
    {
         document.write(mainFrame);
    }
    else
    {
        if(typeof(div_avatar) != "undefined")
        {
            div_avatar.innerHTML = mainFrame;
        }
    }
    if(typeof(accountList) != "undefined") accountList.innerHTML = '<font  id="accountFont">' + vipPrice +' </font>';
    if(typeof(tokenList) != "undefined") tokenList.innerHTML = '<font  id="tokenFont">'  + nonVipPrice * rate  +' </font>';
    if(typeof(ticketList) != "undefined") ticketList.innerHTML = '<font  id="ticketFont">' + iTickets +' </font>';
}

function isDuringDiscount()
{
    //CYC十週年活動
    var star = new Date(2010, 7, 19, 11, 00, 00);
    var end = new Date(2010, 8, 21, 11, 00, 00);
    now = new Date();
    return false;
//    return (now > star && now < end);
}

function changeColor(sHash)
{
    var aTmp = sHash.split(',');
    var oPic = eval('m'+aTmp[0]);
    var sUrl = oPic.src;
    var aBuyList = getItemList("buyList");

    for(var j in aColorMap)
    {
        if(typeof(aColorMap[j]) == "function") continue;
        var sColor = aColorMap[j]['name'].toLowerCase();
        if(sUrl.indexOf(sColor) >= 0)
        {
            sOldColor = sColor;
            sOldPattern = aAvatar[aTmp[0]]['sn'][j]+'_'+aAvatar[aTmp[0]]['mID']+sOldColor;
            sNewColor = aColorMap[aTmp[1]]['name'].toLowerCase();
            sNewPattern = aAvatar[aTmp[0]]['sn'][aTmp[1]]+'_'+aAvatar[aTmp[0]]['mID']+sNewColor;
            oPic.src = sUrl.replace(sOldPattern, sNewPattern);
            if(aAvatar[aTmp[0]].hasBack == 1)
            {
                var oPic_b = eval('m'+aTmp[0]+'_b');
                var sUrl_b = oPic_b.src;
                oPic_b.src = sUrl_b.replace(sOldPattern, sNewPattern);
            }
            break;
        }
    }
    // 修改全域變數預設的color
    aAvatar[aTmp[0]]['colorID'] = aTmp[1];
    var item = new Array();
    item['id'] = aTmp[0];
    item['colorID'] = aTmp[1];
    if(aBuyList.hasSameIDAndColor(item) < 0)
    {
        showItemList(aTmp[0]);
    }
}

function changeWardrobeColor(sHash)
{
    var aTmp = sHash.split(',');
    var aBuyList = getItemList("buyListWardrobe");
    // 修改全域變數預設的color
    aAvatar[aTmp[0]]['colorID'] = aTmp[1];
    aAvatar[aTmp[0]]['expDate'] = aTmp[2];
    var item = new Array();
    item['id'] = aTmp[0];
    item['colorID'] = aTmp[1];
    if(aBuyList.hasSameIDAndColor(item) < 0)
    {

        showItemList(aTmp[0]);
    }
    saveList("buyListWardrobe", aBuyList);
}

//////////////////////////////////////////////////商店   衣櫃左邊人物圖層位置////////////////////////////////////////////////////////////////////
HAIR_F_MALE_X       = 4;    HAIR_F_MALE_Y       = 6;
HAIR_F_FEMALE_X     = 4;    HAIR_F_FEMALE_Y     = 6;
MOUTH_MALE_X        = 31;   MOUTH_MALE_Y        = 58;
MOUTH_FEMALE_X      = 31;   MOUTH_FEMALE_Y      = 58;
EYES_MALE_X         = 27;   EYES_MALE_Y         = 39;
EYES_FEMALE_X       = 27;   EYES_FEMALE_Y       = 39;
FACE_MALE_X         = 21;   FACE_MALE_Y         = 22;
FACE_FEMALE_X       = 21;   FACE_FEMALE_Y       = 22;
OVERCOAT_F_MALE_X   = 4;    OVERCOAT_F_MALE_Y   = 54;
SUIT_MALE_X         = 4;    SUIT_MALE_Y         = 54;
SUIT_FEMALE_X       = 4;    SUIT_FEMALE_Y       = 54;
ADORN_FEMALE_X      = 0;    ADORN_FEMALE_Y       = 0;
ADORN_MALE_X        = 0;    ADORN_MALE_Y         = 0;
PET_FEMALE_X        = 0;    PET_FEMALE_Y         = 78;
PET_MALE_X          = 0;    PET_MALE_Y           = 78;
OVERCOAT_F_FEMALE_X = 4;    OVERCOAT_F_FEMALE_Y = 54;
SHIRTOUTER_MALE_X   = 9;    SHIRTOUTER_MALE_Y   = 71;
SHIRTOUTER_FEMALE_X = 9;    SHIRTOUTER_FEMALE_Y = 71;
PANTSOUTER_MALE_X   = 10;   PANTSOUTER_MALE_Y   = 71;
PANTSOUTER_FEMALE_X = 10;   PANTSOUTER_FEMALE_Y = 71;
SHIRTINNER_MALE_X   = 10;   SHIRTINNER_MALE_Y   = 71;
SHIRTINNER_FEMALE_X = 10;   SHIRTINNER_FEMALE_Y = 71;
SHOES_MALE_X        = 19;   SHOES_MALE_Y        = 107;
SHOES_FEMALE_X      = 19;   SHOES_FEMALE_Y      = 107;
PANTSINNER_MALE_X   = 10;   PANTSINNER_MALE_Y   = 71;
PANTSINNER_FEMALE_X = 10;   PANTSINNER_FEMALE_Y = 71;
BODY_MALE_X         = 10;   BODY_MALE_Y         = 71;
BODY_FEMALE_X       = 10;   BODY_FEMALE_Y       = 71;
OVERCOAT_B_MALE_X   = 4;    OVERCOAT_B_MALE_Y   = 54;
OVERCOAT_B_FEMALE_X = 4;    OVERCOAT_B_FEMALE_Y = 54;
HAIR_B_MALE_X       = 4;    HAIR_B_MALE_Y       = 4;
HAIR_B_FEMALE_X     = 4;    HAIR_B_FEMALE_Y     = 4;
BACKGROUND_MALE_X   = 0;    BACKGROUND_MALE_Y   = 0;
BACKGROUND_FEMALE_X = 0;    BACKGROUND_FEMALE_Y = 0;

HAIR_F_W = 92;          HAIR_F_H = 134;
MOUTH_W = 35;           MOUTH_H = 17;
EYES_W = 43;            EYES_H = 28;
FACE_W = 55;            FACE_H = 54;
OVERCOAT_F_W = 92;      OVERCOAT_F_H = 122;
SUIT_W = 92;            SUIT_H = 122;
ADORN_W = 100;          ADORN_H = 180;
PET_W = 100;            PET_H = 102;
SHIRTOUTER_W = 83;      SHIRTOUTER_H = 70;
PANTSOUTER_W = 81;      PANTSOUTER_H = 102;
SHIRTINNER_W = 81;      SHIRTINNER_H = 61;
SHOES_W = 63;           SHOES_H = 70;
PANTSINNER_W = 81;      PANTSINNER_H = 101;
BODY_W = 81;            BODY_H = 101;
OVERCOAT_B_W = 92;      OVERCOAT_B_H = 122;
HAIR_B_W = 92;          HAIR_B_H = 159;
BACKGROUND_W = 100;     BACKGROUND_H = 180;

var hash = new Array();
hash['HAIR_B']      = 0;
hash['OVERCOAT_B']  = 1;
hash['BODY']        = 2;
hash['PANTSINNER']   = 3;
hash['SHOES']         = 4;
hash['SHIRTINNER']   = 5;
hash['PANTSOUTER']  = 6;
hash['SHIRTOUTER']  = 7;
hash['OVERCOAT_F']  = 8;
hash['FACE']          = 9;
hash['MOUTH']       = 10;
hash['EYES']          = 11;
hash['SUIT']          = 12;
hash['HAIR_F']       = 13;
hash['ADORN']       = 14;
hash['PET']           = 15;

function renderHeader(nickname)
{
    var mainFrame = '<div id="nickname" style="position:absolute; left:'+(offset_x-50)+'px; top:'+(offset_y-70)+'px; width:175px; height:20px; z-index:'+20+'">';
    mainFrame += '<center>'+''+'</center></div>';
    mainFrame += '<div id="avatar' + avatar_id + '" style="position:absolute; left:' + (offset_x - 11 - 29) + 'px; top:' + (offset_y - 70) + 'px; width:100px; height:180px; z-index:' + 20 + '"></div>';
    document.write(mainFrame);
}

function setID(id)
{
    avatar_id = id;
}

function setSex(sSex, sMemberSex)
{
    sex = sSex;
    memberSex = sMemberSex;
}
function setPayementState(sPayementState)
{
    paymentState = sPayementState;
}
/**
 *  這個僅限用來顯示用     不可做為結帳的依據
 * @param sPayementState
 */
function setOwnMoney(iAcc, iTicket, iToken)
{
    if(iAcc > 0) iOwnAccount = iAcc;
    if(iTicket > 0) iOwnTicket = iTicket;
    if(iToken > 0) iOwnToken = iToken;
}

function setRate(iRate)
{
    rate = iRate;
}

function setOffset(_x, _y)
{
    offset_x = _x;
    offset_y = _y;
}

// 購物車的復原功能
function clearList()
{
    clearAvatar();
    if(typeof(list) != "undefined") list.innerHTML = "";
    paint("", SHOP_MODE);
}

function setInitTicketDay()
{
    set_cookie('alertTicketDay', 'false', 1);
}

function gotoWardrobe(herf)
{
    cleanWeb();
    window.location.href = herf;
}

function checkEnterWardrobe()
{
    if(paymentState != 2)
    {
        cleanWeb();
        loginDialog();
    }
}

function cleanFromWeb()
{
    if(getParameter('sex') == 'null' && getParameter('page') == 'null' && getParameter('type') == 'null' )
    {
        clearAvatar();
        if(typeof(list) != "undefined") list.innerHTML = "";
    }
}

function cleanWeb()
{
    clearAvatar();
    if(typeof(list) != "undefined") list.innerHTML = "";
//    paint("", SHOP_MODE);
}
function setChange(money)
{
    set_cookie('tokenChange', money, 1);
}

function count(bDiscount)
{
    var obj = document.getElementsByName("item[]");
    var money = 0;
    var discount = 1;
    if(typeof(bDiscount) == "undefined") bDiscount = false;
    if(isDuringDiscount() && bDiscount)
    {
        discount = 0.5;
    }
    for(i=0; i<obj.length; i++)
    {
        if(obj[i].checked)
        {
            if(paymentState == 2)// 2 is vip
            {
                money += Math.round(aAvatarPrice[obj[i].value] * discount * 1) / 1;
            }
            else
            {
                money += aAvatarNonVipPrice[obj[i].value];
            }
        }
    }
    return money;
}


function doAlert(buyListName)
{
   var coinType;
   if(get_cookie('sParamPayType') == "account")
   {
       coinType = "C幣";
       setChange('account');
   }
   else if(get_cookie('sParamPayType') == "ticket")
   {
       coinType = "禮卷";
       setChange('ticket');
   }
   else
   {
       coinType = "籌碼";
       setChange('token');
   }
   alert('您的預購商品"' + buyListName + '"是' + coinType + '限定商品，無法作切換喔！');
   history.back(-1);
}

function _toCookie(aItem)
{
    if(!(aItem instanceof Array)) return "";
    //
    var aTmp = new Array();
    for(var i=0; i<aItem.length; ++i)
    {
        aTmp.push(aItem[i]['id']+'-'+aItem[i]['colorID']);
    }
    return aTmp.join(',');
}

function saveList(name, aItem)
{
    saveAvatar(name, _toCookie(aItem));
}

function saveAvatar(name, sAvatar)
{
//    var expires = new Date();
//    expires.setTime(expires.getTime() + 20 * 60 * 1000);  // 20 mins
    if(sAvatar == "") sAvatar = "0";
    set_cookie(name+avatar_id, sAvatar, 1);
}

function checkMoneyEnough()
{
    if(getParameter('payType') =="account")
    {
        var checkout = document.getElementById('accountFont');
        if(parseInt(iOwnAccount) < parseInt(checkout.innerHTML))
        {
            document.getElementById('accountFont').style.color="#FF0000";
        }
        else
        {
            document.getElementById('accountFont').style.color="";
        }
    }
    else if(getParameter('payType') =="ticket")
    {
        var checkout = document.getElementById('ticketFont');
        if(parseInt(iOwnTicket) < parseInt(checkout.innerHTML))
        {
            document.getElementById('ticketFont').style.color="#FF0000";
        }
        else
        {
            document.getElementById('ticketFont').style.color="";
        }
    }
    else
    {
        var checkout = document.getElementById('tokenFont');
        if(parseInt(iOwnToken) < parseInt(checkout.innerHTML))
        {
            document.getElementById('tokenFont').style.color="#FF0000";
        }
        else
        {
            document.getElementById('tokenFont').style.color="";
        }
    }
}
function clearAvatar()
{
    saveAvatar("buyList", "0");
    saveAvatar("buyListWardrobe", "0");
    saveAvatar("doffList", "0");
    saveAvatar("remove", "0");
    saveAvatar("equip", "0");
    saveAvatar("doSave", "0");
}

function addData(id, colorID)
{
    var aData = new Array();
    aData['id'] = id;
    aData['colorID'] = colorID;
    return aData;
}
function getItemCounts()
{
    var obj = document.getElementsByName("item[]");
    var money = 0;
    for(i=0; i<obj.length; i++)
    {
        if(obj[i].checked)
        {
           money++;
        }
    }
    return money;
}

function doCheckCash(actionCheckout)
{
    if(getParameter('payType') =="account")
    {
       var checkout = document.getElementById('accountFont');
       if(typeof(checkout.innerHTML) != "undefined")
       {
         if(iOwnAccount - checkout.innerHTML <0)
         {
            alert('您的C幣不足');
            return;
         }
         else
         {
             set_cookie('alertTicketDay', 'false', 1);
             window.location.href = actionCheckout;
         }
       }
    }
    else if(getParameter('payType') =="ticket")
    {
        var checkout = document.getElementById('ticketFont');
        if(typeof(checkout.innerHTML) != "undefined")
        {
          if(iOwnTicket - checkout.innerHTML <0)
          {
              alert('您的禮卷不足');
              return;
          }
          else
          {
              window.location.href = actionCheckout;
          }
        }
    }
    else
    {
        var checkout = document.getElementById('tokenFont');
        if(typeof(checkout.innerHTML) != "undefined")
        {
          if(iOwnToken - checkout.innerHTML <0)
          {
              alert('您的籌碼不足');
              return;
          }
          else
          {
              window.location.href = actionCheckout;
          }
        }
    }
}

function getParameter(parameterName)
{
    var queryString = window.location.search.substring(1);
    var parameterName = parameterName + "=";
    if(queryString.length > 0)
    {
        begin = queryString.lastIndexOf(parameterName);
        if(begin != -1)
        {
            begin += parameterName.length;
            end = queryString.indexOf("&", begin);
            if(end == -1)
            {
                end = queryString.length
            }
            return unescape(queryString.substring(begin, end));
        }
        return "null";
    }
}
function _showWholeBodyList(aList)
{
    if(!(aList instanceof Array)) return;
    var sHtml = "<table width=150 border=0 cellspacing=0 cellpadding=0 >";
    for(var i=0; i<aList.length; ++i)
    {
        if(aList[i]['id'] > 0)
        {
            sHtml += "<tr>"
            sHtml += "<td width=130 class='style1'>"+'&nbsp '+aAvatar[aList[i]['id']]['name']+"</td>";
            if(getParameter('i') != "newAvaCheckout")
            {
                sHtml += "<td width=20><a style='cursor:hand', onclick='javascript:takeOffBySuit(\""+aAvatar[aList[i]['id']]['map']+"\",\""+true+ "\");'><img src='images/wardrobe/delete_over.gif' title='卸除服飾'></a></td>";
            }
            sHtml += "</tr>";
         }
    }
    sHtml += "</table>";
    if(typeof(listR) != "undefined") listR.innerHTML = sHtml;
}

//  購物車清單
function _showItemList(aList)
{
    if(!(aList instanceof Array)) return;
    var discount = 1;
    if(getParameter('payType') =="account")
    {
        var rate = 1;
        if(isDuringDiscount())
        {
            discount = 0.5;
        }
        var sCTImage = "<img src=images/newAvatar/C-icon.gif align=absmiddle />" ;
        var sHtml = "<table width=160 border=0 cellspacing=0 cellpadding=0 >";
    }
    else if(getParameter('payType') =="ticket")
    {
        var sCTImage = "<img src=images/eBankNew/avatar/" + aAvatar[-1]['sex'] +"/" + aAvatar[-1]['sex'] + "_v_ticket.gif align=absmiddle />" ;
        var sHtml = "<table width=160>";
    }
    else
    {
        var rate = 200;
        var sCTImage = "<img src=images/newAvatar/T-icon.gif align=absmiddle />" ;
        var sHtml = "<table width=160>";
    }

    for(var i=0; i<aList.length; ++i)
    {
        sHtml += "<tr>"
        sHtml += "<td>"+'&nbsp '+aAvatar[aList[i]['id']]['name']+"</td>";
        if(getParameter('payType') =="ticket")
        {
            sHtml += "<td>"+aAvatar[aList[i]['id']]['ticket'] + sCTImage +"</td>";
        }
        else
        {
            if(paymentState == 2)
            {
                sHtml += "<td>"+ Math.round(aAvatar[aList[i]['id']]['price'] * rate * discount*1)/1 + sCTImage +"</td>";
            }
            else
            {
               sHtml += "<td>"+aAvatar[aList[i]['id']]['nonVipPrice']*rate+ sCTImage +"</td>";
            }
        }
        if(getParameter('i') != "newAvaCheckout")
        {
            sHtml += "<td><a  style='cursor:hand', onclick='javascript:showItemList(\""+aList[i]['id']+"\")'><img src='images/newAvatar/del_boutton.gif'></a></td>";
        }
        sHtml += "</tr>";
    }
    sHtml += "</table>";
    if(typeof(list) != "undefined") list.innerHTML = sHtml;
}

//  購物車清單
function _showRemoveList(aList)
{
    if(!(aList instanceof Array)) return;
    if(getParameter('payType') =="account")
    {
        var rate = 1;
        var sCTImage = "<img src=images/newAvatar/C-icon.gif align=absmiddle />" ;
        var sHtml = "<table width=165 border=0 cellspacing=0 cellpadding=0 >";
    }
    else if(getParameter('payType') =="ticket")
    {
        var sCTImage = "<img src=images/eBankNew/avatar/" + aAvatar[-1]['sex'] +"/" + aAvatar[-1]['sex'] + "_v_ticket.gif align=absmiddle />" ;
        var sHtml = "<table width=165>";
    }
    else
    {
        var rate = 200;
        var sCTImage = "<img src=images/newAvatar/T-icon.gif align=absmiddle />" ;
        var sHtml = "<table width=165>";
    }
    for(var i=0; i<aList.length; ++i)
    {
        sHtml += "<tr>"
        sHtml += "<td>"+'&nbsp '+aAvatar[aList[i]['id']]['name']+"</td>";
        if(getParameter('i') != "newAvaCheckout")
        {
            sHtml += "<td><a  style='cursor:hand', onclick='javascript:showItemList(\""+aList[i]['id']+"\")'><img src='images/newAvatar/rollBack.gif'></a></td>";
        }
        sHtml += "</tr>";
    }
    sHtml += "</table>";
    if(typeof(removeList) != "undefined") removeList.innerHTML = sHtml;
}

function getItemList(name, bFlag)
{
    if(!bFlag)
    {
        var sItem = get_cookie(name+avatar_id);
    }
    else
    {
        var sItem = name;
    }
    var aList = new Array();
    if(sItem != null && sItem != "0")
    {
        var aTmp = sItem.split(',');
        for(var i=0; i<aTmp.length; ++i)
        {
            var aData = aTmp[i].split('-');
            aList.push(addData(aData[0], aData[1]));
        }
    }
    return aList;
}

function processItemList(aItem, item)
{
    if(item == null) return aItem;
    var index;
    if((index = aItem.hasSameID(item)) >= 0 && aAvatar[aItem[index]['id']]['colorID'] != aAvatar[item['id']]['colorID'])
    {
        aItem.replace(item, index);
    }
    else if((index = aItem.hasSameIDAndColor(item)) >= 0)
    {
        aItem.remove(index);
            var aDoffList = getItemList("doffList");
            aDoffList = removeItemList(aDoffList, item);
            saveList("doffList", aDoffList);
            _showRemoveList(aDoffList);

    }
    else if((index = aItem.hasSameType(item)) >= 0)
    {
        aItem.replace(item, index);
            var aDefaultList = getItemList("default");
            var aDoffList = getItemList("doffList");
            if(aDefaultList.hasSameType(item) >= 0)
            {
                var aGetSameTypeFromDefual = getSameType(aDefaultList, aAvatar[aItem[index]['id']]['map']);
                var aGetSameTypeFromDoffList = getSameType(aDoffList, aAvatar[aItem[index]['id']]['map']);
                if(aGetSameTypeFromDefual != null)
                {
                    aDoffList = addItemList(aDoffList, aGetSameTypeFromDefual);
                    saveList("doffList", aDoffList);
                    _showRemoveList(aDoffList);
                }
                if(aDoffList.hasSameIDAndColor(item) >= 0)
                {
                    aDoffList = removeItemList(aDoffList, item);
                    saveList("doffList", aDoffList);
                    _showRemoveList(aDoffList);
                }
            }
    }
    else
    {
        aItem.push(item);
        var aDoffList = getItemList("doffList");
        if(aDoffList.hasSameIDAndColor(item) >= 0)
        {
            aDoffList = removeItemList(aDoffList, item);
            saveList("doffList", aDoffList);
            _showRemoveList(aDoffList);
        }
    }
    // 購物清單去除預設服裝
    if(aDefault.hasSameIDAndColor(item) >= 0)
    {
        aItem.removeSameType(item);
        if(typeof(removeList) != "undefined") removeList.innerHTML = "";
    }
    return aItem;
}

function removeItemList(aItem, item)
{
    if(item == null) return aItem;
    var index;
    if((index = aItem.hasSameType(item)) >= 0)
    {
        aItem.remove(index);
    }
    return aItem;
}

function addItemList(aItem, item)
{
    if(item == null) return aItem;
    var index;
    if((index = aItem.hasSameType(item)) >= 0)
    {
    }
    else
    {
        aItem.push(item);
    }
    return aItem;
}

// 格式化: 將流水號補成三位數  ex:  1 ~> 001
function mIDFormat(sMID)
{
    var len = sMID.length;
    for (var i = 0; i<3-len; i++)
    {
        sMID = '0'+sMID;
    }
    return sMID;
}

function AvatarInfo(sex, type)
{
    this.x = eval(type+'_'+sex+'_X');
    this.y = eval(type+'_'+sex+'_Y');
    this.w = eval(type+'_W');
    this.h = eval(type+'_H');
    this.z = hash[type];
}

Array.prototype.remove = function(index)
{
    if(isNaN(index) || index > this.length) return false;
    for(var i=0,n=0; i<this.length; i++)
    {
        if(this[i] != this[index])
        {
            this[n++] = this[i];
        }
    }
    this.length -= 1;
    return true;
}

Array.prototype.replace = function(item, index)
{
    if(index >= this.length || index < 0) return false;
    this[index] = item;
    return true;
}

Array.prototype.hasSameID = function(item)
{
    if(item != null)
    {
        for (var i = 0; i<this.length; i++)
        {
            if (this[i]['id'] == item['id'])
            {
                return i;
            }
        }
    }
    return -1;
}

Array.prototype.hasSameIDAndColor = function(item)
{
    if(item != null)
    {
        for (var i = 0; i<this.length; i++)
        {
            if (this[i]['id'] == item['id'] && this[i]['colorID'] == item['colorID'])
            {
                return i;
            }
        }
    }
    return -1;
}

Array.prototype.hasSameType = function(item)
{
    if(item == null) return -1;
    {
        for (var i = 0; i<this.length; i++)
        {
            if(aAvatar[this[i]['id']]['map'] == aAvatar[item['id']]['map'])
            {
                return i;
            }
        }
    }
    return -1;
}

Array.prototype.removeSameType = function(item)
{
    if(item != null)
    {
        for(var i=0;i<this.length;i++)
        {
            if(aAvatar[this[i]['id']]['map'] == aAvatar[item['id']]['map'])
            {
                this.splice(i, 1);
            }
        }
    }
}

Array.prototype.removeSameIDAndColor = function(item)
{
    if(item != null)
    {
        for (var i = 0; i<this.length; i++)
        {
            if (this[i]['id'] == item['id'] && this[i]['colorID'] == item['colorID'])
            {
                this.splice(i, 1);
            }
        }
    }
}

function alertItemCannotSelect(desc)
{
    if(sex != memberSex )
    {
        alert('性別不符，無法選購此商品!');
        return;
    }
    if(desc != null && desc != "")
    {
        alert(desc);
    }
    else
    {
         if(getParameter('payType') =="account")
         {
            alert("此項商品尚未開放使用C幣購買");
         }
         else if(getParameter('payType') =="ticket")
         {
            alert("此項商品尚未開放使用禮卷購買");
         }
         else
         {
            alert("此項商品尚未開放使用籌碼購買");
         }
    }

}

 function markEquipItem(index)
{
    doRecoverImage();
    if(typeof(arrImage) == "undefined")   return;
    var changeImage = document.getElementById(arrImage[index].title);
    changeImage.src = "images/wardrobe/" + memberSex + "/" + memberSex + "_use_over.gif";
}

function doRecoverImage()
{
    if(typeof(arrImage) == "undefined") return;
    for(var i=0; i<8; i++)
    {
        if(arrImage[i] != null)
        {
            var defImage = document.getElementById(arrImage[i].title);
            defImage.src = "images/wardrobe/" + memberSex + "/" + memberSex + "_use_none.gif";
        }
    }
}
function checkReloadThisPage()
{
    if(get_cookie('isPHPExecuted') == 'true')
    {
        set_cookie('isPHPExecuted', 'false', 1);
    }
    else
    {
       window.location.reload();
    }
}
  function getWholeBody()
    {
        var aPaint = getItemList("default");
        if(getParameter('i') =="wardrobe")
        {
            var aBuyList = getItemList("buyListWardrobe");
        }
        else
        {
            var aBuyList = getItemList("buyList");
        }

        for(var i=0; i<aBuyList.length; i++)
        {
            aPaint = processItemList(aPaint, aBuyList[i], true);
        }
        var aRemove = getItemList('remove');
        for(var i=0; i<aRemove.length; i++)
        {
            aPaint.removeSameIDAndColor(aRemove[i]);
        }
        return aPaint;
    }

function checkNecessityCloth()
{
    var aPaint = getWholeBody();
    for(var i=0; i<aPaint.length; ++i)
    {
        if(aAvatar[aPaint[i]['id']]['map'] == 'overcoat' || aAvatar[aPaint[i]['id']]['map'] == 'shirtOuter' || aAvatar[aPaint[i]['id']]['map'] == 'shirtInner' || aAvatar[aPaint[i]['id']]['map'] == 'suit')     //  shirtOuter
        {
            return false;
        }
    }
    return true;
}

function checkNecessityPants()
{
    var aPaint = getWholeBody();
    for(var i=0; i<aPaint.length; ++i)
    {
        if(aAvatar[aPaint[i]['id']]['map'] == 'pantsOuter' || aAvatar[aPaint[i]['id']]['map'] == 'pantsInner' || aAvatar[aPaint[i]['id']]['map'] == 'suit')     //  pantsOuter
        {
            return false;
        }
    }
    return true;
}

function doSpryEffectFade(effectID)
   {
       //反淡化處理
       if(typeof(effectID) != "undefined")
       {
           if(effectID != null)
           {
               if(eval('window'+'.'+effectID))
               {
                   var effectFade = eval(effectID);
//                   effectFade.start();
               }
           }
       }
       else   //淡化處理
       {

           var aPaint = getWholeBody();
           var bBreak = false;
           for(var i=0; i<8; ++i)
           {
               for(var j=0; j<aPaint.length; ++j)
               {

                   if(aAvatar[aPaint[j]['id']]['expDate'] == '0' || typeof(aAvatar[aPaint[j]['id']]['expDate']) == "undefined")
                   {
                       aAvatar[aPaint[j]['id']]['expDate'] = '00000000000000';
                   }

                   var effectFadeString = ('equip' + aAvatar[aPaint[j]['id']]['id'] +   aPaint[j]['colorID']   + aAvatar[aPaint[j]['id']]['expDate'] + i);
//                      alert(aAvatar[aPaint[j]['id']]['expDate']);
                   if(eval('window'+'.'+effectFadeString))
                   {
                       var effectFade = eval('equip' + aAvatar[aPaint[j]['id']]['id'] + aPaint[j]['colorID'] + aAvatar[aPaint[j]['id']]['expDate'] + i);
//                       effectFade.start();
                       bBreak = true;
                       break;
                   }
               }
               if(bBreak) break;
           }
       } //enf if
   }
//var http_request = false;
function doReloadShop()
{
    if(get_cookie('wardrobeSaveSuccess') == 'true')
    {
        cleanWeb();
        set_cookie('wardrobeSaveSuccess', 'false', 1);
    }
}
function doSaveAvatar(url)
{
     $.ajax({
        type : "POST",
        url : url,
        dataType : "html",
        success: function(data)
        {

            if($(data).find('#changeSuccess').html() != null )
            {
                alert('儲存成功');
                set_cookie('wardrobeSaveSuccess', 'true', 1);
            }
            else
            {
//                if($(data).find('#changeError').html() != null )
//                {
//                }
//                else
//                {
                alert('儲存失敗'); //  未知原因
                set_cookie('wardrobeSaveSuccess', 'false', 1);
//                }

            }
        },
        error : function()
        {
            alert("Sorry, The requested property could not be found.");
        }
});
}

