/*
function showTicketTypeTable( handle ){
    UI.$("table_"+handle.currentTab.tab.keyword).style.display = "";
    if( handle.prevTab.tab && handle.prevTab.tab.keyword != handle.currentTab.tab.keyword ){ 
       UI.hide("table_"+handle.prevTab.tab.keyword);
    }
    selectItemFocus();
    
    //ticketCon.clearItemSelect();
}*/

function purchase( formName ) {
    var radio = document[formName].ticket;
    var itemId = null;
    for( var i=0,cnt=radio.length; i<cnt; i++ ){
        if( radio[i].checked == true ){
            itemId = radio[i].value;
        }
    }
    if( itemId == null ){
        alert("이용권을 선택해 주세요");
    } else {
        //UI.Popup("/ticket/purchaseform.do?itemId="+itemId, "purchaseTicket", "width=629, height=600, scrollbars=no, resizable=no");
        Music.newWin("/ticket/purchaseform.do?itemId="+itemId, "purchaseTicket", "width=420, height=260, resizable=no, scrollbars=yes");
    }       
    //window.open("/ticket/purchaseform.do", "purchaseTicket", "width=629, height=647, scrollbars=no");
}
function gift( formName ) {
    var radio = document[formName].ticket;
    var itemId = null;
    for( var i=0,cnt=radio.length; i<cnt; i++ ){
        if( radio[i].checked == true ){
            itemId = radio[i].value;
        }
    }
    if( itemId == null ){
        alert("이용권을 선택해 주세요");
    } else {
//        /UI.Popup("/ticket/giftform.do?itemId="+itemId, "purchaseTicket", "width=629, height=600, scrollbars=no, resizable=no");
        Music.newWin("/ticket/giftform.do?itemId="+itemId, "purchaseTicket", "width=420, height=260, resizable=no, scrollbars=yes");
    }
    //window.open("/ticket/giftform.do", "giftTicket", "width=600, height=400, scrollbars=yes");
}

function goGift(){
    var url = "/ticket/giftform.do";
    var param = "?ticketType="+tabTicket.index;
    if( ticketCon.itemId ){
    	param += "&itemId="+ticketCon.itemId;
    }
    location.href=url+param;
}

/*
function selectItemFocus(){
    var conMain = UI.$("conScr");
    var conTable = UI.$("conScrTable");
    var selectedItem = UI.$("row_"+Music.TicketSelectedItemId);
    conTable.scrollTop = selectedItem.offsetTop;
}
*/
/*
function pay() {
    var form = document.ticketFrm;
    if( form ) {
    
        form.method = 'POST';
        if( form.paymentType[2].checked ) {
            // daumcash
            form.action = '/ticket/purchase.do';
        }
        else {
            // BI
            form.action = '/ticket/purchase/preparepaymentIE8.do';
        }
        this.form.method = "post";
        if(this.opt.gift == "no") {
            if(this.opt.how == "mp3") this.form.action = "/purchase/mp3purchase.do";
            else this.form.action = "/purchase/bgmpurchase.do";
        } else {
            if(this.opt.how == "mp3") this.form.action = "/purchase/mp3gift.do";
            else this.form.action = "/purchase/bgmgift.do";
        }
        this.form.submit();
        
        UI.Popup("", "purchasePop", "width=600, height=400, scrollbars=yes");
        form.target = "purchasePop";
        form.submit();
    }
}

function openDaumCash() {
    var url = "https://bill.daum.net/Bront?cmd=cash";
    var winFeat = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=580,height=543";
    newWin = window.open(url, "bill", winFeat);
    newWin.focus();
}


function gift( formName ) {
    var radio = document[formName].ticket;
    var selectedId = null;
    for( var i=0,cnt=radio.length; i<cnt; i++ ){
        if( radio[i].checked == true ){
            selectedId = radio[i].value;
        }
    }
    if( selectedId == null ){
        alert("이용권을 선택해 주세요");
    } else {
        UI.Popup("/ticket/giftform.do", "giftTicket", "width=629, height=647, scrollbars=no, resizable=yes");
    }
    //window.open("/ticket/giftform.do", "giftTicket", "width=600, height=400, scrollbars=yes");
}
*/

Music.TicketSelectedItemId = null;
Music.TicketController = function( objData, _opt ){
    this.data = objData;
    this.itemId = null;
    this.isPeriodic = null;//구매대상 이용권 중 선택 아이템의 정기결제 여부
    this.isAodUse = null;//음악감상(정기결제) 이용권 사용중 여부
    this.isAodPeriodic = null;//사용중인 이용권의 정기결제 아이템 여부
    this.cntGiftItem = 0;//선물 받는 대상자 인원
    this.opt = {
        type : "purchase" // puechase || gift 
    };
    Object.extend(this.opt, _opt);
    this.init();
};
Music.TicketController.prototype = {
    init : function(){
   //     this.formItem = document.frmTicket;
        this.formPayType = document.frmPayType;
        this.form = document.cartFrm;
        this.totalPrice = (this.opt.type=="gift") ? 0 : this.data.list.itemPrice;// 결제금액
        this.setTotalPrice();
    },
    
    
	
  /*  
    setTicketType : function( itemId, isPeriodic ){
        if( !itemId ){
            return false;
        }
        var objRadio = UI.$("ticketType_"+itemId);
        if( !objRadio ){
            alert("이용권 객체가 존재하지 않습니다.");
            return false;
        } else {
            if( objRadio.checked == false ){
                objRadio.checked = true;
            }
        } 
        this.itemId = Music.TicketSelectedItemId = itemId;
        
        this.isPeriodic = isPeriodic;
        this.changeDisplay();// 현재 설정에 따라 하단 버튼의 display여부를 결정
   //     var item = this.getItem( itemId );
        // 결제금액 표시
        this.setTotalPrice( this.data.list.itemPrice );
       
    },*/
    setPaymentType : function() {
    	if(this.totalPrice <= 0) this.isMobile(false);
    	else this.isMobile(true);
    	if(this.totalPrice <= 1000) this.isCard(false);
    	else this.isCard(true);
    },
    
    isMobile : function(show) {
		var _mobile = this.formPayType.paymentType[1];
		if(show) {
			_mobile.disabled = "";
			_mobile.nextSibling.className="";
		} else {
			_mobile.disabled = "true";
			_mobile.nextSibling.className="gray_b1";	
		}
	},
	
    isCard : function(show) {
		var _card = this.formPayType.paymentType[2];
		if(show) {
			_card.disabled = "";
			_card.nextSibling.className="";
		} else {
			_card.disabled = "true";
			_card.nextSibling.className="gray_b1";	
		}
	},
    setTotalPrice : function(){
        
        // 선물하기시 선물내역 표기
        if( this.opt.type == "gift" ){
        	UI.$('toSendTot').innerHTML = this.cntGiftItem;
        	
       //     var objState = UI.$("giftState");
       //     if( !objState ) return false;
            
       //     var objLabel = UI.$("label_"+this.itemId);
       //     if( !objLabel ) return false;
     
            this.totalPrice = this.data.list.itemPrice * this.cntGiftItem;
            var _cost = this.data.list.itemCost * this.cntGiftItem;
          //  var itemPrice = val;
            
   //         objState.innerHTML = '<span id="giftState"><strong>'+objLabel.innerHTML+' '+UI.addComma( itemPrice )+'원 x '+this.cntGiftItem+'명</strong> = <em class="em">'+UI.addComma( this.totalPrice )+'</em>원</span>';
        } else {
        	var _cost = this.data.list.itemCost;
        }
    
        // 결제금액 표기        
    	if( UI.$("totalPay") ){
            UI.$("totalPay").innerHTML = UI.addComma( this.totalPrice );
    	}
    	
    	// 부가세 표기
    	if( UI.$("surtaxPrice") ){
            UI.$("surtaxPrice").innerHTML = UI.addComma( this.totalPrice - _cost) + "원 ";
    	}
    	
    	// 결제수단을 갱신
    	this.chkPaymentType();
    },
/*
    setHideDisplay : function( obj ){
    	if( obj ){ obj.style.display = "none"; }
    },
    setShowDisplay : function( obj ){
        if( obj ){ obj.style.display = "inline"; }
    },

    setHelpMessage : function( type ){
    	var obj = UI.$("helpMessage");
    	if( !obj ) return false;
    	var msg = "";
    	switch( type ){
    	case "type1" : // 이용권사용 + 정기결제
			msg = '<strong>고객님께서는 현재 정기결제 이용권을 사용중입니다.</strong><br>\
			선택 상품은 현재 사용중인 정기결제 이용권 해지 후 구매해주시기 바랍니다.<br><br>\
			이용권 구매내역은 <a href="http://music.daum.net/my/ticket/status.do" target="_openner" class="blue" title="이용권현황으로 이동">MY페이지>이용정보>이용권 현황</a>에서 확인 가능';  
            break;
        case "type2" : // 이용권사용 
			msg = '<strong>고객님께서는 현재 음악감상 이용권을 사용중입니다.</strong><br>\
			음악감상 이용권 사용 고객님께서는 정기결제 이용권의 구매가 불가능합니다.<br>\
			선택 상품은 현재 사용중인 이용권의 사용 완료 후 구매해주시기 바랍니다.<br><br>\
			이용권 구매내역은 <a href="http://music.daum.net/my/ticket/status.do" target="_openner" class="blue" title="이용권현황으로 이동">MY페이지>이용정보>이용권 현황</a>에서 확인 가능';
            break;
        case "type3" : // 이용권미사용 
			msg = '<strong>위 내역을 결제 하시겠습니까?</strong><br>\
			이용권 구매내역은 <a href="http://music.daum.net/my/ticket/status.do" target="_openner" class="blue" title="이용권현황으로 이동">MY페이지>이용정보>이용권 현황</a>에서 확인 가능';  
            break;
        default:
            msg = '';
    	}
    	obj.innerHTML = msg;
    },
    changeDisplay : function(){
        var btnPayObj = UI.$("btnPay");//결제하기
        var btnGiftObj = UI.$("btnGift");//선물하기
        var btnConfirmObj = UI.$("btnConfirm");//확인
        var btnCancelObj = UI.$("btnCancel");//취소
        var formPayType = UI.$("frmPayType");//결제금액 및 결제수단 form
        
        this.setHideDisplay( btnConfirmObj );
        
        //디버깅용
        //this.isAodUse = true;         // 이용권 사용 여부         
        //this.isAodPeriodic = true;    // 사용하는 이용권의 정기결제 여부
        //this.isPeriodic = true;       // 선택한 이용권의 정기결제 여부
       
        // 사용중인 이용권의 종류에 따른 버튼 display         
        if( this.isAodUse == true && this.isAodPeriodic == true ){
	        this.setHideDisplay( btnPayObj );
	        this.setHideDisplay( formPayType );
	        this.setShowDisplay( btnGiftObj );
	        this.setShowDisplay( btnCancelObj );
	        this.setHelpMessage("type1");
       } else if( this.isAodUse == true && this.isAodPeriodic == false ){
            this.setShowDisplay( btnPayObj );
            this.setShowDisplay( btnGiftObj );
            this.setShowDisplay( btnCancelObj );
        	this.setShowDisplay( formPayType );
        	if( this.isPeriodic == true ){
        		this.setHelpMessage("type2");
        	} else {
        		this.setHelpMessage("type3");        	
        	}
        } else {
        	this.setShowDisplay( btnPayObj );
        	this.setShowDisplay( btnGiftObj );
        	this.setShowDisplay( btnCancelObj );
        	this.setShowDisplay( formPayType );
        	this.setHelpMessage("type3");
        }
        
        // 다운로드 이용권 선택여부 - 다운로드 이용권은 언제나 결제, 선물 가능
        var isOnlyDownload = ( this.itemId.indexOf("MPG")>-1 )? true:false;
        if( isOnlyDownload == true ){
            this.setShowDisplay( btnPayObj );
            this.setShowDisplay( btnGiftObj );
            this.setShowDisplay( btnCancelObj );
            this.setShowDisplay( formPayType );
            this.setHideDisplay( btnConfirmObj );
            this.setHelpMessage("type3");
        }

        // 선택된 이용권이 정기결제 이용권이면 선물하기 불가
        if( this.isPeriodic == true ){
            this.setHideDisplay( btnGiftObj );
            // 이용권 사용중이라면 정기결제는 구매 불가
            if( this.isAodUse == true && this.isAodPeriodic == false ){
            	this.setHideDisplay( btnPayObj );
                this.setHideDisplay( formPayType );            	
                this.setHelpMessage("type2");            	
            }
        }
        
        // 버튼이 1개만(취소) 남으면 '확인'으로 치환 후 취소는 숨김
        if( btnPayObj.style.display == "none" &&
            btnGiftObj.style.display == "none" &&
            btnConfirmObj.style.display == "none" && 
            btnCancelObj.style.display != "none"         
        ){
        
        }
    },*/
    onChangeGiftItem : function( handleGift ){
        this.cntGiftItem = handleGift.getIdList().length;
      
	//    var item = this.getItem( this.itemId );	    
    //    var totalPrice = item.itemPrice;
        
	    this.setTotalPrice();
	    
    },
    chkPaymentType : function(){
        // 결제 가능수단
     //   var item = this.getItem( this.itemId );
        var resetFlag = true;
        var checkList = [ "MOBILE", "DAUMCASH", "CREDITCARD" ];
        
        for( var i=0, cnt_i=checkList.length; i<cnt_i; i++){
            var flag = false;
            for( var k=0, cnt_k=this.data.list.itemAvailable.length; k<cnt_k; k++){
                if( checkList[i] == this.data.list.itemAvailable[k] ){
                    flag = true;
                }
            }
            // 해당 결제수단이 아닌 사항들
            var availObj = UI.$("accType_"+checkList[i]);
            if( !availObj ) return false; //결제가 정상적으로 안되면 빠져
            if( flag == false ){
                if( availObj.checked == true ){
                    availObj.checked = false;
                    UI.$( "accType_"+this.data.list.itemAvailable[0] ).checked = true;
                }
                availObj.disabled = true;
            } else {
                if( availObj.disabled == true ){
                    availObj.disabled = false;
                }
            }
        }

        this.setPaymentType();  
     /*   // 1000원 이하
        if( this.totalPrice < 1000 ){
            if( this.formPayType.paymentType[2].checked ){
                this.formPayType.paymentType[2].checked = false;
                var obj = UI.$("accType_"+this.data.list.itemAvailable[0]);
                obj.checked = true;
            }
            UI.$("accType_CREDITCARD_label").className = "gray_b1";
            this.formPayType.paymentType[2].disabled = true;
        } else {
            UI.$("accType_CREDITCARD_label").className = "";
            this.formPayType.paymentType[2].disabled = false;
            
        }     */
    },
/*    getItem : function( id ){
        for( var i=0, cnt=this.data.list.length; i<cnt; i++){
            if( this.data.list[i].itemId == id ){
                return this.data.list[i];
            }
        }
        return false;
    },*/
    clearItemSelect : function(){
        for( var i = 0; i < this.formItem.itemId.length; i++ ) {
            this.formItem.itemId[i].checked = false;
        }
            
        // 결제금액 표시
        this.setTotalPrice( "0" );
    },
    // 구매하기, 결제하기   
    pay : function() {
	    
	    // 선택된 이용권 ID를 체크 
	    /*
	    var selectedId = "";
	    for( var i = 0; i < this.formItem.itemId.length; i++ ) {
	        if( this.formItem.itemId[i].checked ) {
	            selectedId = this.formItem.itemId[i].value;
	            this.formItem.itemId.value = selectedId;
	            break;
	        }
	    }
	    if( selectedId == "" ){
	        alert("구매할 이용권을 선택해 주세요");
	        return false;
	    }
	    this.itemId = Music.TicketSelectedItemId = selectedId; 
*/
		this.form.innerHTML = "";
		this.itemId = this.data.selectedItemId;		
		var param = "";
		
		// 선물하기
		if(this.opt.type == "gift") {
			var receiverArr = giftChoice.getClearList();
			var len = receiverArr.childNodes.length;
			if(len == 0) {
			    alert('선물받으실 분의 Daum 아이디를 입력해 주세요.');
			    return false;
			}

			for(var i=0; i<len; i++) {
			    param += "&receiver=" + receiverArr.childNodes[i].id.replace(/mailList_/g, '');
				Music.makeInputTag(this.form, "receiver", receiverArr.childNodes[i].id.replace(/mailList_/g, ''));
			}
			
			var message = UI.trim(UI.$('sendMessage').value); 
			if(message == "" || message == "선물 메일에 들어갈 메시지를          작성해주세요.") {
			    alert('선물 받으실 분에게 보내는 메시지를 입력해 주세요.');
			    UI.$('sendMessage').value = '';
			    UI.$('sendMessage').focus();
			    return false;
			}
			param += "&message="+message;
			if(UI.getBrowser().ie) {
				var oText = document.createElement("<textarea name=\"message\">");   
			} else {
				var oText = document.createElement("textarea");   
                oText.name = "message" ;   
			}
			oText.value = message;
			oText.className = "hide";
			this.form.appendChild(oText);	
		} 
	
        if( this.formPayType.paymentType[0].checked ) {
            if( parseInt(this.data.daumcash,10) >= parseInt(this.totalPrice,10) ){
                // daumcash
                this.form.method = 'POST';
                if( this.opt.type == "purchase" ) this.form.action = '/ticket/purchase.do';
				else if( this.opt.type == "gift" ) this.form.action = '/ticket/gift.do';

                Music.makeInputTag(this.form, "itemId", this.itemId);
                Music.makeInputTag(this.form, "paymentType", "DAUMCASH");
                this.form.submit();
            } else {
            	alert("Daum캐쉬가 부족합니다. \nDaum캐쉬 추가 충전후 이용해주세요.");
            	return false;
            //    if( confirm("Daum캐쉬가 부족하여 결재를 진행 할 수 없습니다.\n캐시를 충전 하시겠습니까?") ){
              //      openDaumCash();
            //    }
            }
        } else {
            // BI
            var url = "";
            if( this.opt.type == "purchase" ) url = "/ticket/purchase/preparepaymentIE8.do";
            else if( this.opt.type == "gift" ) url = '/ticket/gift/preparepaymentIE8.do';
            
            // 결제방식값	                  
            for( var i=0, cnt=this.formPayType.paymentType.length; i<cnt; i++ ){
                if( this.formPayType.paymentType[i].checked == true ){
                    param += '&paymentType=' + this.formPayType.paymentType[i].value;
                }
            }       
            
            // 선택된 이용권Id            
            param += "&itemId="+this.itemId;
            
            // run prepare payment      
            new UI.Ajax({url:url,param:param,method:"POST",onComplete:this.callBI.bind(this)});      
       /*     var ajax = new UI.Ajax( {url:url, autoSend:false} );
            ajax.options.onComplete = this.callBI.bind(this);
            ajax.options.param = param;
            ajax.options.method = "POST";
            ajax.send();*/
        }
    },

    callBI : function(req) {
	    if (req.readyState == 4) {
	        if (req.status == 200) {
	            eval(req.responseText);
	            if( PreparePayment.errorCode != "" ){
	                alert("결제가 실패하였습니다. : " + PreparePayment.errorName);
	                return;
	            }	            
	            if( PreparePayment.Periodic == "Y" ){	// 자동결제
                    this.openAutoPayment(PreparePayment.Rcvseq, PreparePayment.Pgcate, 1, PreparePayment.ResultUrl + "?rtnParam=" + PreparePayment.RtnParam);
	            } else {
    	            this.openPayment(PreparePayment.Rcvseq, PreparePayment.Pgcate, 1, PreparePayment.ResultUrl + "?rtnParam=" + PreparePayment.RtnParam);
	            }
	         } else {
	            alert(req.statusText);
	         }
	    }   
	},
    openPayment : function (rsvseq, pgcate, noPopup, resultURL) {
	    //var url = "https://bill.daum.net/Elf/start/SettlementBroker.daum?rsvseq=" + rsvseq + "&pgcate=" + pgcate;
	    //var url = "https://bill.daum.net/Elf/start/SettlementBroker.daum?rsvseq=" + rsvseq + "&pgcate=" + pgcate + "&isNoPopup=" + noPopup + "&resultURL=" + resultURL;
	    var param = "?rsvseq=" + rsvseq + "&pgcate=" + pgcate + "&isNoPopup=" + noPopup + "&resultURL=" + resultURL;
	    if(this.formPayType.paymentType[2].checked) var url = "https://bill.daum.net/Elf/instant/Credit.daum";
	    else var url = "https://bill.daum.net/Elf/instant/Mobile.daum";
	    
	    var winOpt = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=549,height=674";
	    if( screen.height < 768 ){
	        winOpt = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=549,height=674,top=0";
	    }
	    var newWin = window.open(url+param, "bill", winOpt);
	    if(newWin) newWin.focus();
	    else alert("팝업이 차단되어 있습니다.");
	},
	openAutoPayment : function(rsvseq, pgcate, noPopup, resultURL) {
	    //var url = "https://bill.daum.net/Elf/start/SettlementBroker.daum?rsvseq=" + rsvseq + "&pgcate=" + pgcate;
	    //var url = "https://bill.daum.net/Elf/start/SettlementBroker.daum?rsvseq=" + rsvseq + "&pgcate=" + pgcate + "&isNoPopup=" + noPopup + "&resultURL=" + resultURL;
	    var param = "?rsvseq=" + rsvseq + "&pgcate=" + pgcate + "&isNoPopup=" + noPopup + "&resultURL=" + resultURL;
	    if(this.formPayType.paymentType[2].checked) var url = "https://bill.daum.net/Elf/subscription/Credit.daum";
	    else var url = "https://bill.daum.net/Elf/subscription/Mobile.daum";
	    
	    var winOpt = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=549,height=674";
	    if( screen.height < 768 ){
	        winOpt = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=549,height=674,top=0";
	    }
	    var newWin = window.open(url+param, "bill", winOpt);
	    if(newWin) newWin.focus();
	    else alert("팝업이 차단되어 있습니다.");
	},
	/*
	openDaumCash : function() {
		var returnURL = encodeURIComponent("http://music.daum.net/purchase/daumcash.html");
		var url = "https://bill.daum.net/Elf/cash/Credit.daum?popURL=" + returnURL;
	    var winFeat = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=580,height=543";
	    newWin = window.open(url, "bill", winFeat);
	    newWin.focus();
	},*/
	goGift : function() {
		var url = "/ticket/giftform.do?itemId=" + this.data.selectedItemId;
		goURL(url);
	},
	goBuy : function() {
		var url = "/ticket/purchaseform.do?itemId=" + this.data.selectedItemId;
		goURL(url);
	}
};

var linkTicketUse = function( id, status ){
    if( id == "" ){ alert("이용권 ID가 없습니다."); return false;}
    var url = "/my/ticket/use.do?id="+id+"&status="+status;
    //UI.Popup( url, "useTicket", "width=300,height=300" );
    location.href=url; 
};


var selectTicketLabel = function( id ){
    var obj = UI.$(id);
    if( obj ){
        obj.checked = true;   
    }
};