/*
/js/destInputControl2.js
*/
var priceRangeArr = new Array();
// 디폴트 마일리지 %
var milageDefaultRate = 0.1;
// geoActionGateWay() 펑션의 콜백함수 지정
var callBackFunc = "geoActionCallback";
//var callBackFunc = "OrderFormSteps";
// 최종 지불금액 값
var finalPayPrice = "";
// autoSuggestResultLi.click() 의 콜백함수 지정
//var destSelectCallBackFunc = "OrderFormSteps";
/*
지명검색 자동완성 모듈..
사용자 인풋이 발생하면 ajax 로 서버에 지명 질의를 하고,
리턴 json 으로 자동완성 리스트를 제시한다.
자동완성 항목중 하나가 클릭되면 해당 값으로 결정..
*/
// keyUp 의 딜레이를 주기위해, delay 를 설정하는 람다함수를 선언...
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
var searchInputVal = "";
var jsonSerialized = "";
$(document).ready( function() {
// 세션스토리지에 검색 결과가 존재하면 그 주소지 검색을 디폴트로 만들어준다.
if( sessionStorage.getItem("destAddressFullString") ) {
// swapDisplay( $(".orderDestUnselected"), $(".orderDestSelected") );
}
// else swapDisplay( $(".orderDestSelected"), $(".orderDestUnselected") );
/*
목적지 검색 input.focus 에 대응.. 스크롤 다운
*/
$(document).on( "focus", "#pointNameSearchInput", function() {
//console.log("focus");
$('html, body').animate({
scrollTop: $(".inquiryHeadlineDest").offset().top -80
}, 500);
});
/*
검색어 입력 keyup 에 반응하는 루틴... 그런데 서버속도가 많이 늦는다.
*/
$("#pointNameSearchInput").off().on( "keyup", function(e) {
var keyCode = e.keyCode || e.which;
if(e.keyCode == 13) {
console.log("Enter pressed!!");
e.preventDefault();
$(this).blur();
}
//console.log("키 입력 감지.....");
// destGeoId , destPointId 리셋...
$("#destGeoId").val( '' );
$("#destPointId").val( '' );
//console.log("keyUp!!!" +$(this).val().length );
// 항목 입력값이 한글 1.5자 이상일 때... "길3"
if($(this).val().length>=2) {
// delay .... 모든 keyUp 에 대응하지 않도록 딜레이를 걸어준다. 0.6sec
delay(function(){
searchInputVal = $("#pointNameSearchInput").val();
var serverActionUrl = $("#autoSuggestKeywordForm").attr("action");
var formStr = $("#autoSuggestKeywordForm").serialize()+"&callback=?";
//console.log("serverActionUrl: "+serverActionUrl +"?"+formStr );
$.getJSON( serverActionUrl, formStr, function(jsonObj) {
$(".destinationFullAddressText").html('').slideUp();
if(typeof jsonObj === "object" && jsonObj != null ) {
//console.log(jsonObj[0]);
if(jsonObj[0].addressBunji) {
// console.log("jsonObj[0].addressBunji: "+ jsonObj[0].addressBunji );
$(".searchResultDiv").slideUp();
$("#selectedDestinationAddress").slideUp();
showUpAutoSuggestList(jsonObj);
}
}
else {
//console.log("찾은게 없다.....");
failedAutoSuggestList();
//$("#autoSuggestResultUl").empty();
//$("#autoSuggestResultUl").append("
찾은게 없다.");
}
} );
}, 300 );
}
else {
//console.log("왜 전부 지워지냐???");
$("#autoSuggestResultUl").html('');
}
} );
/*
제안검색어 목록 클릭시....
선택된 검색어의 풀어드레스/포인트명을 폼 값으로 인스턴스 시킨다.
화면을 스크롤시킨다.
*/
$(document).on( "click", ".autoSuggestResultLi", function() {
// 클릭 시점의 유저인풋 스트링을 보관해둔다.
var userInputStringFinal = $("#pointNameSearchInput").val();
/*
console.log("list clicked!!!!");
consoleLogObject( $(this).data() );
consoleLogObject( $(this).data() );
console.log("geoId: "+$(this).attr("data-geoId") );
console.log("addressShort: "+$(this).attr('data-pointId'));
console.log("autoSuggestPointName: "+ $(this).find(".autoSuggestPointName").text() );
console.log("autoSuggestAddress: "+ $(this).find(".autoSuggestAddress").html() );
$("#destGeoId").val( $(this).attr("data-geoId") );
$("#destPointId").val( $(this).attr('data-pointId') );
*/
/* 2016-11-11 13:43 Ver. 3 */
if($(this).attr("data-addressBunji") && $(this).attr("data-pointName") && $(this).attr("data-xpos") && $(this).attr("data-ypos") ) {
var paramStr = "addressBunji="+$(this).attr("data-addressBunji")+"&addressDoro="+$(this).attr("data-addressDoro")
+"&pointName="+$(this).attr("data-pointName")+"&pointNameTail="+$(this).attr("data-pointNameTail")
+"&xpos="+$(this).attr("data-xpos")+"&ypos="+$(this).attr("data-ypos") ;
//console.log("paramStr : " + paramStr);
paramStr = encodeURI(paramStr);
$.getJSON( "/ajax/destPointSelectAction.php?"+paramStr+"&callback=?", function(jsonObj) {
if(typeof jsonObj === "object" && jsonObj != null ) {
//console.log("instanting geoId value: "+jsonObj.geoId);
$("#destGeoId").val( jsonObj.geoId );
$("#destPointId").val( jsonObj.pointId );
// 콜백 펑션 호출
// 2016-12-06 19:03
// destInputControl.js 모듈을 land 와 order 에서 공동사용하고있다.
// order 에서는 목록선택시 요금계산및 일련 프로세스가 트리거되어야 한다.
// 여기서 excute 되는 destSelectCallBackFunc 는 order.html 에서 사전정의된다.
if( typeof destSelectCallBackFunc !== "undefined" ) window[destSelectCallBackFunc]();
}
});
$("#destPointNameStr, .destPointName").val( $(this).find(".autoSuggestPointName").text()+' '+$(this).find(".autoSuggestPointNameTail").text() );
$("#destInputFullStr, .destFullAddr").val( $(this).find(".autoSuggestAddress").text() );
$("#destFullAddr").val( $(this).find(".autoSuggestAddress").text() );
$(".destinationFullAddressText").slideDown();
$("#pointNameSearchInput").addClass("approvedPointInput");
// display hide
$(".autoSuggestResult").slideUp();
// display on
$(".destinationAddress").slideDown();
// 구버전
$(".destinationPointNameText").text( $(this).find(".autoSuggestPointName").text() );
$(".destinationFullAddressText").text( $(this).find(".autoSuggestAddress").text() );
$(".destinationUserInputSpan").text( userInputStringFinal ).css("display","block");
// 신버전
$("#destPointNameSpan").text( $(this).find(".autoSuggestPointName").text()+' '+$(this).find(".autoSuggestPointNameTail").text() );
$("#destFullAddrSpan").text( $(this).find(".autoSuggestAddress").text() );
$(".orderDestSelected").slideDown();
$(".searchResultDiv, .inquieryResultChartDiv").slideUp();
}
else {
$("#pointNameSearchInput").removeClass("approvedPointInput");
}
// Scroll up
$('html, body').animate({
scrollTop: $(".inquireChargeFormHeadline").offset().top
}, 500);
} );
// 요금 인콰이어리 액션 버튼 클릭시...
// 1. 요금 JSON 을 받아와 처리... ---
// 2. 요금 구간별 통계 JSON 을 포함해서 받아와야 한다.
// 3. inquiryRecentOrders JSON 을 받아와 출력에 채워준다.
$(document).on("click", "#inquireChargeFormActionBtn", function(e) {
e.preventDefault();
if( $("#deptGeoId").val() =="" ) {
if( confirm("출발지 정보를 찾을 수 없습니다. 단말기의 현재위치를 읽도록 허용하시겠습니까?") ) {
ajaxLoadingScreenOn();
geoActionGateWay(callBackFunc);
}
}
else if( $("#destGeoId").val() =="" ) {
if( $(".autoSuggestResultLi").length <1 )
alert("죄송합니다. 목적지 지명검색 결과가 없습니다. 다시 검색해주세요.");
else alert("검색된 지명중 하나를 터치하여 선택해주세요.");
ajaxLoadingScreenOff();
return;
}
else {
//[lbl] genResultBlock;
ajaxLoadingScreenOn();
$("#loadingPopUpDiv").removeClass("display-none").center();
$("#loadingPopUpDiv .shortPopUpDivTxt1").text("구간 대리비를 조회중입니다..");
$(".orderDestSelected").slideDown();
var serverPHP = $("#inquireChargeForm").attr("action");
var serialized = $("#inquireChargeForm").serialize();
$.getJSON( serverPHP+"?"+serialized+"&callback=?", function(jsonObj) {
//console.log("#inquireChargeForm getJSON 액션!!!");
$("#loadingPopUpDiv").addClass("display-none");
$(".searchResultDiv").slideDown();
swapDisplay( ".inquiryUndoneDiv", ".inquiryDoneDiv" );
if( $("#searchResultShowDiv2").is(':visible') ) $("#selectChargeBlockH3Title").text("대리비 선택");
else $("#selectChargeBlockH3Title").text("먼저 대리비 조회를 해주세요");
//console.log("여기 오는가요.....???");
// 출력 데이터를 채워준다.
fillDriveChargeDigits(jsonObj);
// /ajax/inquiryOrders.php 를 호출해 JSON 을 받아온다.
// #RecentOrderSection 을 JSON 받아와 구성해준다.
//loadInquiryRecentOrderSection();
//console.log("#inquireChargeForm getJSON 의 배치 액션 종료!!");
// 요금 통계 차트 Div 를 구성한다. pricePieUL
//console.log("여기도 오는가요....??? : " + jsonObj.driveChargeSummary.driveChargeTotalCnt );
jsonSerialized = serializeFirstDimJSON(jsonObj);
$("#loadingPopUpDiv").removeClass("display-none");
$("#loadingPopUpDiv .shortPopUpDivTxt1").text("운행통계를 구성중입니다..");
setTimeout( function() {
$("#loadingPopUpDiv").addClass("display-none");
if(jsonObj.driveChargeSummary.driveChargeTotalCnt>0) makePricePieUL(jsonObj);
$(".loadingPopUpDiv").removeClass("display-none");
$("#loadingPopUpDiv .shortPopUpDivTxt1").text("구간 운행기록을 구성중입니다..");
setTimeout( function() {
$("#loadingPopUpDiv").addClass("display-none");
makeCarousel(jsonObj);
}, 3000 );
}, 3000 );
/*
$(".loadingPopUpDiv").removeClass("display-none");
$("#loadingPopUpDiv .shortPopUpDivTxt1").text("구간 운행기록을 구성중입니다..");
// 리턴받은 JSON 중 1차 배열만 serialize 해준다.
jsonSerialized = serializeFirstDimJSON(jsonObj);
//console.log("jsonSerialized : "+jsonSerialized);
// Carousel 을 구성해준다.
//console.log("Carousel 을 구성해준다.");
setTimeout( function() {
$("#loadingPopUpDiv").addClass("display-none");
makeCarousel(jsonObj);
}, 2500 );
*/
// Carousel 의 Headline 을 바꿔준다..
// postScripts JSON 을 받아와 출력해준다...
getNfillPostScripts( $("#deptGeoId").val() );
});
}
});
// 대리바구니담기 버튼 클릭시 -- gotoOrderIcon
$(document).on("click", "#addToCartBtn", function() {
var serverPHP = "/ajax/cartAction.php";
$.getJSON( serverPHP+"?mode=addCart&"+jsonSerialized+"&callback=?", function(jsonObj) {
//console.log("cartAction 액션!!!");
if( jsonObj.actionResult=="OK" ) {
shortPopUp( "대리바구니에 담았습니다." );
// shortPopUp 의 디폴트 버튼을 장바구니용 버튼셋으로 바꿔준다.
$(".modalPopupButtonDiv").html("대리바구니 보기 ");
}
else if( jsonObj.actionResult=="AuthFailed" ) shortPopUp( "허용되지 않는 요청입니다.", "Code No. "+jsonObj.ErrorCode );
else if( jsonObj.actionResult=="Duplicated" ) shortPopUp( "이미 바구니에 담긴 오더입니다.", "오더 수량은 대리바구니에서 변경하실 수 있습니다." );
});
});
// #inquireAgainBtn (조회 다시하기) 버튼 클릭시...
$(document).on("click", "#inquireAgainBtn", function() {
$(".searchResultDiv, .inquieryResultChartDiv").slideUp();
$("#inquireChargeFormActionBtn").css("display","block");
$("#addToCartBtn, #inquireAgainBtn, #destinationUserInputSpan").css("display","none");
$(".orderDestSelected").slideUp();
$("#inquiryRecentOrdersSection").slideUp();
resetInquiryResult();
});
});
// Carousel 을 구성해준다.
function makeCarousel(obj) {
//console.log("makeCarousel 펑션 액션!!");
$("#recentOrdersCarouselFrameDiv").children().not('article:first').remove();
$( obj.wholeOrders ).each( function( ind, ea ) {
//console.log("makeCarousel 의 루핑...");
//console.log("#carousel carouselEachBoxDeptAddrNPoints..." + ea.deptPoint );
//consoleLogObject( ea );
var $addedClone = $("#carouselEachBoxArchaeocytes").clone().attr("id","").removeClass("display-none").appendTo("#recentOrdersCarouselFrameDiv");
$addedClone.find(".carouselEachBoxDeptAddrNPoint").text( ea.deptPoint );
$addedClone.find(".carouselEachBoxDestAddrNPoint").text( ea.destPoint );
$addedClone.find(".carouselEachBoxDriveDistance").text( ea.driveDistance );
$addedClone.find(".carouselEachBoxDriveCharge").text( ea.driveCharge.format() );
$addedClone.find(".carouselEachBoxDriveDate").text( ea.driveDate );
} );
$(".recentOrdersHeadline").removeClass("display-none");
}
// 요금 통계 차트 Div 를 구성한다. pricePieUL
function makePricePieUL(obj) {
//console.log("여기 펑션에도 오는가???");
$(".inquieryResultChartDiv").removeClass("display-none").slideDown();
var areaNames = obj.areaNames;
$(".deptAreaName").text(obj.areaNames.deptArea);
$(".destAreaName").text(obj.areaNames.destArea);
$(".driveChargeTotalCnt").text(obj.driveChargeSummary.driveChargeTotalCnt);
$(".minDriveDate").text(obj.driveChargeSummary.minDriveDate);
//consoleLogObject(obj.areaNames);
// 차트 비우고,
$(".chartDataLeftUL").empty();
//$this->driveCharge[$i]['driveCharge']= $rows['driveCharge'];
$( obj.driveChargeArr ).each( function( ind, ea ) {
//consoleLogObject(ea);
//console.log("루프 작동.... ind " + ind );
//console.log("루프 작동.... cnt " + ea.cnt );
//if( ind > 0 ) {
var pr = ea.driveCharge;
var cnt = ea.percent;
$(".chartDataLeftUL").append(""+pr.format()+"원");
//console.log("li 가 추가되었다.... "+cnt);
//consoleLogObject(ea2);
//console.log("each 루프가 가동되었다.");
//console.log("배열의 위치 접근을 못하고있다.. arrCnt " + ea.arrCnt );
//console.log("배열의 위치 접근을 못하고있다.. arrCnt " + ea[1].driveCharge );
//}
//consoleLogObject(ea);
} );
$("#driveChargeSuggested").val(obj.defaultPrice);
//consoleLogObject(obj);
//if( typeof pricePieChart == "undefined" ) pricePieChart = makeEasyPie( "#pricePie" );
pricePieChart = makeEasyPie( "#pricePie" );
var pieVal = $(".pricePieUL li:nth-child(1) " ).data("percent");
updateEasyPie( pricePieChart, pieVal, $(this).data("id") );
$(".pricePieUL li:nth-child(1) " ).siblings().removeClass("selected");
$(".pricePieUL li:nth-child(1) " ).addClass("selected");
//updateEasyPie( pricePieChart, $(".pricePieUL li:nth-child(1) " ).data("percent"), "pricePie" );
}
// 자동완성 항목 리스트를 출력시킨다.
// 서버 Json : geoId, pointId, pointName, pointAddress
function showUpAutoSuggestList(jsonObj) {
//console.log("펑션 호출.....");
$("#autoSuggestResultUl").html('');
if(jsonObj.length>0) {
$.each(jsonObj, function( key, eachArr ) {
//console.log("리스트추가: "+ eachArr.pointName + eachArr.pointNameTail );
//console.log("리스트추가: "+ eachArr.addressBunji );
var pointNameLiStr = "";
if( typeof eachArr.pointName!="undefined" ) {
pointNameLiStr = (eachArr.pointName).trim();
if(eachArr.pointNameTail.length>2) pointNameTailStr = "("+eachArr.pointNameTail+")";
else pointNameTailStr = "";
}
$("#autoSuggestResultUl").append(""+pointNameLiStr+""+pointNameTailStr+
""+eachArr.addressBunji+"");
$("#autoSuggestResultUl").childTxtClass( searchInputVal,'red');
});
$(".autoSuggestResult").css("display","block");
$("#autoSuggestResultUl").slideDown();
}
}
// 자동완성 목록을 찾지 못했을 때..
function failedAutoSuggestList() {
$("#autoSuggestResultUl, .destinationFullAddressText").html('');
$("#autoSuggestResultUl").append("죄송합니다. 검색결과가 없습니다.");
$(".autoSuggestResult").css("display","block");
$("#pointNameSearchInput").removeClass("approvedPointInput");
}
// 받아온 요금을 html 에 채워넣는다.
function fillDriveChargeDigits( obj ) {
var maxPrice = obj.priceRange3;
if(obj.priceRange5) maxPrice = obj.priceRange5;
else if(obj.priceRange4) maxPrice = obj.priceRange4;
// $(".driveChargeDefault").text( obj.defaultPrice.format() );
$("#driveChargeSuggested").val(obj.defaultPrice);
$("#driveChargeUserSelected").val(obj.defaultPrice);
//console.log("#driveChargeSuggested value updated: "+obj.defaultPrice );
$(".driveDistance").text( obj.driveDistance );
$("input[name=driveDistance]").val( obj.driveDistance );
$(".searchResultDiv").slideDown();
$("ul.actions.fit li").css("display","table-cell");
$(".gotoOrderBtnLi").css("display","table-cell");
$("#inquireChargeFormActionBtn").css("display","none");
$("#addToCartBtn, #inquireAgainBtn").css("display","block").addClass("");
// odometer 이펙트로 받아온 밸류 인스턴스..
if( typeof odometer !== "undefined") {
// setTimeout(function(){
//odometer.innerHTML = obj.defaultPrice;
// odometer 가 클래스 매칭되는 모든 요소를 일괄 처리해주지 않더라.
// 게다가 밸류 인스턴스도 안되게 인터셉트 하기 때문에, odometer 적용된 요소 하나하나 밸류를 넣어줘야 한다.
$(".driveChargeDefault").html( obj.defaultPrice );
$("#driveChargeDigits").html( obj.defaultPrice );
if(typeof obj.priceRange0 !=="undefined") $(".driveChargeMin").text( obj.priceRange0.format() );
$(".driveChargeMax").text( maxPrice.format() );
//console.log("obj.defaultPrice 의 내용 : "+obj.defaultPrice);
ajaxLoadingScreenOff();
// }, 600);
}
// 구버전.. odometer 없이 값만 인스턴스 해준다.
else {
$(".driveChargeDefault").text( obj.defaultPrice.format() );
$(".driveChargeMin").text( obj.priceRange0.format() );
$(".driveChargeMax").text( maxPrice.format() );
}
// 선택가능 요금 어레이 준비
priceRangeArr.length = 0;
if(obj.priceRange0) priceRangeArr[0]= obj.priceRange0;
if(obj.priceRange1) priceRangeArr[1]= obj.priceRange1;
if(obj.priceRange2) priceRangeArr[2]= obj.priceRange2;
if(obj.priceRange3) priceRangeArr[3]= obj.priceRange3;
if(obj.priceRange4) priceRangeArr[4]= obj.priceRange4;
if(obj.priceRange5) priceRangeArr[5]= obj.priceRange5;
//makeChargeAdjuster(priceRangeArr);
//console.log("priceRange0: "+priceRangeArr[0]);
//$(".chargeAdjuster").css("display","inline");
//$("#driveChargeDigits").text( $("#driveChargeDigits").text().format() );
// 예정 마일리지 업데이트
var milageWillGiven = calcMilage($("#driveChargeUserSelected").val(), priceRangeArr);
$("#milageWillBeGivenStr").text( milageWillGiven.format() );
$("#milageWillBeGivenInput").val(milageWillGiven);
// 최종 결제금액 값과 출력을 무결하게 유지한다.
//makeFinalPayPrice();
// 여기서는 요금쿼리의 첫번째 스텝이므로, 최종지불금액은 단순계산금액으로 간단히 인스턴스해준다.
// 최종지불금액 업데이트
finalPayPrice = $("#driveChargeUserSelected").val();
if(typeof finalPayPrice != "undefined" && finalPayPrice.length > 3) $("#finalPayPriceStr").text( finalPayPrice.format() );
//console.log("펑션 fillDriveChargeDigits 의 마지막");
}
// 요금검색 결과를 리셋한다.
function resetInquiryResult() {
$(".driveDistance, .driveChargeDefault, .driveChargeMin, .driveChargeMaxm .odometer-inside ").html('0');
//console.log("reset called!!!");
}
// 선택된 금액에 대해 차별적인 마일리지를 리턴한다.
function calcMilage(price, priceRangeArr) {
price = parseInt(price);
var len = priceRangeArr.length;
if(priceRangeArr[0]==price) return Math.round( price*( milageDefaultRate*0.005 ) )*100;
else if(priceRangeArr[1]==price && priceRangeArr[4]) return Math.round( price*( milageDefaultRate*0.0075 ) )*100;
else return price*milageDefaultRate;
}
// JSON 의 일차원 배열들만 serialize 해준다.
function serializeFirstDimJSON(obj) {
var serializedStr = "";
$.each( obj, function(ky, vl) {
//console.log( "typeof : "+ky+" : " + typeof vl );
if(typeof vl !== "object") serializedStr += ky+"="+vl+"&";
});
return serializedStr;
}
// 엘리먼트 자식요소의 모든 매칭 텍스트에 class 를 부여한다.
// 자동완성 하위 매칭 텍스트에 class 를 추가해줄 때 사용.
/**** usage: $(selector).childTxtClass( searchInputVal,'red'); ****/
jQuery.fn.childTxtClass = function (pattern, className) {
var regex = new RegExp("#" + pattern + "#", "g");
this.children().filter( function() {
return this.innerHTML.match(regex);
}).addClass(className);
return this;
}