﻿// 초기 변수 설정
var OrderControl = {
	getProductName: function() {
		var i = document.f1.productSeq.selectedIndex;
		return document.f1.productSeq.options[i].text;
	},
	
	getPrice: function() {
		var productSeq = document.f1.productSeq.value;
		var productName = this.getProductName();
		
		$('productName').innerHTML = productName;

		document.f1.productType.value = this.getProductType(productSeq);
		document.f1.productSubType.value = this.getProductSubType(productSeq);
		
		var productSubType = document.f1.productSubType.value;
		var productType = document.f1.productType.value;
		
		if (productSeq <= 3) {
			$('quantity').length = 1;
		} else {
			if ($('quantity').length==1) {
				for (var i=2;i<=10;i++) {
					SelectBoxOptionAdd($('quantity'), i , i);
				}
			}
		}
		
		if (productSubType == 2) {
			this.skinHide();
		}
		
		var albumSeqs = arrayToString(document.f1.albumSeqs);
		var quantity = $('quantity').value;
		
		var deliveryOption = GetRadioValue(document.f1.option3);
		
		// Ajax Call
		var param = 'cmd=getOrderAmount' +
			'&productType=' + productType +
			'&productSubType=' + productSubType +
			'&albumSeqs=' + albumSeqs +
			'&quantity=' + quantity +
			'&deliveryOption=' + deliveryOption +
			'&_uid=' + (new Date()).getTime();
			
		var url = '/main/shop/order';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				var rst = xmlHttp.responseText.trim();
				OrderControl.printPrice(rst);
			},
			onFailure: function(xmlHttp) {
				alert('서버에 응답이 없습니다. 잠시 후 다시 시도해주세요.');
			}
		});
	},
	// 2009-07-21 : cmhan 
	getGoodsPrice: function() {
		var productName = this.getProductName();		
		var productSeq = $('productSeq').value;
		var quantity = $('quantity').value;
		
		document.f1.productType.value = this.getProductType(productSeq);
		document.f1.productSubType.value = this.getProductSubType(productSeq);
		
		if (productSeq <= 3) {
			$('quantity').length = 1;
		} else {
			if ($('quantity').length==1) {
				for (var i=2;i<=10;i++) {
					SelectBoxOptionAdd($('quantity'), i , i);
				}
			}
		}	
		$('productName').innerHTML = productName;		
		// Ajax Call
		var param = 'cmd=getGoodsAmount' +
			'&productSeq=' + productSeq + 
			'&quantity=' + quantity +
			'&_uid=' + (new Date()).getTime();
			
		var url = '/main/shop/order';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				var rst = xmlHttp.responseText.trim(); 
				OrderControl.printPrice(rst);
			},
			onFailure: function(xmlHttp) {
				alert('서버에 응답이 없습니다. 잠시 후 다시 시도해주세요.');
			}
		});
	},
	
	
	getProductType: function(productSeq) {
		var productType = 1;
		if (productSeq == 1 || productSeq == 2 || productSeq == 3) {
			productType = 1;
		} else if (productSeq == 4 || productSeq == 5 || productSeq == 6) {
			productType = 2;
		} else if (productSeq == 7 || productSeq == 8 || productSeq == 9) {
			productType = 3;
		} else if(productSeq == 10){
			productType = 4;
		}
		
		return productType;
	},
	
	getProductSubType: function(productSeq) {
		var getProductSubType = 1;
		if (productSeq == 1 || productSeq == 4 || productSeq == 7) {
			getProductSubType = 1;
		} else if (productSeq == 2 || productSeq == 5 || productSeq == 8) {
			getProductSubType = 2;
		} else if (productSeq == 3 || productSeq == 6 || productSeq == 9) {
			getProductSubType = 3;
		} else if (productSeq == 10) {
			getProductSubType = 4;
		}
		return getProductSubType;
	},
	
	setDeliveryAmount: function(deliveryOption) {
		if (deliveryOption == 1) {
			$('msgDeliveryAdd').style.display = 'block';
			$('deliveryDiv').style.display = 'block';
		} else if (deliveryOption == 2) {
			$('msgDeliveryAdd').style.display = 'none';
			$('deliveryDiv').style.display = 'none';
		}
		
		this.getPrice();
	},
	
	setOption: function(productSeq) {
		var productType = document.f1.productType.value = this.getProductType(productSeq);
		var productSubType = document.f1.productSubType.value = this.getProductSubType(productSeq);
		
		this.hideTitleDescription();
		
		if (productType == 1) { // 내PC에 저장일 경우
			$('deliveryOptionDiv').style.display = 'none';
			$('option3_2').checked = true;
			$('msgDeliveryAdd').style.display = 'none';
			$('deliveryDiv').style.display = 'none';
			$('optionDiv01').style.display = 'none';
			$('titleDescriptionPc').style.display = 'block';
		} else if (productType == 2) { // cd
			$('deliveryOptionDiv').style.display = 'block';
			$('option3_1').checked = true;
			$('msgDeliveryAdd').style.display = 'block';
			$('deliveryDiv').style.display = 'block';
			$('optionDiv01').style.display = 'block';
			$('titleDescriptionCd').style.display = 'block';
		} else { // dvd
			$('deliveryOptionDiv').style.display = 'block';
			$('option3_1').checked = true;
			$('msgDeliveryAdd').style.display = 'block';
			$('deliveryDiv').style.display = 'block';
			$('optionDiv01').style.display = 'block';
			$('titleDescriptionDvd').style.display = 'block';
			$('option1_play1').checked = true;
		}
	
		if (productSubType == 2) { // flash 없을 때
			this.skinHide();
			$('pcSampleDiv').style.display = 'none';
			if (productType == 3) {
				$('movieSampleDiv').style.display = 'none';
				$('dvdSampleDiv').style.display = 'block';
			} else {
				$('movieSampleDiv').style.display = 'block';
				$('dvdSampleDiv').style.display = 'none';
				$('option1_avi').checked = true;
			}
			$('skinDiv').style.display = 'none';
		} else {
			this.skinShow();
			$('pcSampleDiv').style.display = 'block';
			$('movieSampleDiv').style.display = 'none';
			$('dvdSampleDiv').style.display = 'none';
			$('skinDiv').style.display = 'block';
		}
		
		if (productType == 1 && productSubType == 2) { // 동영상 email 받기 일 경우 Email 주소 입력 창 출력, 전체 제목 출력 안함.
			$('titleDiv').style.display = 'none';
			$('emailDiv').style.display = 'block';
		} else {
			$('titleDiv').style.display = 'block';
			$('emailDiv').style.display = 'none';
		}
	},
	
	hideTitleDescription: function() {
		$('titleDescriptionPc').style.display = 'none';
		$('titleDescriptionCd').style.display = 'none';
		$('titleDescriptionDvd').style.display = 'none';
	},
	
	skinShowHide: function() {
		if ($('openingDiv').style.display == 'none') {
			var productType = document.f1.productType.value;
			var productSubType = document.f1.productSubType.value;
			
			if (productSubType == 2) {
				this.skinHide();
				alert('"DVD 제작" 상품은 스킨을 선택할 필요가 없습니다.');
				
			} else {
				this.skinShow();
			}		
		} else {
			this.skinHide();
		}
	},

	skinShow: function() {
		$('openingDiv').style.display='block';
		$('btnOpeningDiv').src='/image/mypepbox/btn_skin_up.gif';
	},
		
	skinHide: function() {
		$('openingDiv').style.display='none';
		$('btnOpeningDiv').src='/image/mypepbox/btn_skin_down.gif';
	},
	
	printPrice: function(amount) {
		var quantity = $('quantity').value;
		
		quantity = parseInt(quantity,10);

		if (isNaN(quantity) || quantity <= 0) {
			quantity = 1;
		}
		
		var productType = document.f1.productType.value;
		
		if (productType == 1 && quantity > 1) {
			alert('"PC 저장하기" 상품은 수량을 1개만 선택 가능합니다.');
			$('quantity').selectedIndex = 0;
			quantity = 1;
		}
		
		$('amount').innerHTML = Comma(amount);
	},
	
	preview: function() {
		
		var albumSeqs = this.makePreviewStringAlbumSeq($('f1').albumSeqs);
		var albumTitle = $('album_title').value;
		var openingSeq = GetRadioValue(document.f1.openingSeq);
		var skinPath = $('openUrl' + openingSeq).value;
		
		var url = '/main/order/popPcSavePreview.jsp?'
			+ 'albumSeq=' + albumSeqs
			+ '&skinPath=' + skinPath
			+ '&albumTitle=' + encodeURIComponent(albumTitle);
		
		GlobalPopup.PopWindow(url,'preview', '', '1004','698','true');
	},

	popMovieSample: function() {
		GlobalPopup.popMovieSample();
	},
	
	popDvdSample: function() {
		GlobalPopup.popDvdSample();
	},
	
	popStyleSample: function(styleSeq) {
		var url = "./popStyleSample.jsp?styleSeq="+styleSeq;
		GlobalPopup.PopWindow(url,'popStyleSample', '', '452','471','true');
	},
	
	makePreviewStringAlbumSeq: function(obj) {
		var result = '';
		if(obj.length){
			for (var i=0;i<obj.length;i++) {
				result = result + obj[i].value + ';';
			}
		} else {
			result = obj.value + ';';
		}
		return result;
	}, 
	
	downloadAblum: function(orderSeq) {
		GlobalPopup.PopWindow('/main/center/albumDownload.jsp?orderSeq=' + orderSeq + '&_uid=' + (new Date()).getTime(),'application', '', '458','386','true');
	},
	
	applyCoupon: function (seq) {
		if (seq > 0) {
			// Ajax Call
			var param = 'cmd=getMyCoupon'
				+ '&seq=' + seq
				+ '&_uid=' + (new Date()).getTime();
			
			var url = '/main/shop/couponServlet';
			new Ajax.Request(url, {
				parameters: param,
				onSuccess: function(xmlHttp) {
					var xml = xmlHttp.responseXML;	
					var record_data = xml.getElementsByTagName("record");
					
					if(record_data){
						var row = 0;
						for(row=0;row<record_data.length;row++){
							
							if (record_data.item(row).hasChildNodes())
							{
								var rows = record_data.item(row);
								var seq = GetValue(rows, "seq");
								var couponSeq = GetValue(rows, "coupon_seq");
								var title = GetValue(rows, "title");
								var discountMethod = GetValue(rows, "discount_method");
								var discountAmount = GetValue(rows, "discount_amount");
								var minPayAmount = GetValue(rows, "min_pay_amount");
								
								if (couponSeq == 36) { // 맘스다이어리 특별 할인 쿠폰 : 1개의 앨범에 대해서만 할인 됨.
									OrderControl.calCouponForOnlyOneAlbum(discountMethod, discountAmount, minPayAmount);
								} else {
									OrderControl.calCoupon(discountMethod, discountAmount, minPayAmount);
								}
							}
						}
						
						if (row == 0) {
							alert('사용할 수 없는 쿠폰입니다.');
							return;
						}
					}
				},
				onFailure: function(xmlHttp) {
					alert('서버 연결에 실패했습니다. 다시 이용해 주세요.');
				}
			});
		} else {
			this.calCoupon(1, 0, 0);
		}
	},
	
	calCouponForOnlyOneAlbum: function() {
		// 무조건 100% 처리
		
		var maxPricePerAlbum = $('maxPricePerAlbum').value.toNumber(); // 예외 처리 쿠폰의 할인 금액 계산용 임시 변수
		var amount = $('amount').value.toNumber();
		var deliveryAmount = $('deliveryAmount').value.toNumber();
		var couponAmount = maxPricePerAlbum;
		
		var realAmount = amount - maxPricePerAlbum;
		
		if (realAmount < 0) {
			realAmount = 0;
			couponAmount = amount;
		}
		
		if ($('albumCount').value > 1) {
			alert('- 본 쿠폰은 여러 앨범 중 1개  앨범만 할인을 받습니다.\n\n' 
				+ '- 할인 받는 앨범은 최고가 스타일을 적용한 앨범입니다.'); 
		}
		
		$('couponAmount').value = couponAmount;
		$('good_mny').value = realAmount + deliveryAmount;
		$('realAmount').innerHTML = Comma(realAmount + deliveryAmount);
		
		if (realAmount + deliveryAmount == 0) {
			this.msgDisplay('noPay');
		} else {
			this.msgDisplay('default');
		}
	},
	
	calCoupon: function(discountMethod, discountAmount, minPayAmount) {
		var amount = $('amount').value.toNumber();
		var couponAmount = 0;
		var deliveryAmount = $('deliveryAmount').value.toNumber();
		
		if (minPayAmount > 0 && minPayAmount > amount) {
			alert('선택하신 쿠폰은 주문 금액이 ' + minPayAmount + ' 이상인 경우에 사용할 수 있습니다. 다른 쿠폰을 사용해주세요.');
			$('memberCouponSeq').selectedIndex = 0;
			calCoupon(1, 0, 0);
			return;
		}
		
		if (discountMethod == 1) { // 금액
			couponAmount = discountAmount;
		} else {
			couponAmount = amount * (discountAmount/100);
		}
		
		var realAmount = amount - couponAmount;
		
		if (realAmount < 0) {
			realAmount = 0;
			couponAmount = amount;
		}
		
		$('couponAmount').value = couponAmount;
		$('good_mny').value = realAmount + deliveryAmount;
		$('realAmount').innerHTML = Comma(realAmount + deliveryAmount);
		
		if (realAmount + deliveryAmount == 0) {
			this.msgDisplay('noPay');
		} else {
			this.msgDisplay('default');
		}
	},
	
	
	msgDisplay: function(val) {
		if (val == 'default') {
			$('msgDefault').style.display = 'block';
			$('msgNoPay').style.display = 'none';
		} else {
			$('msgDefault').style.display = 'none';
			$('msgNoPay').style.display = 'block';		
		}
	},
	
	callMakeZip: function(orderSeq) {
		// Ajax Call
		var param = 'cmd=makeZip'
			+ '&orderSeq=' + orderSeq
			+ '&_uid=' + (new Date()).getTime();
		
		var url = '/pepbox-cms/cdservice/cdService.html';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				var rst = xmlHttp.responseText.trim();
			},
			onFailure: function(xmlHttp) {
				alert('서버 연결에 실패했습니다. 다시 이용해 주세요.');
			}
		});
	},
	
	setMemberInfo: function() {
		$('receiverName').value = $('memberName').value;
		$('receiverPhone1_1').value = $('cellphone_1').value;
		$('receiverPhone1_2').value = $('cellphone_2').value;
		$('receiverPhone1_3').value = $('cellphone_3').value;
	},
	
	timerCheckOrderZipFileState: function () {
		setTimeout("OrderControl.checkOrderZipFileState()", 2000);
		_timerCheckOrderZipFileState = setInterval("OrderControl.checkOrderZipFileState()", 10000); 
	},
	
	checkOrderZipFileState: function () {
		
		if (isDownReady) {
			clearTimeout(_timerCheckOrderZipFileState);
			return;
		}
		
		// Ajax Call
		var param = 'cmd=getFlashZipFileState'
			+ '&orderSeq=' + orderSeq
			+ '&_uid=' + (new Date()).getTime();
		
		var url = '/pepbox-cms/cdservice/cdService.html';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				var rst = xmlHttp.responseText.trim();
				
				if (rst == '2') {
					// zip 파일 생성 완료 , 다운로드 가능
					$('downloadLink').innerHTML = '<img src="../../image/mypepbox/title_down.gif" width="745" height="98"><br /><a href="/main/order/orderZipFileDownLoad?orderSeq=' + orderSeq + '" target="_blank"><img src="../../image/mypepbox/btn_flash_down.gif" width="202" height="39" border="0"></a>';
					isDownReady = true;
				} else if (rst == '1') {
					// zip 파일 생성 중
					$('downloadLink').innerHTML = '<img src="/image/common/loading_l.gif" vspace="40"/><br />잠시만 기다려 주세요. 주문하신 앨범량에 따라 1분에서 최대 10분정도 소요 될 수 있습니다.';
				} else if (rst == '3') {
					// zip 파일 생성 재요청 
					OrderControl.retryOrderZipFile();
					$('downloadLink').innerHTML = '<img src="/image/common/loading_l.gif" vspace="40"/><br />잠시만 기다려 주세요. 주문하신 앨범량에 따라 1분에서 최대 10분정도 소요 될 수 있습니다.';
					isDownReady = true;
				} else {
					$('downloadLink').style.display = 'none';
					$('downloadFail').style.display = 'block';
					isDownReady = true;
				}
			},
			onFailure: function(xmlHttp) {
				alert('서버 연결에 실패했습니다. 다시 이용해 주세요.');
			}
		});
	},
	
	retryOrderZipFile: function () {
		// Ajax Call
		var param = 'cmd=getFlashZipPath'
			+ '&orderSeq=' + orderSeq
			+ '&_uid=' + (new Date()).getTime();
		
		var url = '/pepbox-cms/cdservice/cdService.html';
		new Ajax.Request(url, {
			parameters: param,
			onSuccess: function(xmlHttp) {
				var rst = xmlHttp.responseText.trim();
				
				if (rst == '1') {
					// 요청 완료
					isDownReady = false;
					_timerCheckOrderZipFileState = setInterval("OrderControl.checkOrderZipFileState()", 10000); 
				} else {
					
				}
			},
			onFailure: function(xmlHttp) {
				alert('서버 연결에 실패했습니다. 다시 이용해 주세요.');
			}
		});
	}
}

var _arrWizardStepValue = new Array(0,1,2,2);

var OrderWizard = {
	type : '',
	currentStep : 1,
	
	closeWizardDiv: function() {
		var wizardDiv = $('wizardDiv');
		wizardDiv.style.display = 'none';
		GlobalPopup.showElement('SELECT');
		document.body.removeChild($('GrayBackDiv'));
	},
	
	selStepValue: function(value) {
		var step = this.currentStep;
		
		_arrWizardStepValue[step] = value;
		
		// 화면에 선택된 것 표시
		this.setRadio(value);
	},
	
	setDefaultValue: function() {
		var currentValue = _arrWizardStepValue[this.currentStep];
		
		this.setRadio(currentValue);
	},
	
	setRadio: function(value) {
		var value;
		
		if (this.currentStep == 1) {
			//if (value==1) { // 1
			//	$('btnStep1Next').src = $('btnStep1Next').src.replace('_next.', '_ok.');
			//} else { // 2
			//	$('btnStep1Next').src = $('btnStep1Next').src.replace('_ok.', '_next.');
			//}
				$('btnStep1Next').src = $('btnStep1Next').src.replace('_next.', '_ok.');
		}
		
		if (value==1) { // 1
			$('imgRadio01').src = $('imgRadio01').src.replace('_off.', '_on.', '_off.');
			$('imgRadio02').src = $('imgRadio02').src.replace('_on.', '_off.', '_off.');
			$('imgRadio03').src = $('imgRadio03').src.replace('_on.', '_off.', '_off.');
		} else if (value==2){ // 2
			$('imgRadio01').src = $('imgRadio01').src.replace('_on.', '_off.', '_off.');
			$('imgRadio02').src = $('imgRadio02').src.replace('_off.', '_on.', '_off.');
			$('imgRadio03').src = $('imgRadio03').src.replace('_on.', '_off.', '_off.');
		} else{
			$('imgRadio01').src = $('imgRadio01').src.replace('_on.', '_off.', '_off.');//
			$('imgRadio02').src = $('imgRadio02').src.replace('_on.', '_off.', '_off.');
			$('imgRadio03').src = $('imgRadio03').src.replace('_off.', '_on.', '_off.');
		}
	},
	
	wizardPrev: function() {
		if (this.currentStep == 1) {
			return;
		}
		this.currentStep--;
		this.showStep();
	},
	
	wizardNext: function() {
		var wizardStepValue = _arrWizardStepValue[this.currentStep];
		
		if (this.currentStep == 1) { // DVD 주문
			if (wizardStepValue == 1) {
				this.closeWizardDiv();
				this.setProductSeq(8);
			
			} else if (wizardStepValue == 2){
				this.closeWizardDiv();
				this.setProductSeq(5);
			} else {
				this.closeWizardDiv();
				this.setProductSeq(2);
			}
		}
		
		if (this.currentStep == 2) { // CD 주문, 동영상 받기
		}
		
		if (this.currentStep == 3) {
			var productSeq = 1;
			
			if (_arrWizardStepValue[1] == 1) {
				productSeq = 8;
			} else if (_arrWizardStepValue[2] == 1 && _arrWizardStepValue[3] == 1) { // CD (동영상)
				productSeq = 5;
			} else if (_arrWizardStepValue[2] == 1 && _arrWizardStepValue[3] == 2) { // 동영상 email
				productSeq = 2;
			} else if (_arrWizardStepValue[2] == 2 && _arrWizardStepValue[3] == 1) { // CD (Flash)
				productSeq = 4;
			} else if (_arrWizardStepValue[2] == 2 && _arrWizardStepValue[3] == 2) { // PC 저장하기
				productSeq = 1;
			} else {
				alert('선택 오류.. 있을 수 없는 선택입니다.');
				this.currentStep = 1;
				this.showStep();
				return;
			}
			
			this.setProductSeq(productSeq);
			this.closeWizardDiv();
			return;
		}
		
		this.currentStep++;
		this.showStep();
	},
	
	setProductSeq: function(productSeq) {
		//alert(productSeq);
					
		if (this.type == 'goOrder') {
			CartControl.goOrder(productSeq);
			return;
		}
		
		// 해당 값으로 지정
		var obj = $('productSeq');
		for (var i=0;i<obj.length;i++) {
			if (obj.options[i].value == productSeq) {
				obj.selectedIndex = i;
				break;
			}
		}
		
		OrderControl.setOption(productSeq);
		OrderControl.getPrice();
	},	
	
	showStep: function() {
		$('wizardStep1Div').style.display = 'none';
		$('wizardStep2Div').style.display = 'none';
		$('wizardStep3Div').style.display = 'none';
		$('wizardStep3Div2').style.display = 'none';
		
		if (this.currentStep == 3) {
			if (_arrWizardStepValue[2] == 1) {
				$('wizardStep3Div2').style.display = 'block';
			} else {
				$('wizardStep3Div').style.display = 'block';
			}
		} else {
			$('wizardStep' + this.currentStep + 'Div').style.display = 'block';
		}
		
		// 선택된 기본 값을 보여 준다.
		this.setDefaultValue();
	},
	
	showWizardDiv: function(type) {
		this.type = type;
		this.currentStep = 1;
		
		this.showStep();
		
		var oBody = getBody();
		var oBodyInnerSize = getBodyInnerSize();
		
		GlobalPopup.makeGrayBackDiv();
		
		var windowWidth = 700;
		var windowHeight = 600;
							
		// left, top 계산 : 화면 중앙에 오도록
		var windowTop = Math.floor((oBodyInnerSize.height - windowHeight) / 2);
		if (windowTop <0)
		{
			windowTop = 0;
		}
		
		windowTop = oBody.top + windowTop;

		var windowLeft = Math.floor((oBodyInnerSize.width - windowWidth) / 2);
		if (windowLeft <0)
		{
			windowLeft = 0;
		}
		
		var wizardDiv = $('wizardDiv');
				
		wizardDiv.style.top = windowTop + 'px';
		wizardDiv.style.left = windowLeft + 'px';
		wizardDiv.style.width = windowWidth + 'px';
		wizardDiv.style.height = windowHeight + 'px';
		wizardDiv.style.zIndex = '500000';
		wizardDiv.style.display = 'block';
	}
}