[더페이스샵] 1+1 피부 보습 지키기 프로젝트 - 미미박스(Memebox)
429,762 개의 상품 1,734,256 개의 리뷰
12월 마지막 특가! 놓치지 마세요!~ [더페이스샵] 1+1 피부 보습 지키기 프로젝트
'; // // $('#imageListWrapper').append(image); // // // // input files tag 추가 // $('#writeReviewModalWrap input:file').hide(); // // if ( $('#writeReviewModalWrap input:file').length < 4 ) { // // input files 추가 // addNewInputFile(); // } // }); /** * .x button click event */ // $(document).on('click', '.x', function(event) { // // event.preventDefault(); // // //target // var target = $(this).attr('value'); // // filename 취득 // var fileName = $(this).attr("name"); // // img 삭제 // $('div[name="' + fileName + '"]').remove(); // // input file 삭제 // $('input[name="' + fileName + '"]').remove(); // // var imageSize = Number($(this).attr('fileSize')); // sumImageSize -= imageSize; // // // 파일추가 // if( $('#writeReviewModalWrap input:file').length < maxImageCount && // $('input[name="filename"]').length === 0 ) { // addNewInputFile(); // } // }); // 리뷰 리스트 페이징 function getReviewPage(page) { var selectors = $(".select"); var selectorsIds = []; var skinType = 0; var orderType = $("#actOrder option:selected").val(); var selectedOrderIdx = $("select[name='actOrder'] option:selected").index(); var contentViewPickOption = $("#contentOrder option:selected").val(); var contentViewPickSelectedOrderIdx = $("select[name='contentOrder'] option:selected").index(); var apiUrl = '/ajax/reviews?productId=' + '521370' +'&skinType='+ skinType + '∨derType=' + orderType + '&page=' + page + '&contentViewPickOption=' + contentViewPickOption; selectors.each(function(index, item){ var option = $(item); if(option.val() !== '') { apiUrl += '&optionValue[' + index + ']=' + option.val(); selectorsIds.push({name: option.attr('name'), index: option.prop("selectedIndex")}); } }); $.ajax({ type: 'get', url: apiUrl, cache: false }).done(function(res) { scrollToDealDetail(); $('#dealReview').html(res); $('#actOrder option')[selectedOrderIdx].selected = true; $('#actOrder [value="'+ orderType+ '"]').selected = true; $('#contentOrder [value="'+ contentViewPickOption+ '"]').selected = true; $("#contentOrder option")[contentViewPickSelectedOrderIdx].selected = true; $.each(selectorsIds, function(index,item){ $('.select[name='+item.name+']').prop('selectedIndex', item.index); }); $('.reviewSelect').selectric(); //$(document.body).scrollTop($('#dealReview').offset().top); $('a[rel^=lightbox]').lightBox({ overlayBgColor: '#000', overlayOpacity: '0.5', keyToPrev: 'a', keyToNext: 's', keyToClose: 'd', maxWidth: 615, maxHeight: 370 }); }).fail(function(res) { return false; }); } // select box 타입별 리뷰 리스트 조회 function getReviewList (obj) { var selectors = $(".select"); var selectorsIds = []; var skinType = 0; var orderType = $("#actOrder option:selected").val(); var selectedOrderIdx = $("select[name='actOrder'] option:selected").index(); var contentViewPickOption = $("#contentOrder option:selected").val(); var contentViewPickSelectedOrderIdx = $("select[name='contentOrder'] option:selected").index(); var apiUrl = '/ajax/reviews?productId=' + '521370' + '&skinType='+ skinType + '∨derType=' + orderType + '&contentViewPickOption=' + contentViewPickOption; selectors.each(function(index, item){ var option = $(item); if(option.val() !== '') { apiUrl += '&optionValue[' + index + ']=' + option.val(); selectorsIds.push({name: option.attr('name'), index: option.prop("selectedIndex")}); } }); $.ajax({ type: 'get', url: apiUrl, cache: false }).done(function(res) { $('#dealReview').html(res); $('#actOrder option')[selectedOrderIdx].selected = true; $('#contentOrder [value="'+ contentViewPickOption+ '"]').selected = true; $("#contentOrder option")[contentViewPickSelectedOrderIdx].selected = true; $.each(selectorsIds, function(index,item){ $('.select[name='+item.name+']').prop('selectedIndex', item.index); }); $('.reviewSelect').selectric(); $('a[rel^=lightbox]').lightBox({ overlayBgColor: '#000', overlayOpacity: '0.5', keyToPrev: 'a', keyToNext: 's', keyToClose: 'd', maxWidth: 615, maxHeight: 370 }); return false; }).fail(function(res) { return false; }); } '; // html.push(option); // }); for(var i=0; i'+band.name+''; html.push(option); } html.push(base[2]); $('.order-product__content').prepend(html.join('')); self.initSelectbox($('.select_band')); }, article: function(step, params){ _logger('Render.article', params.data); var self = this; var label = ''; switch(step){ case 0: label = "첫번째"; break; case 1: label = "두번째"; break; case 2: label = "세번째"; break; default: label = (step+1)+'번째'; } // params.options.length 가 옵션 갯수 // 1이상이면 aritcle은 순서(첫번째, 두번째..)를 표시하지 않아야 함 // 1이면 opton은 순서(첫번째, 두번째..)를 표시하지 않아야 함 if(params.options.length > 0){ label = ''; } if(params.style === 'DEFAULT'){ label = ''; }else if(params.style === 'MERGE'){ label = '(' + params.title + ') ' + label; } var base = self.baseSelectbox({step: step, type: 'article', label: label+' 상품'}); var html = [base[0], base[1]]; // params.data.map(function(article){ // var option = ''+article.name+''; // html.push(option); // }); for(var i=0; i'+article.name+''; html.push(option); } html.push(base[2]); if ( !($('.order-product__item').hasClass('is-visible')) ) { $('.order-product__item').addClass('is-visible'); } $('.order-product__item').append(html.join('')); self.initSelectbox($('.select_article_'+step)); if(deal.isAddCart === false){ $('.order-product__item .select_article_'+step).selectric('open'); } deal.isAddCart = false; }, option: function(step, params){ _logger('Render.option'); var self = this; var label = ''; switch(step){ case 0: label = "첫번째"; break; case 1: label = "두번째"; break; case 2: label = "세번째"; break; default: label = (step+1)+'번째'; } // params.options.length 가 옵션 갯수 // 1이상이면 aritcle은 순서(첫번째, 두번째..)를 표시하지 않아야 함 // 1이면 opton은 순서(첫번째, 두번째..)를 표시하지 않아야 함 if(params.options.length === 1){ label = ''; } var base = self.baseSelectbox({step: step, type: 'option', label: label+' 옵션'}); var html = [base[0], base[1]]; // params.data.map(function(article){ // var option = ''; // html.push(option); // }); for(var i=0; i'; html.push(option); } html.push(base[2]); if ( !($('.order-product__item').hasClass('is-visible')) ) { $('.order-product__item').addClass('is-visible'); } $('.order-product__item').append(html.join('')); self.initSelectbox($('.select_article_'+step)); if(deal.isAddCart === false){ $('.order-product__item .select_article_'+step).selectric('open'); } deal.isAddCart = false; }, depended: function(data){ _logger('Render.depended', data); var self = this; var base = self.baseSelectbox({step: 0, type: 'depended', label: '추가 구성상품'}); var html = [base[0], base[1]]; // data.map(function(article){ // var option = ''+article.name+''; // html.push(option); // }); for(var i=0; i'+article.name+''; html.push(option); } html.push(base[2]); if ( !($('.order-depended__item').hasClass('is-visible')) ) { $('.order-depended__item').addClass('is-visible'); } $('.order-depended__item').html(html.join('')); self.initSelectbox($('.select_depended')); }, cartItem: function(data){ var tmpl = Handlebars.templates['dealCartItems']; if(!tmpl){ _logger('!tmpl cartItem') return false; } var html = tmpl(data.article); if(data.article.type !== 'DEPENDED'){ $('.order-selected__block').show(); $('.order-selected__block .order-selected__list').map(function(item){ if($(this).data('type') === 'default'){ $(this).prepend(html); } }); }else{ $('.order-selected__block-additional').show(); $('.order-selected__block-additional .order-selected__list').map(function(item){ if($(this).data('type') === 'depended'){ $(this).prepend(html); } }); } if(deal.readOnly === true){ if (data.article.type !== 'DEPENDED') { $('.item-delete').hide(); } } }, makeSelectOption: function(optionItemInfo){ var optionItemClassName = optionItemInfo.data.thumbnail || optionItemInfo.data.isimage ? 'option-item has-thumbnail' : 'option-item' ; var emptyImage = optionItemInfo.data.isimage? ' ' : ''; var optionItemHtml = ''; optionItemHtml += ''; optionItemHtml += optionItemInfo.data.thumbnail ? ' ' : emptyImage; optionItemHtml += '' optionItemHtml += '' + optionItemInfo.text + ''; optionItemHtml += optionItemInfo.data.price ? '' + $.number(optionItemInfo.data.price) + '원' : ''; optionItemHtml += '' optionItemHtml += '' optionItemHtml += ''; return optionItemHtml; }, initSelectbox: function(object){ var self = this; $(object).selectric({ responsive: true, inheritOriginalWidth: false, maxHeight: 250, labelBuilder: function(currItem) { var labelItemHtml = ''; if (currItem.data.type && currItem.value === '0') { labelItemHtml = '' + currItem.data.type + '을 ' + currItem.text; } else { labelItemHtml = self.makeSelectOption(currItem); } return labelItemHtml; }, optionsItemBuilder: function(itemData) { var optionItemHtml = self.makeSelectOption(itemData); return optionItemHtml; }, onBeforeOpen: function() { $('.selectric-items li[data-index="0"]').css('display', 'none'); }, onChange: function(element, selectric) { var classList = $(element).attr('class').split(' '); // var selectboxName = classList.find(function(item){ return item.indexOf('select_') >= 0;}); var selectboxName = null; for(var i=0; i= 0){ selectboxName = item; break; } } _logger('\tSelectric onChange :', selectboxName, $(element).val()); if ($(element).val() === '0') { $(selectric.elements.wrapper).removeClass('selectric-change'); return false; } else { $(selectric.elements.wrapper).addClass('selectric-change'); } }, onOpen: function(element){ var classList = $(element).attr('class').split(' '); // var selectboxName = classList.find(function(item){ return item.indexOf('select_') >= 0;}); var selectboxName = null; for(var i=0; i= 0){ selectboxName = item; break; } } _logger('\tSelectric onOpen :', selectboxName, $(element).val()); if($(element).val() !== '0'){ $(element).val(0); $(element).selectric('refresh'); $(element).selectric('open'); } // 밴드가 열린경우 article/option 삭제, article/option 이 열린경우 하위 selectbox 삭제 if(selectboxName === 'select_band'){ $('.order-product__item').empty(); }else if(selectboxName.indexOf('select_article_') >= 0){ var splitData = selectboxName.split('_'); if(splitData.length !== 3){ return false; } var step = parseInt(splitData[2]); $.each($('.order-product__item').find('select'), function(){ var _classList = $(this).attr('class').split(' '); // var _selectboxName = _classList.find(function(item){ return item.indexOf('select_') >= 0;}); var _selectboxName = null; for(var i=0; i<_classList.length; i++){ var item = _classList[i]; if(item.indexOf('select_') >= 0){ _selectboxName = item; break; } } var _splitData = _selectboxName.split('_'); if(_splitData.length !== 3){ return false; } if(parseInt(_splitData[2]) > step){ $(this).selectric('destroy'); $(this).remove(); } }); } }, onClose: function(element) { var classList = $(element).attr('class').split(' '); // var selectboxName = classList.find(function(item){ return item.indexOf('select_') >= 0;}); var selectboxName = null; for(var i=0; i= 0){ selectboxName = item; break; } } _logger('\tSelectric onClose :', selectboxName, $(element).val()) var selectValue = (/^\d+$/.test($(element).val()))? parseInt($(element).val()) : $(element).val(); if(selectValue === 0){ _logger('\tskip close action'); return false; } if(selectboxName.indexOf('band') >= 0){ deal.selectBand(selectValue); }else if(selectboxName.indexOf('article') >= 0){ var step = selectboxName.split('_'); deal.selectBandArticle(parseInt(step[2]), selectValue); }else{ _logger('addDependedCartItem', selectboxName, selectValue) deal.addDependedCartItem(selectValue); } // 다른위치의 동일한 selectbox 도 동일한 값으로 셋팅함 $.each($('.order-product__item').find('select'), function(){ var _classList = $(this).attr('class').split(' '); // var _selectboxName = _classList.find(function(item){ return item.indexOf('select_') >= 0;}); var _selectboxName = null; for(var i=0; i<_classList.length; i++){ var item = _classList[i]; if(item.indexOf('select_') >= 0){ _selectboxName = item; break; } } if(selectboxName === _selectboxName && selectValue !== $(this).val()){ $(this).val(selectValue); $(this).selectric('refresh'); } }); } }); // $(object).selectric('open'); sidebarContentHeight(); }, bandsDetail: function(bandId, data){ _logger('Render.bandsDetail'); if(!data || !bandId){ alert('일시적인 오류입니다. 잠시후 다시 시도해 주세요.'); return false; } // 우선 렌더링할 페이지 구하기 var showIndexList = []; for(var key = 0; key<=data.length; key++){ if(data[key].id === bandId){ if(key > 0){ showIndexList.push(key-1); } showIndexList.push(key); if(key <= data.length-1){ showIndexList.push(key+1); } break; } } // var bands = data.map(function(band, key){ // var copyObj = Object.create(band); // if(showIndexList.indexOf(key) === -1){ // copyObj['contents'] = []; // } // return copyObj; // }); var bandDatas = []; for(var i=0; i '); }else if(contents.type === 'VIDEO'){ html.push('
'); }else{ html.push(contents.text); } } if(html.length > 0){ $('.bandContents_'+bandId).html(html.join('')); } }else{ _logger('\tskip render '+ bandId); } }, dealDetail: function(data){ $('#dealContent').html(data); // 밴드 상세정보 클릭/옵션선태 버튼 클릭 // deal 객체가 이미 있다고 가정함 $.each($('#dealContent').find('div'), function(){ if($(this).attr('id') && $(this).attr('id').indexOf('band') >= 0){ try{ var bandId = $(this).attr('id').split("_")[1]; var dealId = $(this).data('dealid'); var self = $(this); $.each(bands, function(k, v){ if(v.id === parseInt(bandId) && v.articleStatus !== 'OPENED'){ self.addClass('is-sold-out'); } }); if($(this).attr('class').indexOf('is-sold-out') === -1){ $.each($(this).find('button'), function(){ if($(this).attr('class').indexOf('status__sale-detail') >= 0){ $(this).on('click', function () { _logger('click detail', bandId, dealId); try{ deal.showBandDetail = true; deal.loadBandsDetail(bandId); }catch(e){} }); }else if($(this).attr('class').indexOf('status__sale-option') >= 0){ $(this).on('click', function () { _logger('click option', bandId, dealId); try{ deal.selectBand(bandId); }catch(e){} // 딜상세에서 밴드 선택 try{ analytics.track('Band Select', { id: '521370', // Product ID name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트', // Product Name band_id: bandId, // bandId band_name: deal.selectionBand.name // bandName }); }catch(e){} }); } }); } }catch(e){ _logger(e); } } }); try { var arrLink = $('#dealDetail').find('a'); $.each(arrLink, function() { if($(this).attr('href').indexOf('memebox://uri/parse?url=http://m.') >= 0) { this.href = $(this).attr('href').replace('memebox://uri/parse?url=http://m.', 'http://m.'); } if($(this).attr('href').indexOf('memebox://uri/parse?url=http://www.') >= 0) { this.href = $(this).attr('href').replace('memebox://uri/parse?url=http://www.', 'http://m.'); } }); } catch(e) { } }, relatedContents: function(data){ var tmpl = Handlebars.templates['dealRelatedContents']; if(tmpl){ var html = tmpl(data); $("#relatedContents").html(html); _logger('Render.relatedContents', data); } }, recommendation: function(data){ var tmpl = Handlebars.templates['dealRecommendation']; if(tmpl){ var html = tmpl(data); $("#recommendationDeals").html(html); _logger('Render.recommendation', data); } }, delivery: function(data){ var tmpl = Handlebars.templates['dealDelivery']; if(tmpl){ var html = tmpl(data); $("#dealDeliveryInfo").html(html); _logger('Render.delivery', data); } }, articleInfo: function(data){ var tmpl = Handlebars.templates['dealInfo']; if(tmpl) { var html = tmpl(data); $("#dealInfo").html(html); _logger('Render.articleInfo', data); // 상품안내 변경처리 if ($('#dealInfo .infoOptionItem').length < 2) { var itemName = $('.infoOptionItem').text(); $('#dealInfo .linkSelect').hide(); $('#dealInfo .linkSelect').replaceWith('
'); } else { $('#dealInfo .linkSelect').selectric({ labelBuilder: function(currItem) { return currItem.text; }, optionsItemBuilder: function(itemData, element) { return '' + itemData.text + ''; }, onChange: function() { if($(this).val() === "0"){ return false; } var $targetEle = $('.'+$(this).val()); $('#dealInfo .information').hide(); $targetEle.show(); } }); } } } }; var Article = function(data){ return { id: data.id, name: data.name, salePrice: data.salePrice, status: data.status, type: data.type, image: data.image, isImage: (data.isImage)? data.isImage : false }; }; var ArticleOption = function(data){ return { name: data.name, status: data.status } }; var Band = function(data){ return { id: data.id, seq: data.seq, articleStatus: data.articleStatus, name: data.name, originPrice: data.originPrice, salePrice: data.salePrice, image: data.image, status: data.articleStatus, articles: [], selections: [], optionStyle: data.optionStyle, options: data.options, contents: data.contents, addSaleItems: function(step, articles){ _logger('Band.addSaleItems', step, articles) var self = this; if(typeof articles === 'undefined'){ return false; } // let isImage = !!(articles.items.find(function(item){ return (item.contents && item.contents.length > 0 && item.contents[0].content); })); var isImage = null; for(var i=0; i 0 && item.contents[0].content){ isImage = item; break; } } self.articles = self.articles.slice(0, step); // self.articles.push({ // type: articles.type, // data: articles.items.map(function(item){ // if(item.contents && item.contents.length > 0 && item.contents[0].content){ // item['image'] = item.contents[0].content.uri; // } // item['isImage'] = isImage; // return (articles.type === 'article')? Article(item) : ArticleOption(item); // }) // }); var dataList = []; for(var i=0; i 0 && item.contents[0].content){ item['image'] = item.contents[0].content.uri; } item['isImage'] = isImage; dataList.push((articles.type === 'article')? Article(item) : ArticleOption(item)); } self.articles.push({ type: articles.type, data: dataList }); /** * 1. 선택한 band의 article selectbox 생성 : .order-product__item **/ var options = { style: self.optionStyle, data: self.articles[step].data, options: self.options }; if(self.articles[step].type === 'article'){ options['title'] = (self.options.length > 0)? self.options[0].title : ''; Render.article(step, options); }else{ Render.option(step, options); } }, addSelection: function(step, value){ _logger('Band.addSelection', step, value) var self = this; /* * 선택한 다음스텝의 selectbox 는 모두 삭제 * */ self.resetSelection(step); self.selections.push(value); }, resetSelection: function(step){ _logger('Band.resetSelection', step) var self = this; if(typeof step === 'undefined' || step > self.selections.length){ return false; } self.selections = self.selections.slice(0, step); /** * 1. step + 1 부터 selectbox 삭제 : .order-product__item **/ step++; $.each($('.order-product__item').find('select'), function(){ var classList = $(this).attr('class').split(' '); // var selectboxName = classList.find(function(item){ return item.indexOf('select_') >= 0;}); var selectboxName = null; for(var i=0; i= 0){ selectboxName = item; break; } } var splitName = selectboxName.split('_'); if(parseInt(splitName[2]) >= step){ $(this).selectric('destroy'); $(this).remove(); } }); } }; }; var CartItem = function(){ return { article: null, qty: 1, pointRate: 1, totalPrice: 0, addPoint: 0, init: function(data){ var self = this; self.article = data.article; self.qty = data.qty || 1; self.pointRate = data.pointRate || 1; self.calcTotal(); }, changeQty: function(qty){ this.qty = qty; this.calcTotal(); }, calcTotal: function () { this.totalPrice = this.article.salePrice * this.qty; this.addPoint = Math.ceil((this.totalPrice * this.pointRate) / 100); } } }; var Cache = function(){ return { cacheData: {}, add: function(key, value){ _logger('\tCache.add', key, value); this.cacheData[key] = value; return true; }, remove: function(key){ _logger('\tCache.remove', key); this.cacheData[key] = null; }, get: function(key){ if(this.cacheData[key]){ _logger('\tCache.get', key, this.cacheData[key]); } return this.cacheData[key]; } } }; var Deal = function(){ return { selectionBand: null, bands: [], bandsDetail: null, dependArticles: [], cartItems: [], showBandDetail: false, setBandDetailId: null, submit: false, readOnly: false, cache: Cache(), isAddCart: false, buyLimit: { min: { deal: 1, article: 1 // 1003xxxx: 최소 xxxx }, max: { deal: 999, // 150000xx: 최대 xx개, 150003xx: 최대 xx회(구매횟수), 15xxxyyy: xxx일 최대 yyy개 article: 999 // 1004xxxx: 최대 xxxx개 } }, init: function(){ var self = this; var policyItems = '[20030001,20050001,21000098,10040010,20010005]'; if(!policyItems || policyItems === '[]'){ return false; } try{ policyItems = JSON.parse(policyItems); for(var i = 0; i< policyItems.length; i++){ var item = parseInt(policyItems[i]); // deal은 구현하지 않기로 함 if(item >= 10040001 && item <= 10049999){ self.buyLimit.max.article = (item % 10040000 > 0)? item % 10040000 : 1; }else if(item >= 10030001 && item <= 10039999){ self.buyLimit.min.article = (item % 10030000 > 0)? item % 10030000 : 1; } } }catch(e){ return false; } }, addBands: function(bands){ var self = this; if(typeof bands !== 'object'){ return false; } _logger('Deal.addBands', bands); self.bands = []; // bands.map(function(band){ // if(band.contents && band.contents.length > 0 && band.contents[0].content){ // band['image'] = band.contents[0].content.uri; // } // self.bands.push(Band(band)); // }); for(var i=0; i 0 && band.contents[0].content){ band['image'] = band.contents[0].content.uri; } self.bands.push(Band(band)); } }, selectBand: function(bandId){ var self = this; _logger('Deal.selectBand', bandId); if(bandId !== null && $('.select_band').length >= 1){ $('.select_band').map(function(){ if(parseInt($(this).val()) !== bandId){ $(this).val(bandId); $(this).selectric('refresh'); // $(this).selectric('close'); } }); } if(self.readOnly){ return false; } var self = this; self.setSelectionBand(bandId); _logger('\tset selectband', self.selectionBand); /** * article / option 초기화 */ $('.order-product__item').empty(); _logger('\tempty : order-product__item') if(bandId === null){ $('.select_band').val('0'); $('.select_band').selectric('refresh'); }else{ self.selectionBand.selections = []; self.loadSaleItems({step: 0}); } }, setSelectionBand: function(bandId){ var self = this; bandId = parseInt(bandId); self.selectionBand = null; // self.bands.map(function(band){ // if(band.id === bandId){ // self.selectionBand = band; // } // }); for(var i=0; i< res.data.length; i++){ var band = res.data[i]; bands.push(new Band(band)); } /** * 1. 선택한 밴드 정보를 this.selectionBand 에 할당 * 2. band 상세설명 띄우기 **/ // self.setSelectionBand(bandId); self.bandsDetail = bands; Render.bandsDetail(parseInt(bandId), self.bandsDetail); } }); }, loadSaleItems: function(params){ _logger('Deal.loadSaleItems', params); /** * 추가구성 상품(params.depended === true) 은 bandId, selectItems를 보내지 않음 **/ var self = this; if(typeof params.depended === 'undefined'){ params['depended'] = false; } var bandId = (params.depended || self.selectionBand.id < 1)? null : self.selectionBand.id; var selectItems = (params.depended)? [] : self.selectionBand.selections; var cacheKey = 'band_'+ ((bandId === null)? -1 : bandId); if(params.depended === true){ cacheKey += '_depended' } var options = { type: 'post', url: '/ajax/product/521370/saleItems', data: { productId: parseInt('521370'), bandId: bandId, selectItems: selectItems, depended: (!params.depended)? false: params.depended }, cache: false, cacheKey: cacheKey }; self.loadAjaxData(options, function (err, res){ if(err && err.msg){ alert(err.msg); return false; } if(!res.data.selected && (params.step === 0 || params.depended === true)){ self.cache.add(cacheKey, res); } _logger('\tajax', res); var items = res.data.items; var isSmartOption = false; // 최종선택 상품 -> 장바구니 담기 대상 if(res.data.selected){ var selectArticle = res.data.selected; if(selectArticle && selectArticle.contents && selectArticle.contents.length > 0 && selectArticle.contents[0].content){ selectArticle['image'] = selectArticle.contents[0].content.uri; } self.addCartItem(Article(selectArticle)); if(self.showBandDetail === false){ self.selectBand(((self.bands.length > 1)? null: -1)); }else{ $('.order-product__item').empty(); self.selectionBand.selections = []; self.loadSaleItems({step: 0}); } }else if(isSmartOption === false && items.length === 1 && items[0].type === 'DEFAULT'){ $('#openBands').remove(); self.selectionBand.selections.push(items[0].id); self.readOnly = true; self.loadSaleItems(params); }else if(typeof params.depended === 'undefined' || params.depended === false) { // 다음단계 article or option self.selectionBand.addSaleItems(params.step, res.data); }else{ // 추가구성 상품 self.addDependArticle(res.data.items) } return false; }); }, loadDetail: function(){ var self = this; var options = { type: 'get', url: '/ajax/product/521370/detail', data: {}, cache: false }; self.loadAjaxData(options, function(err, result){ if(err || !result.data || !result.data.contents){ alert('일시적인 오류 입니다.'); return false; } if(result.data.contents) { Render.dealDetail(result.data.contents); _logger('loading: deal contents'); } if(result.data.relatedContents){ Render.relatedContents(result.data.relatedContents); } }); }, loadRecommencation: function(){ var self = this; var options = { type: 'post', url: '/ajax/product/521370/recommendation', data: { categoryGroupId: 388, brandId: 41844, brandName: "더페이스샵" }, cache: false }; self.loadAjaxData(options, function(err, result){ if(err || !result.data || !result.data.recommendationDeals){ // alert('일시적인 오류 입니다.'); return false; } if(result.data.recommendationDeals) { var searchSegmentData = { s_keywords: getUrlParameter('q'), s_productId: '521370', s_category: '388', s_brand: '41844' }; result.data['searchSegmentData'] = searchSegmentData; Render.recommendation(result.data); } }); }, loadDelivery: function(){ var self = this; var options = { type: 'get', url: '/ajax/product/521370/delivery', cache: false }; self.loadAjaxData(options, function(err, result){ if(err || !result.data){ alert('일시적인 오류 입니다. 잠시 후 다시 시도해 주세요.'); return false; } if(result.data){ Render.delivery(result.data); } }); }, loadArticleInfo: function(){ var self = this; var options = { type: 'get', url: '/ajax/product/521370/articlesInfo', cache: false }; self.loadAjaxData(options, function(err, result){ if(err || !result.data){ alert('일시적인 오류 입니다. 잠시 후 다시 시도해 주세요.'); return false; } if(result.data){ Render.articleInfo(result.data); } }); }, addDependArticle: function(articles){ _logger('Deal.addDependArticle', articles); var self = this; if(typeof articles !== 'object'){ return false; } // let isImage = !!(articles.find(function(item){ return (item.contents && item.contents.length > 0 && item.contents[0].content); })); var isImage = null; for(var i=0; i 0 && item.contents[0].content){ isImage = item; break; } } self.dependArticles = []; // articles.map(function(article){ // if(article.contents && article.contents.length > 0 && article.contents[0].content){ // article['image'] = article.contents[0].content.uri; // } // article['isImage'] = isImage; // self.dependArticles.push(Article(article)); // }); for(var i=0; i 0 && article.contents[0].content){ article['image'] = article.contents[0].content.uri; } article['isImage'] = isImage; self.dependArticles.push(Article(article)); } /** * 1. 추가구성상품 article selectbox 생성 : .dependedArticles **/ Render.depended(self.dependArticles); }, addDependedCartItem: function(articleId){ var self = this; _logger('Deal.addDependedCartItem', articleId); // var findArticle = self.dependArticles.find(function(article){ // return article.id === articleId // }); var findArticle = null; for(var i=0; i .selectedArticles (일반상품) .selectedDependedArticles (추가구성상품) **/ Render.cartItem(cartItem); }else{ var plus = (self.buyLimit.max.article > duplicate.qty)? ++duplicate.qty : self.buyLimit.max.article; self.changeQtyCartItem(articleObject.id, plus); } self.calcCartItem(); }, changeQtyCartItem: function(articleId, qty){ var self = this; _logger('Deal.changeQtyCartItem', articleId, qty); // var cartItem = this.cartItems.find(function(item){ // return item.article.id === articleId; // }); var cartItem = null; for(var i=0; i< self.buyLimit.min.article)? self.buyLimit.min.article : qty; qty = (qty > self.buyLimit.max.article)? self.buyLimit.max.article : qty; cartItem.changeQty(qty); self.calcCartItem(); $('.item-qty__text[data-articleid='+ articleId +']').val(qty); $('.item-price__number[data-articleid='+ articleId +']').html(cartItem.totalPrice.toString().replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")); }, deleteCartItem: function(articleId){ var self = this; _logger('Deal.deleteCartItem', articleId); var counter = { normal: 0, depended: 0 }; // var newCart = this.cartItems.filter(function(item){ // if(item.article.id !== articleId && item.article.type === 'DEPENDED'){ // counter.depended++; // }else if(item.article.id !== articleId){ // counter.default++; // } // return item.article.id !== articleId; // }); var newCart = []; for(var i=0; i 0){ alert('추가구성상품만 구매하실 수 없습니다.'); return false; } if(counter.normal === 0){ $('.order-selected__block').hide(); } if(counter.depended === 0){ $('.order-selected__block-additional').hide(); } self.cartItems = newCart; self.calcCartItem(); $('.cartitem-'+articleId).remove(); return true; }, deleteAllCartItem: function(){ var self = this; if(self.readOnly === true){ return false; } for(var i=0; i<= 0){ alert('구매할 상품을 선택하세요.'); // return callback('empty item'); return false; } var cartObject = { carts: [] }; // self.cartItems.map(function(item){ // cartObject.carts.push({'itemId': item.article.id, 'itemCount': item.qty, 'price': item.totalPrice, 'itemTitle': item.article.name}); // }); for(var i=0; i<= 0){ alert('구매할 상품을 선택하세요.'); // return callback('empty item'); return false; } var cartObject = { carts: [] }; // self.cartItems.map(function(item){ // cartObject.carts.push({'itemId': item.article.id, 'itemCount': item.qty, 'price': item.totalPrice, 'itemTitle': item.article.name}); // }); for(var i=0; i<= deal.buyLimit.min.article){ qty = deal.buyLimit.min.article; } _logger('change qty', thisId, qty); deal.changeQtyCartItem(parseInt(thisId), qty); }); // 개별 옵션 수량 키보드 입력 $(document).on('focus', '.item-qty__text', function() { $(this).select(); }); $(document).on('keydown', '.item-qty__text', function() { var temp = $(this).val(); $(this).on('change keyup paste', function() { var regexp = /[^[0-9]/gi; if (regexp.test($(this).val())) { alert('숫자만 입력 가능합니다.'); $(this).val(temp); $(this).focus(); return false; } else { var qty = Number($(this).val()); if(qty <= 1){ qty = 1; $(this).val(qty); } var $this = $(this); var thisId = $this.data('articleid'); $.each($('.order-selected__item').find('input'), function(){ if($(this).data('articleid') === thisId){ $(this).val(qty); } }); deal.changeQtyCartItem(parseInt(thisId), qty); // renderCartPopup($(".itemShow"), cartItems); } }); }); // 선택한 아이템 삭제처리 $(document).on('click', '.item-delete', function () { var $this = $(this); if (deal.readOnly === true && $this.closest('.order-selected__list').data('type') !== 'depended') { return false; } deal.deleteCartItem(parseInt($this.data('articleid'))); }); // 즉시구매 버튼 $('.order-trigger-purchase').on('click', function () { var searchKeyword = getUrlParameter('q'); var st = getUrlParameter('st'); var sct = getUrlParameter('sct'); deal.submitPurchase(function(err, result){ if(err){ alert(err); return false; } var loginChk = ''; if (!loginChk && !!result.type && result.type == 'temp') { location.href='/login?returnUrl='+escape('/bridge/checkout'); return false; } if(!result.cid){ alert('일시적인 오류입니다. 고객센터에 문의해 주세요'); return false; } // 즉시 구매 try{ analytics.track('Button Clicked', { category: 'Product Page', label: 'Checkout Right Away Button', band_id: deal.setBandDetailId && deal.showBandDetail === true? deal.setBandDetailId : null, s_keywords: searchKeyword }); }catch(e){} location.href='https://order.memebox.com/order/'+result.cid+'?q='+encodeURI(searchKeyword) + '&st=' + st + '&sct=' + sct; }); }); // 장바구니 넣기 처리 $('.order-trigger-cart').on('click', function () { deal.submitCart(function(err, result){ if(err){ alert(err); return false; } // Segment Track Button Behaviour analytics.track('Button Clicked', { category: 'Product Page', label: 'Only Add To Cart Button' }); // GTM addToCart var products = []; for (var i = 0; i < deal.cartItems.length; i++) { products.push({ // Provide product details in a productFieldObject. 'id': deal.cartItems[i].article.id, // Product ID (string). 'name': deal.cartItems[i].article.name, // Product name (string). 'brand': '더페이스샵', 'category': '', // Product brand (string). 'variant': '', // Product variant (string). 'price': deal.cartItems[i].totalPrice, 'quantity': deal.cartItems[i].qty }); // Segment Analytics: Add To Cart try{ analytics.track('Cart Added', { id: '521370', // Product ID name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트', // Product Name item_id: deal.cartItems[i].article.id, // SKU is Variant ID item_name: deal.cartItems[i].article.name, // item_title band_id: deal.setBandDetailId && deal.showBandDetail === true? deal.setBandDetailId : null, quantity: deal.cartItems[i].qty // Variant Quantity }); }catch(e){} } try{ fbq('track', 'AddToCart', { content_type: 'product', content_ids: ['521370'], content_name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트', contents_category: (typeof fbqCategoryName !== 'undefined')? fbqCategoryName : '' }); }catch(e){} try{ dataLayer.push({ 'event': 'addToCart', 'ecommerce': { 'currencyCode': 'KRW', 'add': { 'products': products } } }); }catch(e){} // 오류 발생시 팝업 노출을 하지 않기 위해 위치 이동 wrapEntirePage(); renderCartPopup(); if ( $('.advanced-option-detail').css('display') === 'block' ) { $('.detail__option-block').appendTo('.detail__option-sidebar'); $("#contentsOptionDetail").html(''); /** * 선택중인 밴드정보 초기화 */ try{ deal.selectBand(null); deal.showBandDetail = false; }catch(e){} sidebarContentHeight(); $('.detail__option-sidebar').trigger('sticky_kit:recalc'); } $('.cartPopupWrap').show(); $('#shoppingBtn').on('click', function (e) { unwrapEntirePage(); // Segment Analytics: Button Behaviour analytics.track('Button Clicked', { category: 'Product Page', label: 'Popup > Continue Shopping' }); $('.cartPopupWrap').hide(); }); $('#cartClose').on('click', function (e) { unwrapEntirePage(); // Segment Analytics: Button Behaviour analytics.track('Button Clicked', { category: 'Product Page', label: 'Popup > Close Popup' }); $('.cartPopupWrap').hide(); }); $('#goCartBtn').click(function () { // Segment Analytics: Button Behaviour analytics.track('Button Clicked', { category: 'Product Page', label: 'Popup > Go To Cart' }); window.location.href = "https://order.memebox.com/cart"; }); }); }); function renderCartPopup(){ var popupTemplate = ""; var itemTitle = (deal.cartItems.length >= 1) ? deal.cartItems[0].article.name : ''; popupTemplate += ""; popupTemplate += "
"; } popupTemplate += " "; $(".itemShow").html(popupTemplate); } $('.timer').memeCountdown({ prefix: '', msg: '판매가 종료되었습니다!' }); // 찜하기 var TARGET_TYPE = { PRODUCT: 10001001 }; var checkFlags = false; $('.order-trigger-favorite').on('click', function() { var loginInfo = false; if(!loginInfo) { alert("로그인이 필요한 서비스 입니다."); location.href = '/login?returnUrl=/product/521370?list=%5B%EB%8D%94%ED%8E%98%EC%9D%B4%EC%8A%A4%EC%83%B5%5D+%EC%BB%A8%EC%8B%A4%EB%9F%AC+%EB%A6%AC%ED%80%B4%EB%93%9C+%EB%B2%A0%EC%9D%BC+Recommended+Products'; return false; } var wishId = $(this).attr('data-wishid') || 0; var $btn = $(this); var apiUrl = '/wish/create'; var params = { targetType: TARGET_TYPE.PRODUCT, targetId: '521370', id: $(this).attr('data-wishid') || 0 }; if(checkFlags) { return false; } else { if(parseInt(wishId, 10)) { if(!params.id) { alert('잠시후 다시 시도해주세요.'); return false; } apiUrl = '/wish/remove'; checkFlags = true; $.ajax({ type: 'post', url: apiUrl, data: params, dataType: 'json', cache: false }).done(function(body) { alert('찜하기가 해제되었습니다.'); wishId = 0; $btn.attr('data-wishid', 0); // Segment Analytics: Tracks when user adds product to wishlist analytics.track('Wishlist Removed', { id: params.targetId, name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트' }); return false; }).fail(function(error) { error = JSON.parse(error.responseText); alert(error.msg || '다시 시도해주세요.'); return false; }).always(function() { checkFlags = false; return false; }); } else { if(!params.targetId || !params.targetType) { alert('잠시후 다시 시도해주세요.'); return false; } checkFlags = true; $.ajax({ url: apiUrl, type: 'POST', data: params }).done(function(body) { wishId = body.data.id; $btn.attr('data-wishid', body.data.id); try{ fbq('track', 'AddToWishlist', { content_type: 'product', content_ids: ['521370'], content_name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트', contents_category: (typeof fbqCategoryName !== 'undefined')? fbqCategoryName : '' }); }catch(e){} // Segment Analytics: Tracks when user adds product to wishlist analytics.track('Wishlist Added', { id: '521370', name: '[더페이스샵] 1+1 피부 보습 지키기 프로젝트' }); return alert('찜한 상품에 저장 되었습니다.'); }).fail(function(error) { error = JSON.parse(error.responseText); _logger(error); alert(error.msg || '찜하기에 실패하였습니다.'); }).always(function() { checkFlags = false; return false; }); } } }); // 컨텐츠 고정바 function contentsFixedElement() { var $contentsNav = $('.dealTabNav'); var navOffset = $contentsNav.offset().top; var offsetBasis = navOffset + $('.dealContents').outerHeight(); var scroll = $(window).scrollTop(); if (scroll >= navOffset && scroll < offsetBasis - $contentsNav.height() - 6) { $('.dealContents').addClass('fixed'); } else { $('.dealContents').removeClass('fixed'); } } function sidebarContentHeight() { var $referenceElement = ($('.advanced-option-detail').find('.detail__option-block').length ? $('.advanced-option-detail') : $(window)); var $parentElement = $('.detail__option-block'); var $targetElement = $parentElement.find('.order-selected__content'); var headHeight = $parentElement.find('.detail__option-block-head').outerHeight() + $parentElement.find('.order-product').outerHeight(); var footHeight = $parentElement.find('.order-selected__bottom').outerHeight() + $parentElement.find('.order-selected__button').outerHeight(); if ( !($('.detail__option-sidebar').hasClass('is_stuck')) && !($('.advanced-option-detail').find('.detail__option-block').length)) { headHeight = headHeight + $('.memeTab').outerHeight(); } $targetElement.css('height', $referenceElement.outerHeight() - (headHeight + footHeight)); } $('.detail__option-sidebar').stick_in_parent({ offset_top: 45 }); // 쿠폰 혜택 var layerCheckFlag = false; var layerClickflags = false; $('.couponDown-layerOpenBtn').click(function() { if(!layerCheckFlag && !layerClickflags) { layerClickflags = true; analytics.track("Button Clicked", { name: $(this).text().trim() // Name }); var loginInfo = false; if(!loginInfo) { // 로그인 안했을 경우 현재 딜에 적용 가능한 쿠폰정보(ProductController에서 가져온 data)를 모두 보여줌 $('.couponDown-layer').show(); layerClickflags = false; layerCheckFlag = true; } else { // 로그인 했을 경우 유저가 이미 다운받은 쿠폰은 발급완료 처리해야 하므로 couponController로부터 data를 받아와서 비교한다 var couponObj = { productId: '521370' || 0, brandId: '41844' || 0, partnerId: '1533' || 0, categoryId: '388,373,179,392,436,179,792,779,728,789,779,728,382,372,179,338,332,177,395,375,179,381,372,179' || 0 }; $.ajax({ type: 'get', url: '/coupon/list', data: couponObj, cache: false }).done(function(body) { if(!!body.data) { var data = body.data; if(data.listCount > 0) { if(!!data.list) { data.list.forEach(function(userCoupon) { $('button[name="couponDownloadBtn"]').each(function(coupon) { if(parseInt(userCoupon, 10) === parseInt($(this).val(), 10)) { $(this).parent().parent().addClass('unusable-coupon'); $(this).append('발급
완료'); $(this).attr('disabled', true); } }); }); } } } $('.couponDown-layer').show(); layerClickflags = false; layerCheckFlag = true; }).fail(function(error) { layerCheckFlag = false; layerClickflags = false; console.error(error); alert('사용자 쿠폰 목록을 불러오는데 실패하였습니다.'); $('.couponDown-layer').hide(); return false; }); } } else { $('.couponDown-layer').hide(); layerCheckFlag = false; layerClickflags = false; } }); $('.couponDown-layer-closeBtn').click(function() { $('.couponDown-layer').hide(); layerCheckFlag = false; }); var couponDownBtnClicked = false; $(document).on('click', 'button[name="couponDownloadBtn"]', function(e) { if(!couponDownBtnClicked) { couponDownBtnClicked = true; var loginInfo = false; var $button = $(this); analytics.track("Button Clicked", { name: $(this).attr('data-name'), // Name : 쿠폰이름 value1: $(this).attr('data-value') // value1: 쿠폰할인 혹은 할인금액 }); // 로그인 체크 if(!loginInfo) { alert("로그인이 필요한 서비스 입니다."); location.href = '/login?returnUrl=/product/521370?list=%5B%EB%8D%94%ED%8E%98%EC%9D%B4%EC%8A%A4%EC%83%B5%5D+%EC%BB%A8%EC%8B%A4%EB%9F%AC+%EB%A6%AC%ED%80%B4%EB%93%9C+%EB%B2%A0%EC%9D%BC+Recommended+Products'; return false; } var couponObj = { couponNo: $(this).val() }; $.ajax({ type: 'get', url: '/coupon/download', data: couponObj, cache: false }).done(function (body) { couponDownBtnClicked = false; if(body.code === 200) { alert(body.message); $button.parent().parent().addClass('unusable-coupon'); $button.append('발급
마감'); $button.attr('disabled', true); } } }).fail(function (err) { console.error(err); couponDownBtnClicked = false; alert(err); return false; }); } }); $(window).on('resize', function() { sidebarContentHeight(); }); $(window).on('scroll', function() { contentsFixedElement(); }); // 딜 이미지 if ($('.descImageThumb').length > 0) { $('.descImageThumb .item').on('click', function() { var $this = $(this); var $target = $($(this).attr('href')); $('.descImageBig .imageCnt').removeClass('on'); $('.descImageThumb .item').removeClass('on'); $target.addClass('on'); $this.addClass('on'); return false; }); } function scrollToDealDetail() { $('html, body').stop().animate({ scrollTop: $('.dealContents').offset().top }, 300); return false; } // 상단 리뷰 숫자 클릭 $('.descToReview').on('click', function() { $('.memeTab .tabItem[href="#review"]').trigger('click'); scrollToDealDetail(); }); function wrapEntirePage() { // $('html').css({width:'100%'}); $('body').css('position', 'relative'); $('body').css('overflow-y', 'hidden'); $('body').css('overflow-x', 'hidden'); $('.cover').css('display','block'); } function unwrapEntirePage() { // $('html').css({width:'100%', position:''}); $('body').css('position', ''); $('body').css('overflow-y', ''); $('body').css('overflow-x', ''); $('.cover').css('display','none'); } // 찜했는지 체크 function checkWished(){ var loginChk = ''; if(!loginChk){ return false; } var options = { type: 'get', url: '/wish/findOne?dealId=521370', data: {}, cache: false }; deal.loadAjaxData(options, function(err, result){ if(err || !result.data){ alert('일시적인 오류 입니다.'); return false; } if(result.data.wishId){ $('.order-trigger-favorite').attr('data-wishid', result.data.wishId); } }); } // Called when a link to a product is clicked. function onRecommendProductClick(product_id, product_name, product_list_id, product_list, categoryGroupId, brandId, recommendType, product_position, position) { // Segment Analytics: User Clicked on Product analytics.track('Product Clicked', { id: product_id, // Product ID name: product_name, // Product Name list_id: product_list_id, list_name: product_list, position: product_position, // Search 영역 s_logType: 'clk', s_keywords: getUrlParameter('q'), // search keyword s_productId: '521370', // Current Product id s_category: '388', // Current Product category s_clickType: recommendType, s_clickAction: 'CLK', s_dealId: product_id, // clicked product Id s_brandId: brandId, // Brand Id of Current Product s_categoryGroupId:categoryGroupId, s_framePosition: position }, function () { // callback 작동안함 }); setTimeout(function(){ if (product_list == '함께 구매시 배송비 절약 상품') { document.location = '/product/'+product_id+'?listId='+ product_list_id + '&listName=' + product_list; // Callback: Redirect to Product Page } else { document.location = '/product/'+product_id+'?listId='+ product_list_id + '&listName=' + product_list + '&st=recommend&sct=' + recommendType; // Callback: Redirect to Product Page } }, 100); } // 브랜드관 클릭 $('#brandShopLink').click(function() { analytics.track("Button Clicked", { name: $(this).attr('data-name') // Name : {브랜드이름}_브랜드관 }); }); $(function() { checkWished(); // 상품설명 링크 자동변경 try { var arrLink = $('#dealDetail').find('a'); $.each(arrLink, function() { if($(this).attr('href').indexOf('memebox://uri/parse?url=http://m.') >=0 ) { this.href = $(this).attr('href').replace('memebox://uri/parse?url=http://m.', 'http://www.'); } if($(this).attr('href').indexOf('memebox://uri/parse?url=http://www.') >=0 ) { this.href = $(this).attr('href').replace('memebox://uri/parse?url=http://www.', 'http://www.'); } }); } catch(e) { } });