//constructor of class optNode
function OptNode(optNo){

	this.optNo = optNo;
	this.subNodes = new Array();


	this.setChildSelBox = function(idName,idx){	

		var newIdx = parseInt(idx) + 1;

		var childSelBoxId = idName + ";" + newIdx + ";Y";

		//debug('start set child' + childSelBoxId);

		if($(childSelBoxId) != undefined){
			this.childSelBox = $(childSelBoxId);								//found child selection box so quit (true)
			//debug('found');
			return true;
		} else {
			childSelBoxId = idName + ";" + newIdx + ";N";
			if($(childSelBoxId) != undefined){									//Not found usable selectionbox, But there may be another selection box. searching go on
				//debug('searching go on');				
				return this.setChildSelBox(idName,newIdx);
				

			} else {
				//debug('end');
				return false; //there is no more selection box so quit (false)
			}
		}				
	};

	if(optNo != null){

		if($('_OPT_SEL_OPTION_' + optNo)==undefined)
			alert('option id를 찾을 수 없습니다. 옵션 작동에 이상이 있을 수 있습니다. 개발자에게 문의하세요');

		this.selBox = $('_OPT_SEL_OPTION_' + optNo).parentNode;

		var arrTmp = this.selBox.id.split(";");
		this.setChildSelBox(arrTmp[0],arrTmp[1]);

		this.id = $('_OPT_SEL_OPTION_' + optNo).id;
		this.innerHTML = $('_OPT_SEL_OPTION_' + optNo).innerHTML;

	}

	
	
	//method addSubNode
	this.addSubNode = function(subNode){										//add subnode method unique
		if( subNode instanceof OptNode ){
			//debug('right instance of OptNode');

			var returnedSubNode = this.nodeByOptNo(subNode.optNo);
			if( returnedSubNode == false){										//If there is exact same item(according to optNo), return false
				//debug('add New');
				this.subNodes.push(subNode);									//If there isn't same item, push given node to the array.

				return this.subNodes[this.subNodes.length-1];
			} else {
				//debug('use exist one');
				return returnedSubNode;
			}
		} else {
			return false;
		}
	};
	////////////////////////

	//method subNodesLength
	this.subNodesLength = function(){											//return length of subitems
		return this.subNodes.length;
	};
	////////////////////////
	
	//method hasSubNode
	this.hasSubNode = function(){
		//debug('sub node length : ' + this.subNodesLength());
		if(this.subNodesLength() > 0)
			return true;
		else
			return false;
	};
	////////////////////////
	
	//mothod nodeByOptNo
	this.nodeByOptNo = function(optNo){
		//debug('finding option no:' + optNo);
		for(var i = 0 ; i < this.subNodes.length ; i++){
			//debug('compare' + this.subNodes[i].optNo + " with " + optNo);
			if(this.subNodes[i].optNo == optNo){
				//debug('find node :' + this.subNodes[i].optNo);
				return this.subNodes[i];										//If there is exact same item(according to optNo), return
			}
		}
		//debug('fail to find node:' + optNo);
		return false;
	};
	/////////////////////////

	this.getNodeByOptNoArray = function(arrOptNo,i){

		if(i < arrOptNo.length){
			var selectedNode = this.nodeByOptNo(arrOptNo[i]);
			return selectedNode.getNodeByOptNoArray(arrOptNo,++i);
		} else 
			return this;
	};

	this.hideAllSubNodes = function(limit){
		if(this.hasSubNode()){
			this.subNodes.each(function(item){
				item.hideNode();
				item.hideAllSubNodes();
			});
		}
	};

	//Show only nodes belong to this object 
	this.showAllSubNodesBut = function(limit){
		this.hideAllOptionsOfSubNode();
		this.showAllSubNodes();
	};	

	this.hideAllOptionsOfSubNode = function(){
		
		//debug('start hiding');

		if(this.childSelBox != undefined){
			//debug('hide all' + this.childSelBox.options.length);

			while(this.childSelBox.options.length > 0){
				//debug('delete' + this.childSelBox.options.length);
				this.childSelBox.options.remove(0);
			}

			if(this.hasSubNode()){
				//debug('subnode deleting...' + this.subNodes[0].optNo);
				this.subNodes[0].hideAllOptionsOfSubNode();
				//debug('subnode deleted');
			}
		}		
	};

	this.showAllSubNodes = function(){
		if(this.hasSubNode()){
			//debug('show subnode...');
			this.subNodes.each(function(item){
				item.showNode();
			});
			//debug('end subnode show..');

			this.subNodes[0].showAllSubNodes();
		}
	};

	this.showNode = function(){
		//this.selOption.style.color="blue";
		//this.selOption.color = "auto";
		var oNode = document.createElement("option");
		
		this.selBox.options.add(oNode);
		oNode.innerHTML = this.innerHTML;
		oNode.value = this.optNo;
		oNode.id = this.id;	

	};
}

///////////
var optionTree = "";
Event.observe(window,'load',
	function(){
		
		//chPriceByOpt($('DETAIL_FORM'));										//페이지가 로딩될때 옵션/셋구성상품에 따른 가격을 계산하여 보여줌		
		
		var tCount = $('subImgCount').value;
		var i=0;
		for(i;i < tCount;i++) {
			var id = "objId"+i;
			Event.observe(id,'mouseover',eventHandler.mOver);//서브이미지 이미지별 핸들러..
		}
		
		optionTree = new OptNode(null); //create root node
		makeOptTree();
		
		//writeTree(optionTree);

		Pkey = $('cbGoodsList').value.replace(",","");
		showStock(Pkey, -1);
	}
);

var eventHandler = { //이벤트 핸들러 주로 ajax 관련해서 변경되는 값들

	mOver: function(event) {	//마우스 오버시..

		obj = $("lastDiv").value;
		if(obj != "") $(obj).style.display = "none";

		var commonLib = new CommonLibary;
		var targetObject = commonLib.GetEventTargetObj(event);
//		imgSrcId = "mImg"+targetObject.getAttribute("id");//		limgSrcId = "lImg"+targetObject.getAttribute("id");//		$('mViewImage').src = $(imgSrcId).value;//		$('nLImg').value = $(limgSrcId).value;
		divImg = "div_"+targetObject.getAttribute("id");
		$(divImg).style.display = "";

		$("lastDiv").value = divImg;

		}
}

var imageOperator = {		//이벤트 핸들러 주로 ajax 관련해서 변경되는 값들

	rightArrow: function(event) {	//마우스 오버시..

	var tCount = $('subImgCount').value;
		if( tCount > 4 ) {

			var i=0;
			for(i=0;i < tCount;i++) {
		
			var id = "divobjId"+i;
			if( $(id).style.display != "none") {
			
				var id = "divobjId"+(i+4);
				if($(id)) {
					$(id).style.display = "block";

					var id = "divobjId"+i;
					$(id).style.display = "none";
					
					break;
					}
				}
			}

		}

		},

	leftArrow: function(event) {	//마우스 오버시..
	var tCount = $('subImgCount').value;
			if( tCount > 4 ) {
				var i=0;
				for(i=0;i < tCount;i++) {
			
				var id = "divobjId"+(tCount-i-1);
					if( $(id).style.display != "none") {
							
					var id = "divobjId"+(tCount-i-4-1);
					if($(id)) {
						$(id).style.display = "block";

						var id = "divobjId"+(tCount-i-1);
						$(id).style.display = "none";
						
						break;
						}
					}
				}
		
			}

		}
}


//즉시구매하기
function buyNowInDetail(){
	if($('prohibit_order').value=="Y"){
		alert('온라인에서 주문할 수 없는 상품입니다. 고객센터 콜센터를 이용하여 주문해주시기 바랍니다.');
	} else {
		var objForm = $('DETAIL_FORM');

		objForm.action= $('domain').value + '/shop/shop_order.html';
		objForm.submit();
	}
}




//하나씩 증가시키는 스핀 에디터
function incCount(obj,obj2, pn){
	var val;
	val = parseInt(obj.value);

	if (pn=="p"){		
		val += 1;		
	} 
	else{
		if (val > 1){
			val -= 1;
		}		
	}	
	obj.value = val;
	obj2.value = val;

}

//
function setOptionSel(form, Pkey, optNums){	
	var numb = 0;
	var arrOptNums = optNums.split("_");	

	var objSel = form["SEL_OPTION_" + Pkey + "[]"];

	if(objSel != undefined){
		for(numb=0 ; numb < arrOptNums.length ; numb++){
			for(i=0; i<objSel[numb].length ; i++){
				if(objSel[numb][i].value == arrOptNums[numb]){
					objSel[numb][i].selected = true;
					break;
				}
			}
		}
	}
}



//옵션에 따라 값을 변하게 만드는 함수
//chPriceBySet(document.DETAIL_FORM,'sell_price_base','{.name}','sell_price','form_price', 'dis_price_span', 'cpn_price')"
function chPriceByOptOld(form){

	Pkey = $('cbGoodsList').value.replace(",","");

	if($("prohibit_order").value != "Y"){ //주문 불가능이 아닐 경우만
		
		var optPrice=0;															//옵션추가가격
		var optDlvPirce=0;														//옵션추가배송비	
		var setPrice = 0;														//셑 추가가격
		var ordPrice = 0;														//주문가격
		var couponPrice = 0;													//쿠폰할인가
		var cateDisPrice = $("cate_dis_amt").value;								//분류이벤트 할인금액
		var classDisPrice = $("class_dis_amt").value;							//회원 등급별 할인금액

		var optionObj = form["SEL_OPTION_" + Pkey + "[]"];						//옵션선택 셀렉션 박스 배열(0..n
		var setObj = form["SEL_SET_" + Pkey + "[]"];							//셑 선택 셀렉션 박스 배열(0..n)		
		var selOptName = "";													
		
		basePrice = toNumber($("sell_price_base").value);						//기본값(판매가) 할당		
		calcCpnPrice(form,basePrice);											//쿠폰가 계산(초기는 없기때문에 무시될 것임-쿠폰 다운로드 후 적용됨)
		couponPrice = toNumber($('cpn_price').value);							//쿠폰가격할당

		//옵션상품 추가금액 산정
		if(optionObj != undefined){			
			if(optionObj[0].name == undefined){
				//하나일 경우				
				optPrice += toNumber($("__OPT" + optionObj.value).value);		//옵션 추가 가격 합산
				optDlvPirce += toNumber($("__OPT_DLV" + optionObj.value).value);//옵션 추가 배송비 합산
				selOptName = optionObj.value;									//선택된 옵션 할당
				
			} else {
				//여러개인 경우
				for(i=0; i < optionObj.length; i++){			
					//___OPT는 class.Option.php에서 붙인 값
					//alert(form["__OPT" + optionObj[i].value].value);

					optPrice += toNumber($("__OPT" + optionObj[i].value).value);		//옵션추가가격 합산
					optDlvPirce += toNumber($("__OPT_DLV" + optionObj[i].value).value);	//옵션추가배송비 합산
					
					if(selOptName != "") selOptName += "_";						//선택된 옵션 문자열 합치기 "_"구분자
					selOptName += optionObj[i].value;
				}
			}
			
			showStock(Pkey, selOptName);										//옵션이 있는 경우의 재고수량 표시

		} else {
			showStock(Pkey, selOptName);										//옵션이 없는 경우의 재고수량 표시
			ordPrice = 0;
		}

		ordPrice = basePrice  + optPrice ;										//판매가 계산(판매가 + 옵션추가가격)

		$("sell_price").innerText = toMoney(ordPrice);

		//옵션이 있는 경우만
		if(optionObj != undefined){
			if(optPrice > 0){
				$("form_price").innerText = "( = " + form["sell_price_base"].value + " + " + toMoney(optPrice) + ")";
				$("oPrice").value = toMoney(optPrice);
			} else {
				$("form_price").innerText = "";
			}
		}

		$("set_price").innerText = toMoney(setPrice);
		
		//할인금액이 이 단계에서 먼저 설정되어야 함
		dPrice = ordPrice - couponPrice - cateDisPrice - classDisPrice; //추가 - cateDisPrice
		dPriceWC = ordPrice - cateDisPrice - classDisPrice; //쿠폰 제외한 할인금액 쿠폰할인금액은 주문페이지에서 주문할 때 적용되므로
		$("dPrice").value = toMoney(dPrice);

		$("dis_price_span").innerText = toMoney(dPrice); //할인금액 = 주문금액 - 쿠폰사용금액 - 카테고리 할인 금액
		//셋상품이 있는 경우만
		//(아래 final_price과는 가격이 다름, 왜냐하면 쿠폰할인가격은 주문할 때 적용되므로 주문페이지에 넘겨줄 실제 상품 가격은 쿠폰
		//할인금액을 제외한 금액인울 final_price에 입력
		if (setObj != undefined){
			$("final_price_span").innerText = toMoney(dPrice + setPrice ); //최종금액 = 할인금액 + 셋 상품 금액 
		}
		
		//최종가격 hidden테그에 저장
		$("final_price").value = toMoney(dPriceWC + setPrice); //최종금액 = 할인금액(쿠폰제외) + 셋 상품 금액 (실제 주문할 때 상품가격으로 적용됨)
		$("total_price").value = toMoney(ordPrice + setPrice);	//총금액
		
		if($("delivery_cost") != null){ //배송비 표시일 경우
			if(toMoney(toNumber($("base_delivery_cost").value) + optDlvPirce)==0){
				$("delivery_cost").innerText = "무료";
			} else {
				$("delivery_cost").innerText = toMoney(toNumber($("base_delivery_cost").value) + optDlvPirce) + "원";
			}			
		}
	}
}


//New 가격 변경 함수

function chPriceByOpt(id){

	var order = id.split(";")[1];												//depth if it has relations
	Pkey = $('cbGoodsList').value.replace(",","");
	var sumupPrice = 0;															//구매가격합계
	var sumupDisPrice = 0;															//할인가격합계
	var optPrice=0;																//옵션추가가격
	var optDlvPirce=0;															//옵션추가배송비	
	var setPrice = 0;															//셑 추가가격
	var cateDisAmt = 0;
	var classDisAmt = 0;
	var couponDisAmt = 0;														//쿠폰할인가
	var disscountedPrice = 0;
	var sumupNotice = "";														//판매가 구성 안내 표시
	var sumupNoticeTitle = "";													//판매가 구성 안내 표시 타이틀
	var priceCount = 0;

	var ordPrice = 0;															//주문가격

	basePrice = toNumber($("sell_price_base").value);							//기본값(판매가) 할당

	if($("prohibit_order").value != "Y"){ //주문 불가능이 아닐 경우만
		
										
		showStock(Pkey, order);								//재고보여주기 위해 저장할 옵션 번호들

		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//옵션상품 추가금액 산정////////////////////////////////////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if($("goods_info")!="undefined"){
			var optionObj = $("goods_info").getElementsByTagName('select');			
			if(optionObj != undefined){				
				for(i=0; i < optionObj.length; i++){
					if(optionObj[i].value!="noselect"){
						optPrice += toNumber($("__OPT" + optionObj[i].value).value);									//옵션추가가격 합산
						optDlvPirce += toNumber($("__OPT_DLV" + optionObj[i].value).value);								//옵션추가배송비 합산					
					}
				}
			}
		}
		//debug("option price(/delivery) : " + optPrice + "/" + optDlvPirce);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//셋상품 추가가 계산////////////////////////////////////////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if($("set_goods")!=undefined){
			var setObj = $("set_goods").getElementsByTagName('select');   

			if (setObj != undefined){

				
				//셋상품 추가 금액 산정/////////////////////////////////////////////
				for(i=0; i < setObj.length; i++){		
					setPrice += toNumber($("__SET" + setObj[i].value).value);	//셋상품 가격합산
				}

				//셋 구성상품 이미지 변경///////////////////////////////////////////

				if(event!=undefined && event.srcElement != undefined){
					if(event.srcElement.id.substr(0,8) == "SEL_SET_"){ //셋 상품 항목이 변경되었을 때만
						var objSel = event.srcElement;
						var imgId = "_IMG_" + event.srcElement.id;

						$(imgId).src = 	$("__SET_IMG" + event.srcElement.value).value;

						for(i=0 ; i<objSel.options.length; i++){
							if(objSel.options[i].selected){
								$(imgId).alt = objSel.options[i].text;
								break;
							}
						}
					}
				}
			}
			//alert("set price : " + setPrice);
		}
		sumupPrice = basePrice + setPrice + optPrice; //구매가격=상품가격 + 세트상품추가가격 + 옵션 추가가격

		priceCount += (basePrice > 0);
		priceCount += (optPrice > 0);
		priceCount += (setPrice > 0);
	
		
		if(priceCount >= 2) { //가격이 두개 이상 합산이 된 경우
			sumupNotice = "(="+ ((basePrice>0)?toMoney(basePrice):"") + ((optPrice>0)? "+" + toMoney(optPrice) :"") + ((setPrice>0)? "+" + toMoney(setPrice):"") + ")";
			sumupNoticeTitle = "(="+ ((basePrice>0)?"판매가":"") + ((optPrice>0)? "+" + "옵션추가가" :"") + ((setPrice>0)? "+" + "세트상품추가가":"") + ")";
		}
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//분류별 할인가 계산////////////////////////////////////////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if($('goods_discount') != undefined && $('goods_discount').value > 0){
			switch($('goods_discount_unit').value){
				case "percent":						
						cateDisAmt = Math.round(sumupPrice * $('goods_discount').value / 100);
					break;
				case "won":
						cateDisAmt = $('goods_discount').value
					break;
			}
		}
		//(1) 할인가 = 판매가 - 분류별 이벤트할인 
		disscountedPrice = sumupPrice - cateDisAmt;
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//회원등급별 할인가 계산////////////////////////////////////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
		if($('add_discount_rate') != undefined && $('add_discount_rate').value > 0){
			classDisAmt = Math.round(disscountedPrice * $('add_discount_rate').value / 100);
		}	
		//(2) 할인가 = 할인가(분류별할인적용) - 회원등급별 할인금액
		disscountedPrice = disscountedPrice - classDisAmt; 
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//쿠폰할인가 계산///////////////////////////////////////////////////////////////////////////////////////////////
		
		calcCpnPrice(disscountedPrice);											//쿠폰가 계산(초기는 없기때문에 무시될 것임-쿠폰 다운로드 후 적용됨)
		couponDisAmt = toNumber($('cpn_price').value);							//쿠폰가격할당
		//(3) 할인가 = 할인가(분류별할인적용 + 회원등급별 할인적용) - 쿠폰할인가
		disscountedPrice = disscountedPrice - couponDisAmt;
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//금액 표시/////////////////////////////////////////////////////////////////////////////////////////////////////
		////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		sumupDisPrice = cateDisAmt + classDisAmt + couponDisAmt; //할인금액은 = 분류별 이벤트 할인 + 회원등급별 할인

		if($('sumup_price') != undefined) $('sumup_price').innerHTML = toMoney(sumupPrice) + '원';						//판매가 표시
		if($('sumup_notice') != undefined) $('sumup_notice').innerHTML = sumupNotice;									//판매가 구성항목 표시
		if($('sumup_notice') != undefined) $('sumup_notice').title = sumupNoticeTitle;									//판매가 구성항목 표시 타이틀
		if($('discount_price') != undefined) $('discount_price').innerHTML = toMoney(disscountedPrice) + '원';	//할인가 표시
		if($('final_price') != undefined) $('final_price').innerHTML = toMoney(disscountedPrice) + '원';				//최종판매금액 표시
		
		$('options_price').value = optPrice;									//옵션추가가 표시
		$('sets_price').value = setPrice;										//세트상품추가가 표시

		$('cate_dis_amt').value = cateDisAmt;									//분류별 할인 금액
		$('class_dis_amt').value = classDisAmt;									//회원 등급별 할인 금액

		
	}
}



//재고표시함수
function showStock(PKey, order){

	if(optionTree && optionTree.subNodes[0] && order == -1){		
		order = optionTree.subNodes[0].selBox.id.split(";")[1];
	}
	
	if($("SEL_OPTION_" + Pkey + "[];" + order + ";Y") != undefined){

		//debug("order:" + order + " /// " + "start show stock" + "SEL_OPTION_" + Pkey + "[];" + order + ";Y");

		var arrSelOptVal = new Array();
		
		var j = 0;

		for(var i = 0 ; i <= order ; i++){
			if($("SEL_OPTION_" + Pkey + "[];" + i + ";Y") != undefined){
				arrSelOptVal[j++] = $("SEL_OPTION_" + Pkey + "[];" + i + ";Y").value;
			}
		}

		//debug(arrSelOptVal);

		var selectedNode = optionTree.getNodeByOptNoArray(arrSelOptVal,0);

		//debug('rearrange...');
		selectedNode.showAllSubNodesBut();
		//debug('End of rearrange...');
	


		//재고수량 표시///////////////////////////////////
		//옵션키조합 만들기
		var arrSel = $A($("goods_info").getElementsByTagName('select'));

		//debug('seloptname making' + arrSel);

		if(arrSel != undefined){

			var selOptName = "";

			for(var i = 0; i < arrSel.length; i++){
				if(arrSel[i].id.split(";")[2] == "Y"){
					if(selOptName != "") selOptName += "_";	
					selOptName += arrSel[i].value;
				}
			}
		}
		///////////////////////////////////////////////////

		
		//재고 표시
		//debug('stock quantity('+selOptName+'):');
		//debug('qty'+$("__stk_qtt__" + selOptName).value);

		if($("__stk_qtt__" + selOptName) == undefined){								//아예재고가 없는 경우
			if($('stock_quantity') != undefined){
				$('stock_quantity_label').hide();
				$('stock_quantity').hide();
			}
		} else {																	//재고가 있는 경우
			
			if($('stock_quantity') != undefined){
				if(toNumber($("__stk_qtt__" + selOptName).value)==0)
					$("stock_quantity").innerText = ": 품절";
				else
					$("stock_quantity").innerText = ": " + $("__stk_qtt__" + selOptName).value; //재고번호로 재고수량 설정

				$('stock_quantity_label').show();
				$('stock_quantity').show();
			}
		}
	} else {
		//debug('not sock related');
	}
}
function makeOptTree(){

	var stkHdObj = $A($('stock_quantity_hidden_layer__').getElementsByTagName("input"));

	stkHdObj.each(function(value){		
		var arrOptCombi = value.id.split("_");									//hide all options first

		for(i=0; i < 5 ; i++){													//eliminate unnecesarry elements using shif method of array
			arrOptCombi.shift();
		}

		treeNode = new OptNode(arrOptCombi[0]);									//create new node		
		cascadeConvert(optionTree.addSubNode(treeNode),arrOptCombi,1);	

	});
}

function cascadeConvert(parentNode, arrCombi, i){
	if(i < arrCombi.length){
		var treeNode = new OptNode(arrCombi[i]); //create node
		cascadeConvert(parentNode.addSubNode(treeNode), arrCombi, ++i);
	}
}

function writeTree(tree, i){
	var txt = "";
	var j=0;
	
	tree.subNodes.each(function(value){
		txt = "";

		if(j==0)
			txt = "";
		else {
			txt = "<br />";
		}
		
		for(k=0 ; k < i ; k++)
			txt += "|-----";

		if(j != 0)
			txt += "--";
		else 
			txt += "=>";

		txt += value.innerHTML + "(" + value.optNo + ")";

		debug(txt, false);

		if(value.hasSubNode()){
			writeTree(value, i+1);
		}

		j++;
	});
}


function calcCpnPrice(basePrice){
	
	var disAmt = 0;
	var comm = "";
	//var discountedAmt = 0;
	if($('coupon_notice')!=undefined)
		$('coupon_notice').innerText = "";

	var minPrc = toNumber($('min_price').value);										//최소주문금액
	var maxDsc = toNumber($('max_discount').value);										//최대할인금액

	

	if(basePrice >= minPrc || minPrc==0){

		if($('cpn_dis_unit').value == "%"){ //할인률
				
			disAmt = Math.round(basePrice * $('cpn_dis_val').value / 100);	
			
			//discountedAmt = basePrice - disAmt;

			
		} else if ($('cpn_dis_unit').value == "W"){ //할인액
			disAmt = toNumber($('cpn_dis_val').value);
			//discountedAmt = basePrice - disAmt;
		}

		if(maxDsc > 0){
			if(disAmt > maxDsc){
				disAmt = maxDsc;
				if($('cpn_attr').value!=""){
					if($('coupon_notice')!=undefined)
						$('coupon_notice').innerText = " ※최대할인가 적용";
				}else{
					if($('coupon_notice')!=undefined)
						$('coupon_notice').innerText = "";
				}
			}
		}

	} else {
		disAmt = 0;
		if($('cpn_attr').value!=""){
			if($('coupon_notice')!=undefined)
				$('coupon_notice').innerText = " ※최소판매가 미달";
		}else{
			if($('coupon_notice')!=undefined)
				$('coupon_notice').innerText = "";
		}
	}


	if($('cpn_attr').value == "discnt"){ //할인
		$('cpn_price').value = disAmt;
		comm = "(" + toMoney(disAmt) + " 원 할인)";
		

		
	} else if($('cpn_attr').value == "save"){ //적립
		$('cpn_price').value = 0;
		comm = "(" + toMoney(disAmt) + " 원 추가적립)";

	} else { //없음

		comm = "";

	}
	if($('coupon_notice')!=undefined)
		$("coupon_notice").innerText = comm;

	//$(dis_price_span).innerText = toMoney(discountedAmt);	
	
}



//장바구니 담기
function storeCartInDetail(){
	var objForm = document.DETAIL_FORM;

	objForm.action='../process/cart_process.php';
	objForm.submit();

}

//상품 찜하기
function storeWLInDetail(){
	var objForm = document.DETAIL_FORM;

	objForm.action='../mypage/mypage_wish.html';
	objForm.submit();
}

function toMoney(val){
	var i = 0;
	var temp = "";
	val += ""; //문자열로 변환

	var ctr = val.length-1;
	for (i = ctr ;i >= 0; i--){
		if (((i-ctr)%3 == 0) && (i!=ctr)){
			temp = "," + temp;
		}
		temp = val.charAt(i) + temp;
	}

	return temp;
}

function toNumber(val){
	var tmp = val.replace(/,/g,"");
	var rtn = parseInt(tmp);
	if(isNaN(rtn))
		return "";
	else
		return rtn;
}