/**
 * JavaScript for Relation Goods Processing.
 * 
 * @author    Sang-jae, Lee <smartsoft at nbizsoft dot com>
 * @copyright (c) 2009 nbizsoft corp.
 * @version   PointShop Plus 
 * @link      http://www.pointshop.co.kr
 */
//<![CDATA[ 
document.observe("dom:loaded", function() {
// arGoodsIds
if ( arRelGoodsInfo.length > 0 ) {

	var oForm = $('__FormGoodsView');
	var bComplexBuyTemplate = true;

	arRelGoodsInfo.each(function(el){

		if ( !$('_idOptPrice_'+el.pid ) ) {
			bComplexBuyTemplate = false;
			throw $break;
		}

	
		var hasOption = false;
		// price		
		switch( el.priceType ) {
		case 1:
			$('_idOptPrice_'+el.pid).appendChild(new Element('INPUT',{'type':'hidden','name':'oRelPrice_'+el.pid,'value':el.arPrice[0].idx}));
			if ( el.arOpts.length < 1 && el.arOptItem.length < 1 ) {
				$('_idOptPrice_'+el.pid).appendChild(new Element('div').update('&nbsp;'));
			}
			hasOption = true;
			break;
		case 2:
			var odivLabel = new Element('div',{'class':'idRelItemLabel'});			
			var txtLabel  = el.optxtitle ? el.optxtitle: 'ÆÇ¸Å°¡ ¼±ÅÃ';
			odivLabel.update( txtLabel );
			
			var odivSelect = new Element('div');
			odivSelect.setStyle({'float':'left'});
			
			var ohtmlPrice = new Element('SELECT',{ 'name': 'oRelPrice_'+el.pid});
            ohtmlPrice.add(new Element('OPTION',{'text': txtLabel,'value':-1, 'className': 'optTitle'}));
			
			el.arPrice.each(function(priceItem){
                ohtmlPrice.add(new Element('OPTION',{'text':priceItem.optxnm + " (" + MakePayValue( priceItem.price ) + ")",'value':priceItem.idx}));
			});
			ohtmlPrice.onchange=function(){
				__psRelItemUpdate( arRelGoodsIds.indexOf(el.pid) );
			}
			odivSelect.appendChild(ohtmlPrice);			
			$('_idOptPrice_'+el.pid).appendChild(odivLabel);
			$('_idOptPrice_'+el.pid).appendChild(odivSelect);
			hasOption = true;
			break;
			
		case 3:
			// opt1
			var odivRow1 = new Element('div');
			var odivLabel = new Element('div',{'class':'idRelItemLabel'});			
			odivLabel.update( el.optxtitle );
			
			var odivSelect = new Element('div',{'class':'idRelItems'});			
			var ohtmlPrice = new Element('SELECT',{'name': 'oRelPrice_'+el.pid+'_1'});
			ohtmlPrice.onchange=function(){
				__psRelItemUpdate( arRelGoodsIds.indexOf(el.pid) );
			}
            ohtmlPrice.add(new Element('OPTION',{'text': el.optxtitle + ' ¼±ÅÃ','value':-1, 'className': 'optTitle'}));
			el.optxnames.each(function(o){
                ohtmlPrice.add(new Element('OPTION',{'text':o,'value':o}));
			});			
			odivSelect.appendChild(ohtmlPrice);		
			odivRow1.appendChild(odivLabel);
			odivRow1.appendChild(odivSelect);
			
			//opt2
			var odivRow2 = new Element('div');			
			var odivLabel2 = new Element('div',{'class':'idRelItemLabel'});			
			odivLabel2.update( el.optytitle );
			
			var odivSelect2 = new Element('div',{'class':'idRelItems'});			
			var ohtmlPrice2 = new Element('SELECT',{'name': 'oRelPrice_'+el.pid+'_2'});
			ohtmlPrice2.onchange=function(){
				__psRelItemUpdate( arRelGoodsIds.indexOf(el.pid) );
			}
            ohtmlPrice2.add(new Element('OPTION',{'text':el.optytitle + ' ¼±ÅÃ','value':-1, 'className': 'optTitle'}));
			el.optynames.each(function(o){
                ohtmlPrice2.add(new Element('OPTION',{'text':o,'value':o}));
			});
			odivSelect2.appendChild(ohtmlPrice2);			
			odivRow2.appendChild(odivLabel2);
			odivRow2.appendChild(odivSelect2);
			
			$('_idOptPrice_'+el.pid).appendChild(odivRow1);
			$('_idOptPrice_'+el.pid).appendChild(odivRow2);
			$('_idOptPrice_'+el.pid).appendChild(new Element('INPUT',{'type':'hidden','name':'oRelPrice_'+el.pid,'value': el.arPrice[0].idx}));
			hasOption = true;
			break;
		default:
			break;
		}
		
		// opts		
		if ( el.arOpts.length > 0 ) {			
			el.arOpts.each(function(o){
				var odivRow = new Element('div');
				var odivLabel = new Element('div',{'class':'idRelItemLabel'});
				odivLabel.update( o.title );
				
				var odivSelect = new Element('div',{'class':'idRelItems'});		
				var ohtmlPrice = new Element('SELECT',{'name': 'oRelOpts_'+el.pid+'[]'});
				ohtmlPrice.add(new Element('OPTION',{'text': o.title + ' ¼±ÅÃ','value':-1, 'className': 'optTitle'}));
				o.opts.each(function(os){
					ohtmlPrice.add(new Element('OPTION',{'text':os,'value':os}));
				});				                
				odivSelect.appendChild(ohtmlPrice);
				$('_idOptItem_'+el.pid).appendChild(odivRow);
				$('_idOptItem_'+el.pid).appendChild(odivLabel);
				$('_idOptItem_'+el.pid).appendChild(odivSelect);
			});			
			hasOption = true; 
		}
		
		// optItems
		if ( el.arOptItem.length > 0 ) {
			var odivLabel = new Element('div',{'class':'idRelItemLabel'});
			odivLabel.update( "¿É¼Ç±¸¸Å" );
			var odivRows = new Element('div',{'class':'idRelItems'});	
			el.arOptItem.each(function(o){							
				var odiv  = new Element('div');
				var oItem = new Element('INPUT',{'name':'oRelAddItem_'+el.pid+'[]', 'type':'checkbox','value': o.price,'title':o.title});
				oItem.onclick=function(){
					__psRelItemUpdate(arRelGoodsIds.indexOf(el.pid));
				}
				odiv.appendChild(oItem);
				odiv.appendChild(document.createTextNode( o.title + ' ('+ MakePayValue(o.price) + ')' ));												
				odivRows.appendChild( odiv );
				
			});
			$('_idOptAddItem_'+el.pid).appendChild(odivLabel);
			$('_idOptAddItem_'+el.pid).appendChild(odivRows);
			hasOption = true;
		}
		
		if ( !hasOption ) {
			$('_idOptions_'+el.pid).update('&nbsp;');
		}
	}); // end_of_each

	if ( bComplexBuyTemplate ) {
	
	// Ç°Àý»óÇ°Ã³¸®
	var arRowItems = oForm.getInputs('checkbox', '_objId_RelGoods[]' );
	arRowItems.each(function(el,idx){
		if ( arRelGoodsInfo[idx].arPrice[0].stock == 0 ) {
			el.disable();
			el.title = 'Àç°íºÎÁ·(Ç°Àý)·Î ÇöÀç ±¸¸Å ÇÒ ¼ö ¾ø½À´Ï´Ù.';
			$('idBuyCount['+idx+']').disable();
		}
	});	

	if ( $('oRelGoodsCheckAll') ) {	
		$('oRelGoodsCheckAll').onclick=function(){		
			var oThis = this;
			var arRowItems = oForm.getInputs('checkbox', '_objId_RelGoods[]' );
			arRowItems.each(function(el){
				if ( !el.disabled ) 
					el.checked = oThis.checked;
			});			
		}
	}
	
	if ( $('id_btn_addcart_relgoods') ) {
		$('id_btn_addcart_relgoods').onclick=function(){
		
			// ÁÖ»óÇ°ÀÇ ¿É¼Ç ¼±ÅÃÀº ÀûÀýÇÑ°¡?
			if ( !__checkMainGoods() ) return;			
			
			// °ü·Ã»óÇ°À» ¼±ÅÃÇÑ °ÍÀÌ ÀÖ±ä ÇÑ°¡?
			var arRow = oForm.getInputs('checkbox', '_objId_RelGoods[]' );
			var iChecked = 0;

			arRow.each(function(el){
				if ( !el.disaled ) {
					if ( el.checked ) iChecked++;
				}
			});
			if ( !iChecked ) {
				alert( 'ÇÔ²² ±¸¸ÅÇÒ °ü·Ã »óÇ°À» ¼±ÅÃÇØ ÁÖ½Ê½Ã¿À.' );
				return;
			}

			// ¼±ÅÃÇÑ °ü·Ã»óÇ°ÀÇ ¿É¼ÇÀ» ¼±ÅÃÇß´Â°¡?
			if ( !__psCheckRelGoods( oForm ) ) return;
		
			if ( confirm( "¼±ÅÃ»óÇ°À» ÇÔ²² Àå¹Ù±¸´Ï¿¡ ³ÖÀ¸½Ã°Ú½À´Ï±î?" ) ) {
				oForm.iCmdExec.value = "buyRelation";
				oForm.submit();
			}
		}
	}

	} // endif (bComplexBuyTemplate)
}

});

// non complex template 
function __psRelGoodsAddCart()
{
	// ÁÖ»óÇ°ÀÇ ¿É¼Ç ¼±ÅÃÀº ÀûÀýÇÑ°¡?
	if ( !__checkMainGoods() ) return;			

	var oForm = $('__FormGoodsView');
	var arRow = oForm.getInputs('checkbox', '_objId_RelGoods[]' );
	var iChecked = 0;

	arRow.each(function(el){
		if ( !el.disaled ) {
			if ( el.checked ) iChecked++;
		}
	});
	
	if ( !iChecked ) {
		alert( 'ÇÔ²² ±¸¸ÅÇÒ °ü·Ã »óÇ°À» ¼±ÅÃÇØ ÁÖ½Ê½Ã¿À.' );
	} else {
		oForm.iCmdExec.value = 'buyRelation';
		oForm.submit();
	}
}

function __psCheckRelGoods(o)
{
	var arRow = o.getInputs('checkbox', '_objId_RelGoods[]');
	var iRowCount = 0;
	var bResult = false;
	arRow.each(function(el){
		if ( el.checked ) {
			var id = el.value;
			var arGoods = arRelGoodsInfo[iRowCount];
			var iNo = parseInt( $F('idBuyCount['+iRowCount+']') );
			var iMinUnit = 1;
			var priceId = 0;
			
			switch( arGoods.priceType ) {
			case 1:
			case 2:
				priceId = $F('oRelPrice_'+id);
				break;
			case 3:
				var priceKey1 = $F('oRelPrice_'+id+'_1');
				var priceKey2 = $F('oRelPrice_'+id+'_2');
				var arFound = arGoods.arPrice.find(function(s){
					if ( s.optxnm == priceKey1 && s.optynm == priceKey2 ) return true;
					return false;
				});
				if ( arFound !== undefined ) {
					$('oRelPrice_'+id).value = priceId = arFound.idx;
				} else {
					priceId = -1;
				}
				break;
			default:
				break;
			}

			var sOptAlert = '»óÇ° "' + arGoods.pname + '"Àº(´Â) ¼±ÅÃÇ×¸ñÀÌ ÀÖ´Â »óÇ°ÀÔ´Ï´Ù.\n\n±¸¸ÅÇÏ°íÀÚ ÇÏ´Â ¼±ÅÃÇ×¸ñÀ» È®ÀÎÇØ ÁÖ½Ê½Ã¿À.';

			// °¡°Ý±¸ºÐ(price)
			if ( priceId < 0 ) {
				alert( sOptAlert );
				bResult = false;
				throw $break;
			}

			// ¿É¼Ç¼±ÅÃ(options)
			if ( arGoods.arOpts.length > 0 ) {
				var oSelOpt,oSlt = document.getElementById('oRelOpts_'+arGoods.pid+'[]');
				
				if(oSlt === null){
					// ¿É¼Ç ¼¿·ºÆ® ¹Ú½º°¡ ¾ø¾î¿ä Ã³¸®  ÇÏ»ï 
					bResult = false;
				}else {
					oSelOpt = oSlt.options[oSlt.selectedIndex];
					if(oSelOpt.value < 0){
						bResult = false;
						alert(sOptAlert);
						throw $break;
					}else {
						//alert('¼±ÅÃÇÑ ¿É¼Ç2 '+oSelOpt.value+' 23!');
					}
				}
				

				/*		

				arOptSels.each(function(oSel){
					if ( oSel.options[oSel.selectedIndex].value < 0 ) {
						alert( sOptAlert );
						bResult = false;
						throw $break;
					}
				});
				*/

			}
			
			// Ç°Àý»óÇ°ÀÎ°¡?
			if ( arGoods.arPrice[priceId].stock == 0 ) {
				// Ç°Àý»óÇ°
				el.checked = false;
				el.title = 'Àç°íºÎÁ·(Ç°Àý)·Î ÇöÀç ±¸¸Å ÇÒ ¼ö ¾ø½À´Ï´Ù.';
				bResult = false;
			} else {
			
			iMinUnit = arRelGoodsInfo[iRowCount].arPrice[priceId].unitMin;
			
			if ( iNo < 0 || iNo < iMinUnit) {
				alert( '»óÇ° ' + arGoods.pname + 'ÀÌ(°¡) ±¸¸Å¼ö·®ÀÌ 0ÀÔ´Ï´Ù. ÃÖ¼Ò '+ iMinUnit +' ÀÌ»ó ±¸¸ÅÇØ¾ßÇÏ´Â »óÇ°ÀÔ´Ï´Ù.' );
				bResult = false;
				throw $break;
			} else 
				bResult = true;				
			}
		}
		iRowCount++;
	});
	
	return bResult;
}

function __psRelGetPrice(gid)
{
	if ( $('oRelPrice_'+gid+'_1') && $('oRelPrice_'+gid+'_2') ) {
		var oForm = $('__FormGoodsView');
		var sSel1 = oForm['oRelPrice_'+gid+'_1'].options[ oForm['oRelPrice_'+gid+'_1'].selectedIndex ].value;
		var sSel2 = oForm['oRelPrice_'+gid+'_2'].options[ oForm['oRelPrice_'+gid+'_2'].selectedIndex ].value;
		var id = arRelGoodsIds.indexOf(gid);
		var retVal = -1;
		arRelGoodsInfo[id].arPrice.each(function(el){
			if ( el.optxnm == sSel1 && el.optynm == sSel2 ) {
				retVal = el.idx;
				throw $break;
			}
		});
		return retVal;
	}
	return -1;
}

function __psRelItemUpdate(id)
{
	var oForm = $('__FormGoodsView');
	var iBasePrice = 0;
	var iBasePoint = 0;
	var iAddItemPrice = 0;
	var gid = arRelGoodsIds[id];
	var no = parseInt( $F('idBuyCount['+id+']') );
	var arGoods = arRelGoodsInfo[id];
	var bItems = true;
	
	if ( no < 1 ) {
		no = 1;	
		$('idBuyCount['+id+']').value = no;
	}
	
	// price
	var iSelPrice = 0;
	switch ( arGoods.priceType) {
	case 2:
		iSelPrice = oForm['oRelPrice_'+gid].options[oForm['oRelPrice_'+gid].selectedIndex].value;		
		break;
	case 3:
		iSelPrice = __psRelGetPrice(gid);		
		break;
	default:		
		break;
	}
	
	var arRowCheck = oForm.getInputs('checkbox', '_objId_RelGoods[]' );
	arRowCheck[id].enable();
	$('idBuyCount['+id+']').enable();	
	arRowCheck[id].title = '';
	
	if ( bItems && iSelPrice >= 0 ) {
		if ( arGoods.arPrice[iSelPrice].stock < 0 ) {
			// Àç°í¹«°ü
		} else if ( arGoods.arPrice[iSelPrice].stock > 0 ) {
			if ( arGoods.arPrice[iSelPrice].stock < no ) {
				alert( '[' + arGoods.pname + '] Àç°íºÎÁ·À¸·Î ÃÖ´ë '+ arGoods.arPrice[iSelPrice].stock + '°³ ÀÌ»óÀº ÁÖ¹®ÇÏ½Ç ¼ö ¾ø½À´Ï´Ù.' );
				return;
			}
		} else {
			var sOptMsg = '';
			var sOptOther = '';
			if ( arGoods.priceType == 3 ) {
				sOptMsg = '\n(' + arGoods.optxtitle + ':' 
							+ arGoods.arPrice[iSelPrice].optxnm + ', '
							+ arGoods.optytitle + ':'
							+ arGoods.arPrice[iSelPrice].optynm + ')';
				sOptOther = '\n\n´Ù¸¥ ¿É¼ÇÀ» ¼±ÅÃÇØ ÁÖ½Ê½Ã¿À.';
			}
		
			arRowCheck[id].disable();
			arRowCheck[id].title = 'Àç°íºÎÁ·(Ç°Àý)·Î ÇöÀç ±¸¸Å ÇÒ ¼ö ¾ø½À´Ï´Ù.';
			$('idBuyCount['+id+']').disable();
			$('idBuyCount['+id+']').value = 0;
			alert( arGoods.pname + sOptMsg + '\n\n¼±ÅÃÇÑ »óÇ°(¿É¼Ç)Àº Ç°ÀýÀÔ´Ï´Ù.' + sOptOther );
			return;
		}
		
		if ( arGoods.arPrice[iSelPrice].unitMin > no ) {
			alert( 'ÃÖ¼Ò '+ arGoods.arPrice[iSelPrice].unitMin + '°³ ÀÌ»ó ÁÖ¹®ÇØ¾ßÇÏ´Â »óÇ°ÀÔ´Ï´Ù.' );
			return;
		}
		if ( arGoods.arPrice[iSelPrice].unitMax < no && arGoods.arPrice[iSelPrice].unitMax > 0 ) {
			alert( 'ÃÖ´ë '+ arGoods.arPrice[iSelPrice].unitMax + '°³ ÀÌ»ó ÁÖ¹® ÇÒ ¼ö ¾ø´Â »óÇ°ÀÔ´Ï´Ù.' );
			return;
		}
	}
	if ( iSelPrice < 0 ) iSelPrice = 0;	
	iBasePrice = arGoods.arPrice[iSelPrice].price;
	iBasePoint = arGoods.arPrice[iSelPrice].point;
	
	// add items
	if ( arGoods.arOptItem.length > 0 ) {		
		var arAddItems = oForm.getInputs('checkbox', 'oRelAddItem_'+gid+'[]' );		
		arAddItems.each(function(el,idx){
			if ( el.checked ) {				
				iAddItemPrice += arGoods.arOptItem[idx].price;
			}
		});
	}
	
	// update
	$('_idPrice_'+gid).update( MakePayValue( ( iBasePrice + iAddItemPrice ) * no ) );
	if ( $('_idPoint_'+gid) ) {
		var iPointRate = parseInt( iBasePoint / iBasePrice * 100.0 );
		$('_idPoint_'+gid).update( MakePayValue( iBasePoint * no ) );
		$('_idPoint_'+gid).title = iPointRate+'%';
	}
}
//]]>
