function open_sort( arg )
{
  location.href = '/front/php/category.php?cate_no=' + arg + '&sort_method='+frm.sort_method.selectedIndex ;
}

function add_basket(product_no)
{
	window.open('/Front/Product/?url=Listbasket&product_no='+product_no, 'list_basket', 'width=405px,height=500px,resizable=yes,scrollbars=yes');
}

/**
 * 상품비교 체크 및 submit
 * 
 * @param max_view_cnt
 * @return
 */
function prdCompareChk(max_view_cnt)
{
    var total_checked = 0;
    var compchk = document.getElementsByName('prdt_comp_list[]');
    
    for(var i=0; i<compchk.length; i++) {
        if(compchk[i].checked) {
            total_checked++;
        }
    }

    if(!total_checked) {
        alert('비교 할 상품을 선택 해주세요.');
        return false;
    }
    if(max_view_cnt < total_checked) {
        alert('상품비교는 '+max_view_cnt+'개 까지 선택이 가능합니다.');
        return false;
    }
    
    for(var i=0; i<compchk.length; i++) {
        if(compchk[i].checked) {
            add_checkbox(compchk[i].value);
        }
    }
    
    var hidden_form = null;
    
    hidden_form = document.createElement('input') ;
    hidden_form.type = 'hidden';
    hidden_form.name = 'url';
    hidden_form.value = 'Compare';
    
    this.f.appendChild(hidden_form);

    this.f.submit();
}

/**
 * 상품비교 체크 폼 생성
 * 
 * @return
 */
function init_form()
{
    if(this.f) {
        this.f.innerHTML = '';
        return this.f;
    }
    this.f = document.createElement('FORM');
    this.f.style.display = 'none';
    this.f.method = 'get';
    this.f.action = '/Front/Product/';
    document.body.appendChild(this.f);
}

/**
 * 상품비교 체크 상품 정리
 * 
 * @param val
 * @return
 */
function add_checkbox(val)
{
    if(!this.f) init_form();
    var check_form = null;
    
    check_form = document.createElement('input') ;
    check_form.type = 'checkbox';
    check_form.name = 'prdt_comp_list[]';
    check_form.value = val;
    
    this.f.appendChild(check_form);    
    check_form.checked = true ;
}

/**
 * 1단 혼합형 상품 옵션 선택
 * @author smyeo
 * @param
 * @return null
 */
function product_option_select(idx)
{
    try {
        eval('var aOptionContents = ' + document.getElementById('sPrdData_'+idx).value);

        // 옵션 키 get
        var aOptionKey = new Array();
        for (var i=0; document.getElementById('a_option_'+idx+'_'+i); i++) {
            var sTmpKey = document.getElementById('a_option_'+idx+'_'+i).value;
            var aTmpKey = sTmpKey.split('::');

            for (sKey in aTmpKey) {
                sTmpKey = aTmpKey[sKey].split('||');
                aOptionKey.push(sTmpKey[1]);
            }
        }
        if (i == 0) {
            // 옵션 없는 상품일경우 pass
            return true;
        }
        
        var sOptionKey = aOptionKey.join('%2C');

        // base data group
        var aOptData = aOptionContents['content'][sOptionKey];

        var iQuantity = parseInt(document.getElementById('quantity_'+idx).value);
        
        var iItemPrice = document.getElementById('prd_sale_price_'+idx).value;
        iItemPrice = parseFloat(iItemPrice.replace(/[^0-9\.]/g, ''));
        if (aOptData['pi_opt_price_type'] == '-') {
            iItemPrice = parseFloat(iItemPrice) - aOptData['pi_opt_price']; 
        } else {
            iItemPrice = parseFloat(iItemPrice) + aOptData['pi_opt_price'];
        }
        iItemPrice = iQuantity * iItemPrice; 

        var aReplaceData = {
                'a_product_min' : aOptData['pi_item_code'],
                'a_prd_item_code' : aOptData['pi_item_code'],
                'a_product_price' : iItemPrice
                //,'aPrdInfo'        : '{"prd_item_code":"'+aOptData['pi_item_code']+'","product_price":'+iItemPrice+',"p_set_prd_flag":"'+document.getElementById('is_set_prd_'+idx).value+'"}'
        };

        // is action
        var bAction = true;

        // 품절여부 확인
        if (aOptData['pi_sell_flag'] == 'T' || aOptData['pi_out_stock_flag'] == 'T') {
            alert('선택하신 상품은 품절 상품입니다.');
            bAction = false;
        }
        
        // 옵션이 일부만 선택되었거나 비정상적일때
        if (aOptData == undefined || !aOptData) {
            bAction = false;
        }
        
        if (bAction == true) {
            for (sKey in aReplaceData) {
                if (document.getElementById(sKey+'_'+idx)) {
                    document.getElementById(sKey+'_'+idx).value = aReplaceData[sKey];
                } else {
                    alert('오류가 발생하였습니다. 페이지 새로고침후 다시 시도해 주세요.');
                    return false;
                }
            }
        } else {
            for (sKey in aReplaceData) {
                if (document.getElementById(sKey+'_'+idx)) {
                    document.getElementById(sKey+'_'+idx).value = '';
                }
            }
        }
    } catch (e) {
        var aReplaceData = new Array(
                'a_product_min',
                'a_prd_item_code',
                'a_product_price'
                //,'aPrdInfo'
        );
        
        for (sKey in aReplaceData) {
            if (document.getElementById(aReplaceData[sKey]+'_'+idx)) {
                document.getElementById(aReplaceData[sKey]+'_'+idx).value = '';
            }
        }
    }
}

/**
 * 1단 혼합형 단일상품 주문/장바구니 담기추가
 * @author smyeo
 * @return null
 */
function add_basket_direct(idx, mode)
{
    var arg             = document.getElementById('a_arg_'+idx).value;
    var product_no      = document.getElementById('a_product_no_'+idx).value;
    var main_cate_no    = document.getElementById('a_main_cate_no_'+idx).value;
    var display_group   = document.getElementById('a_display_group_'+idx).value;
    var has_option      = document.getElementById('a_has_option_'+idx).value;
    var product_min     = document.getElementById('a_product_min_'+idx).value;
    var ship_prepaid    = '';
    var basket_type     = '';
    
    var prd_item_code = document.getElementById('a_prd_item_code_'+idx).value;
    var product_price = document.getElementById('a_product_price_'+idx).value;
    var quantity = document.getElementById('quantity_'+idx).value;
    
    //사용자 정의 옵션 세팅
    document.getElementById('user_option_set').innerHTML = '';
    
    for (var i=0; document.getElementById('a_option_add_'+idx+'_'+i); i++) {
        var optionHtml = '<input name="option_add[]" type="text" value="'+document.getElementById('a_option_add_'+idx+'_'+i).value+'"/>';
        document.getElementById('user_option_set').innerHTML = document.getElementById('user_option_set').innerHTML + optionHtml;
    }
        
    var f = document.main_frm;
    
    // 예외 확인
    if (chkIntval(document.getElementById('quantity_'+idx)) == false) {
        return false;
    }
    
    if (parseInt(quantity.replace(/[^0-9]/g, '')) < 1) {
        alert('수량을 입력해 주세요.');
        return false;
    }
    
    if (document.getElementById('a_product_min_'+idx).value == '') {
        alert('옵션을 선택하세요.');
        return false;
    }
    
    if (document.getElementById('is_set_prd_'+idx).value == 'T') {
        if (confirm('세트상품은 옵션을 다시 선택해 주셔야 합니다.\n\n상품페이지로 이동하시겠습니까?') === true) {
            document.location.href="/Front/Product/?url=Product&product_no="+product_no+"&main_cate_no="+main_cate_no+"&display_group="+display_group;
        }
        return false;
    }
        
    f.command.value = 'add';
    f.redirect.value = mode ;
    f.product_no.value = product_no;
    f.main_cate_no.value = main_cate_no;
    f.display_group.value = display_group;
    f.product_min.value = product_min;
    f.prd_item_code.value = prd_item_code;
    f.product_price.value = product_price;
    f.quantity.value = quantity;
    
    if (f.delv_payment && (ship_prepaid=='C' || ship_prepaid=='P')) { // 스킨 수정 안했을 시에도 호환성 확보를 위해 검사합니다. -smyeo
        f.delv_payment.value = ship_prepaid;
    }
    f.action="/front/php/basket.php?redirect_url=" + document.location.href;
    f.submit();
}

/**
 * 선택항목 장바구니 담기 및 주문
 * @author smyeo
 */
function sel_add_basket(arg)
{
    var wishF = document.product_list;
    var main_cate_no = wishF.main_cate_no.value;
    var offset = wishF.offset.value;
    var page = wishF.page.value;
    
    var iCount = 0;
    var iLastId = parseInt(document.getElementById('lastItemId').value);
    for (var idx=0; idx<=iLastId; idx++) {
        // 옵션 설정 재확인
        product_option_select(idx);
        
        // 수량을 입력하지 않은 대상은 담기/구매되지 않도록 처리
        try {
            var quantity = document.getElementById('quantity_'+idx).value;
            quantity = parseInt(quantity.replace(/[^0-9]/g, ''));
            
            if (chkIntval(document.getElementById('quantity_'+idx)) == false) {
                return false;
            }
            
            if (quantity > 0 && document.getElementById('a_product_min_'+idx).value == '') {
                alert('구매할 상품의 옵션을 선택하세요.');
                return false;
            }

            if (document.getElementById('is_set_prd_'+idx).value == 'T') {
                if (confirm('세트상품은 옵션을 다시 선택해 주셔야 합니다.\n\n상품페이지로 이동하시겠습니까?') === true) {
                    document.location.href="/Front/Product/?url=Product&product_no="+product_no+"&main_cate_no="+main_cate_no+"&display_group="+display_group;
                }
                return false;
            }
            
            if (quantity == 0) {
                document.getElementById('is_disable_item_'+idx).value = 'T';
            } else {
                iCount++;
                document.getElementById('is_disable_item_'+idx).value = 'F';
                
                // 사용자 지정 옵션
                var aUserOption = new Array();
                
                for (var i=0; document.getElementById('a_option_add_'+idx+'_'+i); i++) {
                    aUserOption.push(document.getElementById('a_option_add_'+idx+'_'+i).value);
                }
                document.getElementById('a_option_add_json_'+idx).value = arrayToJson(aUserOption);
            }
        } catch (e) {
            continue;
        }
    }

    if (iCount == 0) {
        alert('구매할 상품의 수량을 입력하세요.');
        return false;
    } else {
        wishF.command.value = 'add';
        wishF.redirect.value = arg;
    
        wishF.action='/front/php/basket.php?redirect_url=' + document.location.href;
        wishF.submit();
        return true;
    }
}

/**
 * 1차 array를 json text로 변환합니다.
 */
function arrayToJson(aTmp)
{
    var aRtnData = new Array();
    for(iKey in aTmp) {
        try{
            if (aTmp[iKey].replace) {
                aTmp[iKey] = aTmp[iKey].replace(/"/g, '\"');
                aRtnData.push( '"'+iKey+'":"'+aTmp[iKey]+'"' );
            }
        } catch(e){
            continue;
        }
    }
    
    return '{'+aRtnData.join(',')+'}';
}

/**
 * 숫자가 입력되었는지 확인
 * @param oObj
 * @return
 */
function chkIntval(oObj)
{
    if (!oObj.value.match(/^[0-9]+$/)) {
        alert('숫자만 입력이 가능합니다.');
        var sReplace = oObj.value.replace(/[^0-9]/g, '');
        oObj.value = (sReplace != '') ? sReplace : '0';
        oObj.focus();
        return false;
    } else {
        return true;
    }
}
