/**
 * xmlhttp 객체 리턴
 *
 * @return object
 */
function getXmlHttpRequest()
{
    var xmlhttp = false;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    return xmlhttp;
}

/**
 * 실명 인증
 */
function checkRealName()
{
    var name = document.getElementById("real_name");
    var rrn1 = document.getElementById("real_rrn1");
    var rrn2 = document.getElementById("real_rrn2");
    var rrn = rrn1.value + rrn2.value;
    
    if (name.value == "" || rrn == "") {
        alert("성명과 주민번호를 입력해주세요.");
        return;
    }
    
    var xmlHttp = getXmlHttpRequest();
    xmlHttp.open("GET",
            "/mem/check-real-name?name=" + name.value + "&rrn=" + rrn,
            false);
    xmlHttp.send();
    if (xmlHttp.status == 200) {
        var retCode = xmlHttp.responseText;
        
        if (retCode == "Y") {
            var realNameCheck = document.getElementById("real_name_check");
            realNameCheck.value = "Y";
            
            alert("실명 확인되었습니다.");
        } else if (retCode == "M") {
            alert("이미 시앙스몰에 가입한 주민번호입니다.");
        } else {
            alert("실명 확인에 실패하였습니다.\n\n에러코드 : " + retCode);
        }
    }
}

/*
 * maxlength 만큼 옮기면 다음으로 이동하기
 */
function nextFocus(nowId, nextId)
{
    var nowForm = document.getElementById(nowId);
    var nextForm = document.getElementById(nextId);
    
    if (nowForm.value.length == nowForm.maxLength) {
        nextForm.focus();
    }
}

/**
 * 사용자 아이디 확인
 * 
 * @param id
 */
function checkUserId(id)
{
    var chk1 = /^[a-z\d]{3,13}$/i;
    var chk2 = /[a-z]/i; 
    //var chk3 = /\d/;
    
    //return (chk1.test(id) && chk2.test(id) && chk3.test(id));
    return (chk1.test(id) && chk2.test(id));
}

/**
 * 사용자 비밀번호 확인
 * 
 * @param pwd
 */
function checkUserPwd(pwd)
{
    var chk1 = /^[a-zA-Z\d]{10,}$/i;
    var chk2 = /[a-zA-Z]/i; 
    var chk3 = /\d/;
    
    return (chk1.test(pwd) && chk2.test(pwd) && chk3.test(pwd));
}

/**
 * 이메일 형식검사
 * @param email
 * @return
 */
function checkEmailFormat(email)
{
    email.replace(" ", "");
    
    if (email == "") {
        alert("이메일을 입력해주세요.");
        return false;
    } else if (email != "") {
        reg = new RegExp("^[\\w\\-]+(\\.[\\w\\-_]+)*@[\\w\\-]+(\\.[\\w\\-]+)*"
                + "(\\.[a-zA-Z]{2,3})$", "gi");
        
        if (!reg.test(email)) {
            alert("잘못된 이메일형식입니다.");
            return false;
        }
    }

    return true;
}

/**
 * 로그인 팝업창
 * 
 * @param move
 */
function loginPopup(move)
{
    var win = window.open("/mem/login-form",
            "login", "width=450, height=320");
    
    if (move) {
        window.location.href = move;
    }
}

/**
 * 로그아웃
 */
function logout()
{
    $.post("/mem/logout",
            function(data) {
                //window.location.reload();
                window.location.href = "/";
            });
}

/**
 * 천단위 콤마
 * 
 * @param num
 * @return string
 */
function numberFormat(num) {
    var reg = /(^[+-]?\d+)(\d{3})/;
    num = String(num);

    while (reg.test(num)) {
        num = num.replace(reg, '$1' + ',' + '$2');
    }

    return num;
}

/**
 * 숫자만 입력
 * 
 * @return
 */
function isNumber(value) {
    var pattern = /[^0123456789]/g;
    
    if (pattern.test(value)) {
        return false;
    } else {
        return true;
    }
}

/**
 * 우편번호 검색
 */
function searchZipcode(form, zipcode, add)
{
    var win = window.open("/index/search-zipcode?form=" + form
                + "&zipcode=" + zipcode + "&add=" + add,
            "search_zipcode", "width=450, height=500");
}

/**
 * 상품 리스트의 테마샵 선택 박스
 * 
 * @param id 선택박스가 있는 레이어그룹 id
 */
function makeThemeSelect(id)
{
    for (var i = 0; i < $("." + id).length; i++) {
        var themeDiv = $("." + id)[i];
        var prodSn = themeDiv.id.replace(id, "");

        $.post("/prod/theme-list", { prod_sn : prodSn },
            function(data) {
                if (data.length == 0) {
                    return;
                }
                
                var sel = document.createElement("select");
                sel.options[0] = new Option("테마숍--------------", "");
                var sn = null;
                $.each(data, function(index, theme) {
                    sel.options[index + 1] = new Option(theme.name, theme.sn);
                    sn = this.prod_sn;
                });
                $(sel).change(
                    function() {
                        window.location.href = "/theme/shop?sn=" + sel.value;
                    });
                $("#" + id + sn).html(sel);
            }, "json");
    }
}

/**
 * 바로구매
 * 
 * @param sn 상품 sn
 */
function quickBuy(prodSn, categorySn)
{
    $.post("/cart/ord-start",
            { "prod_list[]" : prodSn, category_sn : categorySn,
                ord_mode : "Q" },
            function(data) {
                window.location.href = "/cart/ord-form";
            });
}

/**
 * 리스트 상품 장바구니에 추가
 */
function addListCart(prod, category)
{
    var form = document.cart_form;
    
    $.post("/cart/add-list-cart",
            { "prod_sn" : prod, category_sn : category },
            function(data) {
                if (confirm("장바구니에 상품이 추가되었습니다.\n" +
                		"장바구니로 이동하겠습니까?")) {
                    window.location = "/cart/";
                }
            });
}

/**
 * 찜 목록 추가
 */
function addFavorite(prodSn)
{
    if (prodSn) {
        $.post("/prod/add-favorite", { prod_sn : prodSn },
            function(data) {
                if (data.res == false) {
                    alert(data.msg);
                } else {
                    alert("찜 목록에 추가되었습니다.");
                }
            });
    }
}

/**
 * 쿠폰 발급
 * 
 * @param sn
 * @return
 */
function issueCoupon(sn)
{
    $.post("/mem/issue-coupon", { sn : sn },
            function(data) {
                if (data.res == false) {
                    alert(data.msg);
                } else {
                    alert("쿠폰이 발급되었습니다.");
                    window.location.reload();
                }
            });
}

/**
 * 카테고리 전체메뉴
 */
function viewCategoryMenu()
{
    if ($("#category_menu").css("display") == "none") {
        $("#category_menu").css("display", "block");
    } else {
        $("#category_menu").css("display", "none");
    }
}

/**
 * 검색
 */
function search(id)
{
    if ($("#search_keyword").val() == "") {
        alert("검색어를 입력해주세요.");
        $("#search_keyword").focus();
        return;
    }
    
    window.location = "/search/index?keyword="
        + encodeURI($("#search_keyword").val());
}

/**
 * 엔터 이벤트
 */
function hitEnterKey(event){
    if (event.keyCode == 13){
        search();
    } else {
        event.keyCode == 0;
        return;
    }
} 

/**
 * 품절
 */
function soldOut()
{
    alert('품절된 상품입니다.');
}

/**
 * 계정정보 복사
 */
function copyAcct() {
    window.clipboardData.setData("Text", "국민은행 870-01-0151-961 "
            + "(주)동아사이언스");
    alert("계좌정보가 클립보드에 복사되었습니다.");
}

/**
 * 팝업창 쿠키 셋업
 * 
 * @param name
 * @param value
 * @param expiredays
 */
function setPopupCookie(name, value, expiredays)
{
    var todayDate = new Date();
    
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape(value) + "; path=/; expires="
        + todayDate.toGMTString() + ";";
}
