var option_add = false;
var supply_add = false;
var isAndroid = (navigator.userAgent.toLowerCase().indexOf("android") > -1);
var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

function contractHoursText(hours) {
	var totalHours = parseInt(hours, 10) || 0;

	if (totalHours <= 0) {
		return "0시간";
	}

	if (totalHours < 24) {
		return number_format(String(totalHours)) + "시간";
	}

	var day = Math.floor(totalHours / 24);
	var hour = totalHours % 24;

	if (hour > 0) {
		return number_format(String(day)) + "일 " + number_format(String(hour)) + "시간";
	}

	return number_format(String(day)) + "일";
}

function pricingUnitHours(unit) {
	if (unit === 'day') return 24;
	if (unit === 'month') return 24 * 30;
	if (unit === 'year') return 24 * 365;
	if (unit === 'usage') return 1;
	return 1;
}

function pricingUnitDiscountFromLi(unit, $li) {
	var $unitSelect = $li.find('.ct_pricing_unit');
	if (!$unitSelect.length) return 1;
	if (unit === 'day') return parseFloat($unitSelect.data('discount-day')) || 1;
	if (unit === 'month') return parseFloat($unitSelect.data('discount-month')) || 1;
	if (unit === 'year') return parseFloat($unitSelect.data('discount-year')) || 1;
	if (unit === 'usage') return parseFloat($unitSelect.data('discount-usage')) || 1;
	return parseFloat($unitSelect.data('discount-hour')) || 1;
}

function pricingUnitPackagePriceFromLi(unit, $li, baseHourlyPrice) {
	if (unit === 'usage') {
		var usagePackage = parseFloat($li.find('.ct_pricing_unit').data('package-usage'));
		if (!isNaN(usagePackage) && usagePackage > 0) {
			return Math.round(usagePackage);
		}
	}
	var unitHours = pricingUnitHours(unit);
	if (unitHours < 1) unitHours = 1;
	return Math.round((baseHourlyPrice * pricingUnitDiscountFromLi(unit, $li)) * unitHours);
}

function isPricingUnitAllowedInLi(unit, $li) {
	var $unitSelect = $li.find('.ct_pricing_unit');
	if (!$unitSelect.length) return unit === 'hour';
	if (unit === 'day') return String($unitSelect.data('allow-day')) === '1';
	if (unit === 'month') return String($unitSelect.data('allow-month')) === '1';
	if (unit === 'year') return String($unitSelect.data('allow-year')) === '1' || String($unitSelect.data('auto-year')) === '1';
	if (unit === 'usage') return String($unitSelect.data('allow-usage')) === '1';
	return String($unitSelect.data('allow-hour')) === '1';
}

function bestBundlePricingQuote($li, totalHours, baseHourlyPrice, preferredUnit) {
	var units = ['hour', 'day', 'month', 'year', 'usage'];
	var h = parseInt(totalHours, 10) || 0;
	if (h < 1) h = 1;

	var candidates = [];
	for (var i = 0; i < units.length; i++) {
		var u = units[i];
		if (!isPricingUnitAllowedInLi(u, $li)) continue;
		var unitHours = pricingUnitHours(u);
		if (unitHours < 1) unitHours = 1;
		var packagePrice = pricingUnitPackagePriceFromLi(u, $li, baseHourlyPrice);
		if (packagePrice < 0) packagePrice = 0;
		candidates.push({
			unit: u,
			unitHours: unitHours,
			packagePrice: packagePrice
		});
	}

	if (!candidates.length) {
		candidates.push({
			unit: 'hour',
			unitHours: 1,
			packagePrice: Math.round(baseHourlyPrice)
		});
	}

	var maxUnitHours = 1;
	for (var j = 0; j < candidates.length; j++) {
		if (candidates[j].unitHours > maxUnitHours) maxUnitHours = candidates[j].unitHours;
	}

	var limit = h + maxUnitHours;
	var INF = Number.MAX_SAFE_INTEGER;
	var dp = new Array(limit + 1);
	var prevH = new Array(limit + 1);
	var prevI = new Array(limit + 1);
	for (var t = 0; t <= limit; t++) {
		dp[t] = INF;
		prevH[t] = -1;
		prevI[t] = -1;
	}
	dp[0] = 0;

	for (var cur = 0; cur <= limit; cur++) {
		if (dp[cur] === INF) continue;
		for (var ci = 0; ci < candidates.length; ci++) {
			var next = cur + candidates[ci].unitHours;
			if (next > limit) continue;
			var nextCost = dp[cur] + candidates[ci].packagePrice;
			if (nextCost < dp[next]) {
				dp[next] = nextCost;
				prevH[next] = cur;
				prevI[next] = ci;
			}
		}
	}

	var bestH = -1;
	var bestCost = INF;
	for (var covered = h; covered <= limit; covered++) {
		if (dp[covered] === INF) continue;
		if (dp[covered] < bestCost || (dp[covered] === bestCost && (bestH < 0 || covered < bestH))) {
			bestCost = dp[covered];
			bestH = covered;
		}
	}

	if (bestH < 0) {
		bestH = h;
		bestCost = Math.round(baseHourlyPrice * h);
	}

	var mix = {};
	for (var m = 0; m < candidates.length; m++) mix[candidates[m].unit] = 0;
	var trace = bestH;
	while (trace > 0 && prevH[trace] >= 0 && prevI[trace] >= 0) {
		var cidx = prevI[trace];
		var ukey = candidates[cidx].unit;
		mix[ukey] = (mix[ukey] || 0) + 1;
		trace = prevH[trace];
	}

	var repr = '';
	if (preferredUnit && mix[preferredUnit] > 0) {
		repr = preferredUnit;
	}
	if (!repr) {
		var reprOrder = ['year', 'month', 'day', 'hour', 'usage'];
		for (var r = 0; r < reprOrder.length; r++) {
			if ((mix[reprOrder[r]] || 0) > 0) {
				repr = reprOrder[r];
				break;
			}
		}
	}
	if (!repr) repr = 'hour';

	var reprHours = pricingUnitHours(repr);
	if (reprHours < 1) reprHours = 1;
	var reprPackage = pricingUnitPackagePriceFromLi(repr, $li, baseHourlyPrice);
	var reprCount = mix[repr] || 0;
	if (reprCount < 1) reprCount = Math.max(1, Math.ceil(h / reprHours));

	return {
		unit: repr,
		totalPrice: bestCost,
		packagePrice: reprPackage,
		bundleCount: reprCount,
		effectiveHourly: bestCost / h,
		coveredHours: bestH,
		bundleMix: mix
	};
}

function pricingUnitLabelKo(unit) {
	if (unit === 'day') return '1일권';
	if (unit === 'month') return '1개월권';
	if (unit === 'year') return '1년권';
	if (unit === 'usage') return '종량제';
	return '1시간권';
}

function normalizeUsageChargeInput(raw) {
	var amount = parseInt(raw, 10);
	if (isNaN(amount)) amount = 5000;
	if (amount < 5000) amount = 5000;
	if (amount > 1000000) amount = 1000000;
	return amount;
}

function getMemberPointBalance() {
	var mbPoint = parseInt($('#mb_point_balance').val(), 10);
	if (isNaN(mbPoint) || mbPoint < 0) mbPoint = 0;
	return mbPoint;
}

function installPriceByContractHours(totalContractHours) {
	var defaultInstallPrice = parseFloat($("input[name^=default_install_price]").val());
	if (isNaN(defaultInstallPrice) || defaultInstallPrice < 0) defaultInstallPrice = 0;

	var $threshold = $('#install_free_start_hours');
	if (!$threshold.length) {
		return defaultInstallPrice;
	}

	var freeStartHours = parseInt($threshold.val(), 10);
	if (isNaN(freeStartHours) || freeStartHours < 0) freeStartHours = 0;

	var hours = parseInt(totalContractHours, 10);
	if (isNaN(hours) || hours < 0) hours = 0;

	if (freeStartHours > 0 && hours >= freeStartHours) {
		return 0;
	}

	return defaultInstallPrice;
}

function isInstallFeeWaivedByHours(totalContractHours) {
	var $threshold = $('#install_free_start_hours');
	if (!$threshold.length) return false;

	var freeStartHours = parseInt($threshold.val(), 10);
	if (isNaN(freeStartHours) || freeStartHours <= 0) return false;

	var hours = parseInt(totalContractHours, 10);
	if (isNaN(hours) || hours < 0) hours = 0;

	return hours >= freeStartHours;
}

function refreshInstallPriceDisplay(installPrice) {
	var price = parseFloat(installPrice);
	if (isNaN(price) || price < 0) price = 0;

	$("input[name^=io_install_price]").val(String(Math.round(price)));

	var $disp = $('#io_install_price_disp');
	if (!$disp.length) return;

	var ruleText = String($disp.data('rule-text') || '');
	$disp.text(number_format(String(Math.round(price))) + ' Point' + ruleText);
}

function formatBundleMixText(bundleMix) {
	if (!bundleMix) return '';
	var order = ['year', 'month', 'day', 'hour', 'usage'];
	var parts = [];
	for (var i = 0; i < order.length; i++) {
		var u = order[i];
		var cnt = parseInt(bundleMix[u], 10) || 0;
		if (cnt > 0) {
			parts.push(pricingUnitLabelKo(u) + ' ' + cnt + '장');
		}
	}
	return parts.join(' + ');
}

$(function() {
	// 선택옵션
	/* 가상커서 ctrl keyup 이베트 대응 */
	/*
	$(document).on("keyup", "select.it_option", function(e) {
		var sel_count = $("select.it_option").length;
		var idx = $("select.it_option").index($(this));
		var code = e.keyCode;
		var val = $(this).val();

		option_add = false;
		if(code == 17 && sel_count == idx + 1) {
			if(val == "")
				return;

			sel_option_process(true);
		}
	});
	*/

	/* 키보드 접근 후 옵션 선택 Enter keydown 이벤트 대응 */
	$(document).on("keydown", "select.it_option", function(e) {
		var sel_count = $("select.it_option").length;
		var idx = $("select.it_option").index($(this));
		var code = e.keyCode;
		var val = $(this).val();

		option_add = false;
		if(code == 13 && sel_count == idx + 1) {
			if(val == "")
				return;

			sel_option_process(true);
		}
	});

	if(isAndroid) {
		$(document).on("touchend", "select.it_option", function() {
			option_add = true;
		});
	} else {
		var it_option_events = isSafari ? "mousedown" : "mouseup";

		$(document).on(it_option_events, "select.it_option", function(e) {
			option_add = true;
		});
	}

	$(document).on("change", "select.it_option", function() {
		var sel_count = $("select.it_option").length;
		var idx = $("select.it_option").index($(this));
		var val = $(this).val();
		var it_id = $("input[name='it_id[]']").val();

		// 선택값이 없을 경우 하위 옵션은 disabled
		if(val == "") {
			$("select.it_option:gt("+idx+")").val("").attr("disabled", true);
			return;
		}

		// 하위선택옵션로드
		if(sel_count > 1 && (idx + 1) < sel_count) {
			var opt_id = "";

			// 상위 옵션의 값을 읽어 옵션id 만듬
			if(idx > 0) {
				$("select.it_option:lt("+idx+")").each(function() {
					if(!opt_id)
						opt_id = $(this).val();
					else
						opt_id += chr(30)+$(this).val();
				});

				opt_id += chr(30)+val;
			} else if(idx == 0) {
				opt_id = val;
			}

			$.post(
				"./itembuyoption.php",
				{ it_id: it_id, opt_id: opt_id, idx: idx, sel_count: sel_count },
				function(data) {
					$("select.it_option").eq(idx+1).empty().html(data).attr("disabled", false);

					// select의 옵션이 변경됐을 경우 하위 옵션 disabled
					if(idx+1 < sel_count) {
						var idx2 = idx + 1;
						$("select.it_option:gt("+idx2+")").val("").attr("disabled", true);
					}
				}
			);
		} else if((idx + 1) == sel_count) { // 선택옵션처리
			if(option_add && val == "")
				return;

			var info = val.split(",");
			// 재고체크
			if(parseInt(info[2]) < 1) {
				alert("선택하신 선택옵션상품은 재고가 부족하여 구매할 수 없습니다.");
				return false;
			}

			if(option_add)
				sel_option_process(true);
		}
	});

	// 추가옵션
	/* 가상커서 ctrl keyup 이베트 대응 */
	/*
	$(document).on("keyup", "select.it_supply", function(e) {
		var $el = $(this);
		var code = e.keyCode;
		var val = $(this).val();

		supply_add = false;
		if(code == 17) {
			if(val == "")
				return;

			sel_supply_process($el, true);
		}
	});
	*/

	/* 키보드 접근 후 옵션 선택 Enter keydown 이벤트 대응 */
	$(document).on("keydown", "select.it_supply", function(e) {
		var $el = $(this);
		var code = e.keyCode;
		var val = $(this).val();

		supply_add = false;
		if(code == 13) {
			if(val == "")
				return;

			sel_supply_process($el, true);
		}
	});

	if(isAndroid) {
		$(document).on("touchend", "select.it_supply", function() {
			supply_add = true;
		});
	} else {
		var it_supply_events = isSafari ? "mousedown" : "mouseup";

		$(document).on(it_supply_events, "select.it_supply", function(e) {
			supply_add = true;
		});
	}

	$(document).on("change", "select.it_supply", function() {
		var $el = $(this);
		var val = $(this).val();

		if(val == "")
			return;

		if(supply_add)
			sel_supply_process($el, true);
	});

	// 계약일수 마우스 클릭 itemform
	$(document).on("click", "#it_sel_option li button", function() {
		if ($(this).hasClass('ct_count_btn')) {
			return;
		}

		var mode = $(this).text();
		var this_qty;
		var $el_qty = $(this).closest("li").find("input[name^='ct_qty']");

		// input 필드에서 min, max 속성값 가져오기
		var min_qty = parseInt($el_qty.attr('min')) || 0; // 기본값 0
		var max_qty = parseInt($el_qty.attr('max')) || 365; // 기본값 365

		switch(mode) {
			case "증가":
				this_qty = parseInt($el_qty.val().replace(/[^0-9]/, "")) + 1;

				if (this_qty > max_qty) {
					this_qty = max_qty;
					alert("최대 계약일수는 " + number_format(String(max_qty)) + "일 입니다.");
				}

				$el_qty.val(this_qty);
				$(this).val(max_qty);
				price_calculate();
				break;

			case "감소":
				this_qty = parseInt($el_qty.val().replace(/[^0-9]/, "")) - 1;
				if (this_qty < min_qty) {
					this_qty = min_qty;
					alert("최소 계약일수는 " + number_format(String(min_qty)) + "일 입니다.");
				}
				$el_qty.val(this_qty);
				$(this).val(min_qty);
				price_calculate();
				break;

			case "삭제":
				if (confirm("선택하신 옵션항목을 삭제하시겠습니까?")) {
					var $el = $(this).closest("li");
					var del_exec = true;

					if ($("#it_sel_option .it_spl_list").length > 0) {
						if ($el.hasClass("it_opt_list")) {
							if ($(".it_opt_list").length <= 1)
								del_exec = false;
						}
					}

					if (del_exec) {
						$el.closest("li").remove();
						price_calculate();
					} else {
						alert("선택옵션은 하나이상이어야 합니다.");
						return false;
					}
				}
				break;

			default:
				alert("올바른 방법으로 이용해 주십시오.");
				break;
		}
	});


	// 계약시간 마우스 클릭 itemform
	$(document).on("click", "#it_sel_option_hour li button", function() {
		if ($(this).hasClass('ct_count_btn')) {
			return;
		}

		var mode = $(this).text();
		var this_qty;
		var $el_qty = $(this).closest("li").find("input[name^='ct_qty_hour']");

		// input 필드에서 min, max 속성값 가져오기
		var min_qty = parseInt($el_qty.attr('min')) || 0; // 기본값 0
		var max_qty = parseInt($el_qty.attr('max')) || 24; // 기본값 24

		switch(mode) {
			case "증가":
				this_qty = parseInt($el_qty.val().replace(/[^0-9]/, "")) + 1;

				if (this_qty > max_qty) {
					this_qty = max_qty;
					alert("최대 계약시간은 " + contractHoursText(max_qty) + " 입니다.");
				}

				$el_qty.val(this_qty);
				$(this).val(max_qty);
				price_calculate_hour();
				break;

			case "감소":
				this_qty = parseInt($el_qty.val().replace(/[^0-9]/, "")) - 1;
				if (this_qty < min_qty) {
					this_qty = min_qty;
					alert("최소 계약시간은 " + contractHoursText(min_qty) + " 입니다.");
				}
				$el_qty.val(this_qty);
				$(this).val(min_qty);
				price_calculate_hour();
				break;

			case "삭제":
				if (confirm("선택하신 옵션항목을 삭제하시겠습니까?")) {
					var $el = $(this).closest("li");
					var del_exec = true;

					if ($("#it_sel_option_hour .it_spl_list").length > 0) {
						if ($el.hasClass("it_opt_list")) {
							if ($(".it_opt_list").length <= 1)
								del_exec = false;
						}
					}

					if (del_exec) {
						$el.closest("li").remove();
						price_calculate_hour();
					} else {
						alert("선택옵션은 하나이상이어야 합니다.");
						return false;
					}
				}
				break;

			default:
				alert("올바른 방법으로 이용해 주십시오.");
				break;
		}
	});


	// 계약일수 키보드 입력 itemform
	$(document).on("blur", "input[name^='ct_qty']", function() {
		var val = $(this).val();

		if(val !== "") {
			if(val.replace(/[0-9]/g, "").length > 0) {
				alert("계약일수는 숫자만 입력해 주십시오.");
				$(this).val(0);
			} else {
				var d_val = parseInt(val);

				// input 필드에서 min, max 속성값 가져오기
				var min_qty = parseInt($(this).attr('min')) || 0; // 기본값 0
				var max_qty = parseInt($(this).attr('max')) || 365; // 기본값 365

				if (d_val < min_qty) {
					alert("최소 계약일수는 " + min_qty + "일 입니다.");
					$(this).val(min_qty);
				} else if (d_val > max_qty) {
					alert("최대 계약일수는 " + max_qty + "일 입니다.");
					$(this).val(max_qty);
				}
			}
			price_calculate();
		}
	});


	// 계약시간 키보드 입력 itemform
	$(document).on("keyup", "input[name^='ct_qty_hour']", function() {
		var val = $(this).val();

		if(val !== "") {
			if(val.replace(/[0-9]/g, "").length > 0) {
				alert("계약시간은 숫자만 입력해 주십시오.");
				$(this).val(0);
			} else {
				var d_val = parseInt(val);

				// input 필드에서 min, max 속성값 가져오기
				var min_qty = parseInt($(this).attr('min')) || 0; // 기본값 0
				var max_qty = parseInt($(this).attr('max')) || 24; // 기본값 24

				if (d_val < min_qty) {
					alert("최소 계약시간은 " + contractHoursText(min_qty) + " 입니다.");
					$(this).val(min_qty);
				} else if (d_val > max_qty) {
					alert("최대 계약시간은 " + contractHoursText(max_qty) + " 입니다.");
					$(this).val(max_qty);
				}

			}
			price_calculate_hour();
		}
	});

});

// 선택옵션 추가처리
function sel_option_process(add_exec)
{
	var it_price = parseInt($("input#it_price").val());
	var id = "";
	var value, info, sel_opt, item, price, stock, run_error = false;
	var option = sep = "";
	info = $("select.it_option:last").val().split(",");

	$("select.it_option").each(function(index) {
		value = $(this).val();
		item = $(this).closest("tr").find("th label").text();

		if(!value) {
			run_error = true;
			return false;
		}

		// 옵션선택정보
		sel_opt = value.split(",")[0];

		if(id == "") {
			id = sel_opt;
		} else {
			id += chr(30)+sel_opt;
			sep = " / ";
		}

		option += sep + item + ":" + sel_opt;
	});

	if(run_error) {
		alert(item+"을(를) 선택해 주십시오.");
		return false;
	}

	price = info[1];
	stock = info[2];

	// 금액 음수 체크
	if(it_price + parseInt(price) < 0) {
		alert("구매금액이 음수인 상품은 구매할 수 없습니다.");
		return false;
	}

	if(add_exec) {
		if(same_option_check(option))
			return;

		add_sel_option(0, id, option, price, stock);
	}
}

// 추가옵션 추가처리
function sel_supply_process($el, add_exec)
{
	var val = $el.val();
	var item = $el.closest("tr").find("th label").text();

	if(!val) {
		alert(item+"을(를) 선택해 주십시오.");
		return;
	}

	var info = val.split(",");

	// 재고체크
	if(parseInt(info[2]) < 1) {
		alert(info[0]+"은(는) 재고가 부족하여 구매할 수 없습니다.");
		return false;
	}

	var id = item+chr(30)+info[0];
	var option = item+":"+info[0];
	var price = info[1];
	var stock = info[2];

	// 금액 음수 체크
	if(parseInt(price) < 0) {
		alert("구매금액이 음수인 상품은 구매할 수 없습니다.");
		return false;
	}

	if(add_exec) {
		if(same_option_check(option))
			return;

		add_sel_option(1, id, option, price, stock);
	}
}

// 선택된 옵션 출력
function add_sel_option(type, id, option, price, stock)
{
	var item_code = $("input[name='it_id[]']").val();
	var it_msg1 = $("input[name='it_msg1[]']").val();
	var it_msg2 = $("input[name='it_msg2[]']").val();
	var it_msg3 = $("input[name='it_msg3[]']").val();

	var opt = "";
	var li_class = "it_opt_list";
	if(type)
		li_class = "it_spl_list";

	var opt_prc;
	if(parseInt(price) >= 0)
		opt_prc = "(+"+number_format(String(price))+" Point)";
	else
		opt_prc = "("+number_format(String(price))+" Point)";

	opt += "<li class=\""+li_class+" list-group-item\">";
	opt += "<input type=\"hidden\" name=\"io_type["+item_code+"][]\" value=\""+type+"\">";
	opt += "<input type=\"hidden\" name=\"io_id["+item_code+"][]\" value=\""+id+"\">";
	opt += "<input type=\"hidden\" name=\"io_value["+item_code+"][]\" value=\""+option+"\">";
	opt += "<input type=\"hidden\" class=\"io_price\" value=\""+price+"\">";
	opt += "<input type=\"hidden\" class=\"io_stock\" value=\""+stock+"\">";
	opt += "<div class=\"row\"><div class=\"col-sm-7\"><label>";
	opt += "<span class=\"it_opt_subj\">"+option+"</span>";
	opt += "<span class=\"it_opt_prc\">"+opt_prc+"</span>";
	opt += "</label></div><div class=\"col-sm-5\">";
	opt += "<div class=\"input-group\"><input type=\"text\" name=\"ct_qty["+item_code+"][]\" value=\"1\" class=\"form-control input-sm\" size=\"5\">";
	opt += "<div class=\"input-group-btn\">";
	opt += "<button type=\"button\" class=\"it_qty_plus btn btn-sm btn-lightgray\"><i class=\"fa fa-plus-circle fa-lg\"></i><span class=\"sound_only\">증가</span></button>";
	opt += "<button type=\"button\" class=\"it_qty_minus btn btn-sm btn-lightgray\"><i class=\"fa fa-minus-circle fa-lg\"></i><span class=\"sound_only\">감소</span></button>";
	opt += "<button type=\"button\" class=\"it_opt_del btn btn-sm btn-lightgray\"><i class=\"fa fa-times-circle fa-lg\"></i><span class=\"sound_only\">삭제</span></button>";
	opt += "</div></div></div></div>";
	if(!type) {
		if(it_msg1) {
			opt += "<div style=\"margin-top:10px;\"><input type=\"text\" name=\"pt_msg1["+item_code+"][]\" class=\"form-control input-sm\" placeholder=\""+it_msg1+"\"></div>";
		}
		if(it_msg2) {
			opt += "<div style=\"margin-top:10px;\"><input type=\"text\" name=\"pt_msg2["+item_code+"][]\" class=\"form-control input-sm\" placeholder=\""+it_msg2+"\"></div>";
		}
		if(it_msg3) {
			opt += "<div style=\"margin-top:10px;\"><input type=\"text\" name=\"pt_msg3["+item_code+"][]\" class=\"form-control input-sm\" placeholder=\""+it_msg3+"\"></div>";
		}
	}
	opt += "</li>";

	if($("#it_sel_option > ul").length < 1) {
		$("#it_sel_option").html("<ul id=\"it_opt_added\" class=\"list-group\"></ul>");
		$("#it_sel_option > ul").html(opt);
	} else{
		if(type) {
			if($("#it_sel_option .it_spl_list").length > 0) {
				$("#it_sel_option .it_spl_list:last").after(opt);
			} else {
				if($("#it_sel_option .it_opt_list").length > 0) {
					$("#it_sel_option .it_opt_list:last").after(opt);
				} else {
					$("#it_sel_option > ul").html(opt);
				}
			}
		} else {
			if($("#it_sel_option .it_opt_list").length > 0) {
				$("#it_sel_option .it_opt_list:last").after(opt);
			} else {
				if($("#it_sel_option .it_spl_list").length > 0) {
					$("#it_sel_option .it_spl_list:first").before(opt);
				} else {
					$("#it_sel_option > ul").html(opt);
				}
			}
		}
	}

	price_calculate();
}

// 동일선택옵션있는지
function same_option_check(val)
{
	var result = false;
	$("input[name^=io_value]").each(function() {
		if(val == $(this).val()) {
			result = true;
			return false;
		}
	});

	if(result)
		alert(val+" 은(는) 이미 추가하신 옵션상품입니다.");

	return result;
}

// 가격계산 (1일단위 증감시 계산용)
function price_calculate()
{
	var it_price = parseFloat($("input#it_price").val());

	if(isNaN(it_price))
		return;

	var $el_prc = $("input.io_price");
	var $el_qty = $("input[name^=ct_qty]");
	var $el_qty_hour = $("input[name^=ct_qty_hour]");
	var $el_type = $("input[name^=io_type]");
	var price, type, qty, qty_hour, total = 0;

	var remainMbPoint = getMemberPointBalance();
	var totalContractHoursForInstall = 0;

	$el_prc.each(function(index) {
		price = parseFloat($(this).val());
		qty = parseFloat($el_qty.eq(index).val());
		qty_hour = parseFloat($el_qty_hour.eq(index).val());
		type = $el_type.eq(index).val();
		var totalHours = (qty * 24) + qty_hour;
		if (isNaN(totalHours) || totalHours < 1) totalHours = 1;
		var $li = $(this).closest('li');

		if(type == "0") { // 선택옵션
			totalContractHoursForInstall += totalHours;
			var selectedUnit = $li.find('.ct_pricing_unit').val() || 'hour';
			var quote;
			if (selectedUnit === 'usage') {
				var usageAmount = normalizeUsageChargeInput($li.find('.ct_pricing_count').val());
				$li.find('.ct_pricing_count').val(String(usageAmount));
				var needAmount = usageAmount - remainMbPoint;
				if (needAmount < 0) needAmount = 0;
				remainMbPoint = remainMbPoint - usageAmount;
				if (remainMbPoint < 0) remainMbPoint = 0;
				quote = {
					unit: 'usage',
					totalPrice: needAmount,
					packagePrice: needAmount,
					bundleCount: 1,
					effectiveHourly: needAmount,
					coveredHours: 1,
					bundleMix: { hour: 0, day: 0, month: 0, year: 0, usage: 1 }
				};
			} else {
				quote = bestBundlePricingQuote($li, totalHours, it_price, selectedUnit);
			}
			$li.find('.ct_pricing_unit_hidden').val(quote.unit);
			$li.find('.ct_pricing_discount_hidden').val(String(pricingUnitDiscountFromLi(quote.unit, $li)));
			var selectedUnitHours = pricingUnitHours(selectedUnit);
			if (selectedUnitHours < 1) selectedUnitHours = 1;
			var selectedPackage = pricingUnitPackagePriceFromLi(selectedUnit, $li, it_price);
			var selectedTotal = Math.max(1, Math.ceil(totalHours / selectedUnitHours)) * selectedPackage;
			if (quote.totalPrice < selectedTotal) {
				var mixText = formatBundleMixText(quote.bundleMix);
				var msg = '자동최저가 적용';
				if (mixText) msg += ': ' + mixText;
				$li.find('.ct_auto_pricing_notice').text(msg).show();
			} else {
				$li.find('.ct_auto_pricing_notice').hide();
			}
			if (selectedUnit === 'usage') {
				$li.find('.ct_human_time_hint').text('유효기한: 주문일로부터 365일 / 충전필요금액: ' + number_format(String(quote.totalPrice)) + ' Point');
			} else {
				var hintText = '선택기간: ' + contractHoursText(totalHours);
				if (isInstallFeeWaivedByHours(totalHours)) {
					var waivedInstallPrice = parseFloat($("input[name^=default_install_price]").val());
					if (isNaN(waivedInstallPrice) || waivedInstallPrice < 0) waivedInstallPrice = 0;
					hintText += ' ※ 개통비/설치비 ' + number_format(String(Math.round(waivedInstallPrice))) + ' Point 면제';
				}
				$li.find('.ct_human_time_hint').text(hintText);
			}
			total += (quote.totalPrice + (price * totalHours));
		} else { // 추가옵션
			total += (price * totalHours);
		}
	});

	var installPrice = installPriceByContractHours(totalContractHoursForInstall);
	refreshInstallPriceDisplay(installPrice);
	total += installPrice;

	//$("#it_tot_price").empty().html(number_format(String(total))+"원");
	$("#it_tot_price").empty().html(number_format(String(total))+" Point");

	// 설치비는 서버에서 최종 확정되며, 여기서는 동일 규칙을 실시간 미리보기로 반영

}

// 가격계산 (1시간단위 증감시 계산용)
function price_calculate_hour()
{
	var it_price = parseFloat($("input#it_price").val());

	if(isNaN(it_price))
		return;

	var $el_prc = $("input.io_price");
	var $el_qty = $("input[name^=ct_qty]");
	var $el_qty_hour = $("input[name^=ct_qty_hour]");
	var $el_type = $("input[name^=io_type]");
	var price, type, qty, qty_hour, total = 0;

	var remainMbPoint = getMemberPointBalance();
	var totalContractHoursForInstall = 0;

	$el_prc.each(function(index) {
		price = parseFloat($(this).val());
		qty = parseFloat($el_qty.eq(index).val());
		qty_hour = parseFloat($el_qty_hour.eq(index).val());
		type = $el_type.eq(index).val();
		var totalHours = (qty * 24) + qty_hour;
		if (isNaN(totalHours) || totalHours < 1) totalHours = 1;
		var $li = $(this).closest('li');

		if(type == "0") { // 선택옵션
			totalContractHoursForInstall += totalHours;
			var selectedUnit = $li.find('.ct_pricing_unit').val() || 'hour';
			var quote;
			if (selectedUnit === 'usage') {
				var usageAmount = normalizeUsageChargeInput($li.find('.ct_pricing_count').val());
				$li.find('.ct_pricing_count').val(String(usageAmount));
				var needAmount = usageAmount - remainMbPoint;
				if (needAmount < 0) needAmount = 0;
				remainMbPoint = remainMbPoint - usageAmount;
				if (remainMbPoint < 0) remainMbPoint = 0;
				quote = {
					unit: 'usage',
					totalPrice: needAmount,
					packagePrice: needAmount,
					bundleCount: 1,
					effectiveHourly: needAmount,
					coveredHours: 1,
					bundleMix: { hour: 0, day: 0, month: 0, year: 0, usage: 1 }
				};
			} else {
				quote = bestBundlePricingQuote($li, totalHours, it_price, selectedUnit);
			}
			$li.find('.ct_pricing_unit_hidden').val(quote.unit);
			$li.find('.ct_pricing_discount_hidden').val(String(pricingUnitDiscountFromLi(quote.unit, $li)));
			var selectedUnitHours = pricingUnitHours(selectedUnit);
			if (selectedUnitHours < 1) selectedUnitHours = 1;
			var selectedPackage = pricingUnitPackagePriceFromLi(selectedUnit, $li, it_price);
			var selectedTotal = Math.max(1, Math.ceil(totalHours / selectedUnitHours)) * selectedPackage;
			if (quote.totalPrice < selectedTotal) {
				var mixText = formatBundleMixText(quote.bundleMix);
				var msg = '자동최저가 적용';
				if (mixText) msg += ': ' + mixText;
				$li.find('.ct_auto_pricing_notice').text(msg).show();
			} else {
				$li.find('.ct_auto_pricing_notice').hide();
			}
			if (selectedUnit === 'usage') {
				$li.find('.ct_human_time_hint').text('유효기한: 주문일로부터 365일 / 충전필요금액: ' + number_format(String(quote.totalPrice)) + ' Point');
			} else {
				var hintText = '선택기간: ' + contractHoursText(totalHours);
				if (isInstallFeeWaivedByHours(totalHours)) {
					var waivedInstallPrice = parseFloat($("input[name^=default_install_price]").val());
					if (isNaN(waivedInstallPrice) || waivedInstallPrice < 0) waivedInstallPrice = 0;
					hintText += ' ※ 개통비/설치비 ' + number_format(String(Math.round(waivedInstallPrice))) + ' Point 면제';
				}
				$li.find('.ct_human_time_hint').text(hintText);
			}
			total += (quote.totalPrice + (price * totalHours));
		} else { // 추가옵션
			total += (price * totalHours);
		}
	});

	var installPrice = installPriceByContractHours(totalContractHoursForInstall);
	refreshInstallPriceDisplay(installPrice);
	total += installPrice;

	//$("#it_tot_price").empty().html(number_format(String(total))+"원");
	$("#it_tot_price").empty().html(number_format(String(total))+" Point");

	// 설치비는 서버에서 최종 확정되며, 여기서는 동일 규칙을 실시간 미리보기로 반영

}

// php chr() 대응
function chr(code)
{
	return String.fromCharCode(code);
}
