﻿
var objHttp;
var RecvUserId;
var RecvUserNick;
var RecvUserKey;
var SendFlag;
var isProcess = false;
var isDuplication = true;
var MsgDuplication = "";
var ServiceUrl = "http://devge.hanbiton.com";

// WebService
function CallShopWebService(methodName, paramNames, paramValues, func) {

  // native XMLHttpRequest object  
  if (window.XMLHttpRequest) {
    objHttp = new XMLHttpRequest();
  }
  // IE/Window ActiveX version
  else if (window.ActiveXObject) {
    objHttp = new ActiveXObject("Microsoft.XMLHTTP");
  }
  else { 
    // sorry
    return;
  }

	var strEnvelope = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
	      " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"" +
	      " xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
	      "<soap:Body>" +
	      "  <" + methodName + " xmlns=\""+ServiceUrl+"/h_shop/WebService\">";

  // parameters	      
	for (i = 0; i < paramNames.length; i++) {
	  strEnvelope += "<" + paramNames[i] + ">" + paramValues[i] + "</" + paramNames[i] + ">";
	}
	
	strEnvelope = strEnvelope + "  </" + methodName + ">" +
	      "</soap:Body>" +
	      "</soap:Envelope>";

  // add event handler
  objHttp.onreadystatechange = func;

	var szUrl = "/h_shop/WebService/Characon.asmx";

	// send the POST to the Web service
	objHttp.open("POST", szUrl, true);
	objHttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
	objHttp.setRequestHeader("SOAPAction", ServiceUrl+"/h_shop/WebService/" + methodName);
	objHttp.send(strEnvelope);
}

function doSetUserDefaultCharacon(characon_id) {
	
    // add parameters 	  
	  var paramNames = new Array();
	  var paramValues = new Array();

	  paramValues[0] = characon_id;

    // call
	  CallShopWebService("SetDefaultCharacon", paramNames, paramValues, wSetUserDefaultCharaconProcess);	  
	  paramNames[0] = "characon_id";
}

function wSetUserDefaultCharaconProcess() {
  // a readyState of 4 means we're ready to use the data returned by XMLHTTP
  if (objHttp.readyState == 4) {
	  // get the return envelope
	  var szResponse = objHttp.responseText;

    // success code
	  if (objHttp.status == 200) {		
	    var res = objHttp.responseXML.documentElement;
	    switch (res.getElementsByTagName('SetDefaultCharaconResult')[0].firstChild.data) {
	      case "0":	//성공        			
	        break;
	      case "-1":
	        break;
	      case "1":
	        break;
	    }
    } else {
      // unexcepted error occured     
    }
  }
}

function doCheckUserCash(Amount) 
{
	var paramNames = new Array();
	var paramValues = new Array();

	paramNames[0] = "buyAmount";
	paramValues[0] = Amount;

	CallShopWebService("CheckUserCash", paramNames, paramValues, wCheckUserCashProcess);
}

function wCheckUserCashProcess() {
  // a readyState of 4 means we're ready to use the data returned by XMLHTTP
  if (objHttp.readyState == 4) {
	  // get the return envelope
	  var szResponse = objHttp.responseText;

    // success code
	  if (objHttp.status == 200) {
	    var res = objHttp.responseXML.documentElement;
	    
	    switch (res.getElementsByTagName('CheckUserCashResult')[0].firstChild.data) {
	      case "0":	//성공   
	        
	        break;
	      case "-1":
	        alert('로그인을 하여 주십시요');
	        break;
	      case "1":
	        alert('한빛캐시 잔액이 모자릅니다.');
	        break;
	      case "-2":
	        alert('구매 정보가 이상해요');
	        break;
	      case "-3":
	        alert('빌링 시스템을 점검 중입니다.');
	        break;
	        
	    }
    } else {
      // unexcepted error occured
    }
  }
}


function doSendGift(id,buyAmount,ipAddress,msgContents) {
	
	isProcess = true;

	// add parameters 	  
	var paramNames = new Array();
	var paramValues = new Array();

	paramNames[0] = "userId";
	paramNames[1] = "buyAmount";
	paramNames[2] = "userIp";
	paramNames[3] = "msgContents";
	paramValues[0] = id;
	paramValues[1] = buyAmount;
	paramValues[2] = ipAddress;
	paramValues[3] = msgContents;

	// call
	CallShopWebService("SendGift", paramNames, paramValues, wSendGiftProcess);	  
}

function wSendGiftProcess() {
	// a readyState of 4 means we're ready to use the data returned by XMLHTTP
	if (objHttp.readyState == 4) {
	// get the return envelope
		var szResponse = objHttp.responseText;

		// success code
		if (objHttp.status == 200) {		
			var res = objHttp.responseXML.documentElement;	        
			var UserFlag = res.getElementsByTagName('UserFlag')[0].firstChild.data;	
			isProcess = false;	
			
			switch (UserFlag) 
			{
				case "0":	//성공       
					RecvUserId = res.getElementsByTagName('UserId')[0].firstChild.data;
					RecvUserKey = res.getElementsByTagName('UserKey')[0].firstChild.data;
					RecvUserNick = res.getElementsByTagName('UserNick')[0].firstChild.data;
					break;
				case "-1":
					alert('로그인을 하여 주십시요.');
					return false;
					break;					
				case "1":
					alert(res.getElementsByTagName('UserId')[0].firstChild.data + '님은 존재하지 않는 회원입니다');
					return false;
					break;
			}
			if(UserFlag == "0")
			{			
				var CashFlag = res.getElementsByTagName('CashFlag')[0].firstChild.data;
				switch (CashFlag) 
				{
					case "0":	//성공
						break;
					case "-1":
						alert('로그인을 하여 주십시요.');
						return false;
						break;
					case "1":
						alert('한빛캐시 잔액이 모자릅니다.');
						return false;
						break;
					case "-2":
						alert('구매 정보가 이상해요');
						return false;
						break;
					case "-3":
						alert('빌링 시스템을 점검 중입니다.');
						return false;
						break;
				}			
			}
			if(CashFlag == "0")
			{
				if(res.getElementsByTagName('DupFlag')[0].firstChild.data == "1")
				{				
					alert(res.getElementsByTagName('UserId')[0].firstChild.data + '님이 ' 
					+ res.getElementsByTagName('DupMsg')[0].firstChild.data + ' 보유하고 있습니다\n다른 상품을 선물해 보세요~!');
					return false;
				} else {
					if(res.getElementsByTagName('SendFlag')[0].firstChild.data == "0")
					{	
						var f = document.Form1;						
						var objNodeList = res.getElementsByTagName("MsgList");						
//						for (var i=0; i<objNodeList[0].childNodes.length; i++) {							
//							SendMemoMsg(objNodeList[0].childNodes[i].firstChild.data);
//						}						
						
						isProcess = false;	
						var cash = f.TotalAmt.value;
						var cnt_goods = f.ItemCnt.value;
						var top_nm_goods = f.Top_nm_goods.value;
						
						var url= "/h_shop/Characon/GiftSendComplete.aspx?own_user_id=" + RecvUserId + "&cash=" + cash + "&top_nm_goods=" + top_nm_goods + "&cnt_goods=" + cnt_goods +"&own_nick=" + RecvUserNick + "&from=characon" ;
						MM_openBrWindow(url,'popSndGiftConfirm','width=370,height=420');
						
						f.txtRecv.value = "";
						f.txt_Nm_note.value = "";
						location.href = "/h_shop/Characon/CharaconList.aspx?cd_m=4&cd_s=1&cd_ss=0&menuType=1";
					} else {

					}
				}
			}
		} else {
			// unexcepted error occured     
		}
	}
}


function doSendingGift(myid) {
	
	var f = document.Form1;
	

	if(f.txtRecv.value =="" ){
		alert("선물을 받을 회원을 선택 혹은 입력해주세요. ^^*");
		f.txtRecv.focus();					
		return;
	}
	 
	if(f.txtRecv.value ==myid ){
		alert("자기자신에게는 선물을 보낼실 수 없슶니다.");
		f.txtRecv.focus();					
		return;	
	}	
	
	if(!chkStr(f.txtRecv)){
		alert("한명의 회원에게만 선물을 보내실 수 있습니다.");
		f.txtRecv.focus();
		return;
	}		
	
	if(f.txt_Nm_note.value.split(" ").join("") =="" || f.txt_Nm_note.value == "메시지를 입력하세요."){		
		alert("메시지를 남겨주세요. ^^*");
		f.txtRecv.focus();
		//return false;
		return;
	}
	else
	{
		lenm = CountCharLengh2(f.txt_Nm_note);
		if(lenm > 500){
			alert("\n 메시지의 길이가 500자가 넘습니다.");
			f.txt_Nm_note.focus();
			return;			
		}
	}
	if(f.requestIP.value == "")
	{
		alert('올바른 접근 방식이 아닙니다');
		return;
	}
	
	if(isProcess)
	{
		alert('처리중에 있습니다');
		return;
	}	
	if(confirm('한빛캐시 ' + f.TotalAmt.value + ' 원이 소요됩니다.')) {
		doSendGift(f.txtRecv.value,f.TotalAmt.value,f.requestIP.value,f.txt_Nm_note.value);
	} else {
		return;
	}
}

function dobSendingGift(myid) {
	
	var f = document.Form1;
	

	if(f.txtRecv.value =="" ){
		alert("선물을 받을 회원을 선택 혹은 입력해주세요. ^^*");
		f.txtRecv.focus();					
		return;
	} 
	
	if(f.txtRecv.value ==myid ){
		alert("자기자신에게는 선물을 보낼실 수 없슶니다.");
		f.txtRecv.focus();					
		return;	
	}
	
	if(!chkStr(f.txtRecv)){
		alert("한명의 회원에게만 선물을 보내실 수 있습니다.");
		f.txtRecv.focus();
		return;
	}		
	
	if(f.txt_Nm_note.value.split(" ").join("") =="" ){
		alert("메시지를 남겨주세요. ^^*");
		f.txtRecv.focus();
		//return false;
		return;
	}
	else
	{
		lenm = CountCharLengh2(f.txt_Nm_note);
		if(lenm > 500){
			alert("\n 메시지의 길이가 500자가 넘습니다.");
			f.txt_Nm_note.focus();
			return;			
		}
	}
	if(f.requestIP.value == "")
	{
		alert('올바른 접근 방식이 아닙니다');
		return;
	}
	
	if(isProcess)
	{
		alert('처리중에 있습니다');
		return;
	}	

	doCheckDuplication(f.txtRecv.value);

}


function dobSendGift(id,buyAmount,ipAddress,msgContents) {
	
	isProcess = true;
	
    // add parameters 	  
	  var paramNames = new Array();
	  var paramValues = new Array();

	  paramNames[0] = "userId";
	  paramNames[1] = "buyAmount";
	  paramNames[2] = "userIp";
	  paramNames[3] = "msgContents";
	  paramValues[0] = id;
	  paramValues[1] = buyAmount;
	  paramValues[2] = ipAddress;
	  paramValues[3] = msgContents;

    // call
	  CallbShopWebService("SendGift", paramNames, paramValues, wbSendGiftProcess);	  
}

function wbSendGiftProcess() {
	// a readyState of 4 means we're ready to use the data returned by XMLHTTP
	if (objHttp.readyState == 4) {
	// get the return envelope
		var szResponse = objHttp.responseText;

		// success code
		if (objHttp.status == 200) {		
			var res = objHttp.responseXML.documentElement;	        
			var UserFlag = res.getElementsByTagName('UserFlag')[0].firstChild.data;	
			isProcess = false;	
			
			switch (UserFlag) 
			{
				case "0":	//성공       
					RecvUserId = res.getElementsByTagName('UserId')[0].firstChild.data;
					RecvUserKey = res.getElementsByTagName('UserKey')[0].firstChild.data;
					RecvUserNick = res.getElementsByTagName('UserNick')[0].firstChild.data;
					break;
				case "-1":
					alert('로그인을 하여 주십시요.');
					return false;
					break;					
				case "1":
					alert(res.getElementsByTagName('UserId')[0].firstChild.data + '님은 존재하지 않는 회원입니다');
					return false;
					break;
			}
			if(UserFlag == "0")
			{			
				var CashFlag = res.getElementsByTagName('CashFlag')[0].firstChild.data;
				switch (CashFlag) 
				{
					case "0":	//성공
						break;
					case "-1":
						alert('로그인을 하여 주십시요.');
						return false;
						break;
					case "1":
						alert('한빛캐시 잔액이 모자릅니다.');
						return false;
						break;
					case "-2":
						alert('구매 정보가 이상해요');
						return false;
						break;
					case "-3":
						alert('빌링 시스템을 점검 중입니다.');
						return false;
						break;
				}			
			}
		
			if(res.getElementsByTagName('SendFlag')[0].firstChild.data == "0")
			{			
				var f = document.Form1;
				var objNodeList = res.getElementsByTagName("MsgList");
		
				for (var i=0; i<objNodeList[0].childNodes.length; i++) {
					//선물 발송시 실시간 쪽지 기능 막음
					//SendMemoMsg(objNodeList[0].childNodes[i].firstChild.data);
				}						
				
				isProcess = false;	
				var cash = f.TotalAmt.value;
				var cnt_goods = f.ItemCnt.value;
				var top_nm_goods = f.Top_nm_goods.value;
				
				var url= "/h_shop/Characon/GiftSendComplete.aspx?own_user_id=" + RecvUserId + "&cash=" + cash + "&top_nm_goods=" + top_nm_goods + "&cnt_goods=" + cnt_goods +"&own_nick=" + RecvUserNick + "&from=bric" ;
				MM_openBrWindow(url,'popSndGiftConfirm','width=370,height=420');
				
				f.txtRecv.value = "";
				f.txt_Nm_note.value = "";
				location.href = "/h_shop/Characon/CharaconList.aspx?cd_m=4&cd_s=1&cd_ss=0&menuType=1";
			} else {

			}			

		} else {
			// unexcepted error occured     
		}
	}
}

function doCheckDuplication(id) {
	
    // add parameters 	  
	  var paramNames = new Array();
	  var paramValues = new Array();

	  paramNames[0] = "userId";
	  paramValues[0] = id;
		
	  isProcess = true;
    // call
	  CallbShopWebService("CheckDuplication", paramNames, paramValues, wCheckDuplicationProcess);	  
}

function wCheckDuplicationProcess() {
  // a readyState of 4 means we're ready to use the data returned by XMLHTTP
  if (objHttp.readyState == 4) {
	  // get the return envelope
	  var szResponse = objHttp.responseText;

    // success code
	  if (objHttp.status == 200) {		
		isProcess = false;
	    var res = objHttp.responseXML.documentElement;	  
	    var f = document.Form1;

	    switch (res.getElementsByTagName('DupFlag')[0].firstChild.data) {
	      case "0":	//성공        			
			if(confirm('한빛캐시 ' + f.TotalAmt.value + '원이 소요됩니다')) {	
				dobSendGift(f.txtRecv.value,f.TotalAmt.value,f.requestIP.value,f.txt_Nm_note.value);
			} else {
				return false;
			}
	        break;
	      case "-1":
	        alert('권한이 없습니다');
	        break;
	      case "1":
			if(confirm(f.txtRecv.value + '님이 ' + res.getElementsByTagName('DupMsg')[0].firstChild.data + ' 보유하고 있습니다~!\n\n' + '******************************************************\n\n' + '구슬 ' + f.TotalAmt.value + '알이 소요됩니다')) {	
				dobSendGift(f.txtRecv.value,f.TotalAmt.value,f.requestIP.value,f.txt_Nm_note.value);        				
			} else {
				return false;
			}
	        break;
	    }
    } else {
      // unexcepted error occured     
    }
  }
}



function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
	window.open(theURL,winName,features);
}
function OnVoteClick(cdgood, userkey)
{
  if(userkey == -1)
  {
	alert("예뻐요! 추가는 로그인 후에 가능합니다.");
	return false;
  }  
  else
  {
	if(!isProcess)
		doVote(cdgood, userkey);
  }
}

function doVote(cdgood, userkey) {
	  isProcess = true;
	  var paramNames = new Array();
	  var paramValues = new Array();

	  paramNames[0] = "userkey";
	  paramNames[1] = "cdGood";
	  paramValues[0] = cdgood;
	  paramValues[1] = userkey;
	  CallShopWebService("SetRecommand", paramNames, paramValues, wSetRecommand);	  
}

function wSetRecommand() {
  if (objHttp.readyState == 4) 
  {
	  var szResponse = objHttp.responseText;
	  if (objHttp.status == 200) 
	  {		
	    var res = objHttp.responseXML.documentElement;
	    var ret = res.getElementsByTagName('SetRecommandResult')[0].firstChild.data;
	    switch (ret) 
	    {
	      case "-1":
	        alert("이미 예뻐요! 에 투표하셨습니다.");
	        break;
	      case "-2":
	        alert("오류가 발생하였습니다.");
	        break;
	      default:
	        alert("예뻐요! 에 한표 추가되었습니다.");
	        document.getElementById('spVoteCount').innerText = ret;
	        break;    
	    }
    } 
    else 
    {
      alert("오류가 발생하였습니다.");
    }
  }
  isProcess = false;
}

function AlertLogin()
{
	alert("먼저 로그인해 주세요.");
	return false;
}

function BillingCheck()
{
	var bill = document.getElementById('billStatus');
	
	if(bill.value == "F")
	{
		alert("한빛캐시 서비스를 정기점검 (매주 화요일 05:00~08:00)하고 있어요. \n\n                     잠시만 기다려 주세요.");
		return false;
	} 
	else 
	  return true;
}

function SelectDataInsert(value)
{
  SelectData.push(value);
}
function SelectDataDelete(value)
{
  var tmp = new Array();
  for(var i =0;i<SelectData.length;i++)
  {
    if(SelectData[i] != value)
      tmp.push(SelectData[i])
  }
  SelectData = tmp;
}
function SelectDataDeleteByIndexKey(indexkey)
{
  var tmp = new Array();
  for(var i =0;i<SelectData.length;i++)
  {
    var arPrevSelect = SelectData[i].split('$');
    if(indexkey != arPrevSelect[0])
      tmp.push(SelectData[i])
  }
  SelectData = tmp;
}
function HiddenBind()
{
  var list;
  for(var i =0;i<SelectData.length;i++)
  {
    if(list == null)
      list = SelectData[i];
    else
      list = list + '@' + SelectData[i];
  }
  if(list == "undefined")
  {
    alert('상품을 선택하지 않으셨습니다.');
    return false;
  }
  document.getElementById('hCharaconSelect').value = list;
  return true;
}
function OnChangePeriod(checkObj, periodComboObj, priceObj)
{
  var selectvalue = periodComboObj.options[periodComboObj.selectedIndex].value;
  var arSelect = selectvalue.split('$');
  priceObj.innerText = arSelect[3];	
  if(checkObj.checked)
  {  
    SelectDataDeleteByIndexKey(arSelect[0]);
    SelectDataInsert(selectvalue);
  }
}
function OnCheck(checkObj, periodComboObj, type)
{
	var selectvalue = periodComboObj.options[periodComboObj.selectedIndex].value;

	if(type == 5)
	{
    var arSelect = selectvalue.split('$');     
    if(arSelect[0] == 0) 
    {
      for(var i=0; i<CheckBoxData.length;i++)
        document.getElementById("chk_" + CheckBoxData[i]).checked = false;
      SelectData = new Array();
    }  
    else
    {
      document.getElementById("chkMainGoods").checked = false;
      SelectDataDeleteByIndexKey(0);
    }  
	}
	if(checkObj.checked)
    SelectDataInsert(selectvalue);
  else
    SelectDataDelete(selectvalue);
}
function OnViewButtonClick(btObj)
{
  if(!BillingCheck())
    return false;
  
  btObj.click();
  return true;
}

function OnBasketButtonClick(btObj)
{
    btObj.click();
    return true;;
}

function OnViewOtherButtonClick(btObj, cdGood, nmName, type)
{
  if(!BillingCheck())
      return false;

  document.getElementById('hOtherSelect').value = cdGood + '$'+ nmName + '$'+ type;
  btObj.click();
	return true;      
}

function OnListChangeSort(url, SortObj)
{
  var selectIndex = SortObj.selectedIndex;
	var selectvalue = SortObj.options[selectIndex].value;
  window.location.href = url + '&sort=' + selectvalue;
  return false;
}
function OnListButtonClick(btObj, history, cdGood, nmGood)
{
  if(!BillingCheck())
      return false;

  document.getElementById('hCharaconCdGood').value = cdGood;
  document.getElementById('hCharaconNmGood').value = nmGood;
  document.getElementById('hCharaconHistory').value = history;
  document.getElementById(btObj).click();
	return true; 
}
