Skip to content

Instantly share code, notes, and snippets.

@dbwhddn10
Last active August 25, 2021 05:06
Show Gist options
  • Save dbwhddn10/06a9bd9cecaf24493ef9 to your computer and use it in GitHub Desktop.
Save dbwhddn10/06a9bd9cecaf24493ef9 to your computer and use it in GitHub Desktop.
cafe24 자바스크립트
/**
* i18n - Javascript Internationalization System
*
* @author Platform Team
*/
(function() {
var $i18n = {
/**
* Messages
* @var array
* {
* 'DOMAIN NAME' : {
* 'KEY NAME' : 'value',
* 'KEY NAME(Plurals) : ['value', 'value', ...]
* ...
* },
* ...
* }
*/
_lang : {},
/**
* Plurals Expressions
* @var array
* {
* 'DOMAIN NAME' : function(n) {
* expressions
* },
* ...
* }
*/
_pluralsExp : {},
/**
* Current Domain
* @var string
*/
_currDomain : false,
/**
* override the current domain for a single message lookup
*
* @param string domain
* @param string key
* @return string
*/
__d : function(domain, key, __idx__) {
var t = $i18n._lang;
if ($i18n._isEmpty(t) === true) {
return key;
}
if (typeof t[domain] == 'undefined') {
return key;
}
if (typeof t[domain][key] == 'undefined') {
return key;
}
if (typeof t[domain][key] == 'object') {
__idx__ = __idx__ ? __idx__ : 0;
return t[domain][key][__idx__];
}
return t[domain][key];
},
/**
* Plural version of __d
*
* @param string domain
* @param string key1
* @param string key2
* @param int cnt
* @return string
*/
__dn : function(domain, key1, key2, cnt) {
var n = parseInt(cnt);
var idx = $i18n._getPluralsIndex(domain, n);
if (idx == 0) {
return $i18n.__d(domain, key1, 0);
} else {
return $i18n.__d(domain, key2, idx);
}
},
_init : function() {
$i18n._pluralsExp.__reserved_default_exp__ = function(n) {
return n == 1 ? 0 : 1;
};
window['__d'] = function(domain, key) {
return $i18n.__d(domain, key, 0);
};
window['__dn'] = function(domain, key1, key2, cnt) {
return $i18n.__dn(domain, key1, key2, cnt);
};
window['__'] = function(key) {
return $i18n.__d($i18n._currDomain, key, 0);
};
window['__n'] = function(key1, key2, cnt) {
return $i18n.__dn($i18n._currDomain, key1, key2, cnt);
};
window['__i18n_regist__'] = this._regist;
window['__i18n_bind__'] = this._bind;
window['__i18n_plurals_exp_bind__'] = this._pluralsExpBind;
},
_isEmpty : function(val) {
if (!val) return true;
if (val == null) return true;
if (val == undefined) return true;
if (val == '') return true;
if (typeof val == 'object') {
for (var i in val) {
return false;
}
return true;
}
return false;
},
_trim : function(str) {
if(typeof str != 'string') return '';
return str.replace(/(^\s*)|(\s*$)/g, '');
},
_apply : function(method, func) {
this[method] = func;
},
_regist : function(lang) {
if (typeof lang != 'object') return false;
$i18n._lang = lang;
return true;
},
_bind : function(domain) {
if ($i18n._isEmpty(domain) === true) return false;
$i18n._currDomain = domain;
return true;
},
_pluralsExpBind : function(domain, exp) {
if (typeof exp != 'function') {
return;
}
$i18n._pluralsExp[domain] = exp;
},
_getPluralsIndex : function(domain, n) {
if (typeof $i18n._pluralsExp[domain] == 'undefined') {
return $i18n._pluralsExp.__reserved_default_exp__(n);
}
return $i18n._pluralsExp[domain](n);
}
};
$i18n._init();
})();
/*!
* jQuery JavaScript Library v1.4.4
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Thu Nov 11 19:04:53 2010 -0500
*/
(function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h=
h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"||
h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La,
"`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,
e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,
"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+
a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,
C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j,
s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,
j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length},
toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j===
-1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false;
if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--;
if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload",
b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&&
!F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&&
l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z],
z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j,
s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v=
s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)||
[];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u,
false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"),
k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false,
scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent=
false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom=
1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display=
"none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h=
c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);
else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=
c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,
a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",
colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===
1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "),
l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,
"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";
if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r=
a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},
attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&
b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0};
c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,
arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid=
d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+
c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b=
w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===
8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k===
"click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+
d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this,
Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=
c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U};
var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V,
xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired=
B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type===
"file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]===
0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d,
a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d=
1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d===
"object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}});
c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i,
[y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3];
break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr,
q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h=
l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*"));
return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!==
B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()===
i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=
i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g,
"")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n,
m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===
true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===
g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]-
0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n===
"first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===
i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]];
if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m,
g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1;
for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"),
i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g);
n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&&
function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F||
p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g=
t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition?
function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML;
c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},
not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h=
h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):
c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,
2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,
b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&
e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1,
"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null;
else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=
c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a,
b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):
this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",
prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument||
b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length-
1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));
d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i,
jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,
zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),
h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b);
if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=
d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left;
e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b===
"object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&
!this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})},
getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html",
script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data||
!T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache=
false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset;
A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type",
b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&&
c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d||
c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]=
encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",
[b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),
e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});
if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",
3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",
d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,
d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)===
"inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L||
1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b,
d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a*
Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)}
var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;
this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide||
this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=
c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===
b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&&
h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle;
for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+=
parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",
height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells=
f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a,
"marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a,
e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&&
c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();
c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+
b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
// SUB-4602 상품모드(구상품 or 뉴상품)에 따라 프론트 링커 기능에서 참조할 변수 정의
var sProductMode = 'N'; // 뉴상품
/*
* php의 sprintf와 사용방법은 비슷하나 문자열 포멧의 type specifier는 %s만 사용
* 참조 : http://wiki.simplexi.com/pages/viewpage.action?pageId=125338699
*/
function sprintf()
{
var pattern = /%([0-9]+)\$s/g;
var text = arguments[0];
var extract = text.match(pattern, text);
if (extract == null || extract.length < 0) {
var split = text.split('%s');
var count = split.length;
var tmp = new Array();
for (var i = 0; i < count; i++) {
if (typeof arguments[i + 1] != 'undefined') {
tmp.push(split[i] + arguments[i + 1]);
} else {
tmp.push(split[i]);
}
}
return tmp.join('');
} else {
var count = extract.length;
for (var i = 0; i < count; i++) {
var index = extract[i].replace(pattern, '$1');
if (typeof arguments[index] != 'undefined') {
text = text.replace('%' + index + '$s', arguments[index]);
}
}
return text;
}
}
$(document).ready(function(){
$('#btn_search').click(function() {
$('#searchBarForm').submit();
});
$('input[name="keyword"]').keypress(function(e) {
if (e.keyCode == 13 && $.trim($(this).val()) === '') {
alert(__('검색어를 입력해주세요'));
return false;
}
});
$('#searchBarForm').submit(function(e) {
if ($.trim($(this).find('#keyword').val())=='') {
alert(__('검색어를 입력해주세요'));
return;
}
if (mobileWeb === true) {
$Recentword.saveRecentWord($(this).find('#keyword').val());
}
});
$('.btn_order').click(function() {
$type = $(this).attr('rel');
$('#order_by').val($type);
$('#searchForm').submit();
});
$('.btn_view').click(function() {
$view = $(this).attr('rel');
if ($view != 'list') {
$sAction = '/product/search_'+$view+'.html';
} else {
$sAction = '/product/search.html';
}
$('#view_type').val($view);
$('#searchForm').attr('action', $sAction);
$('#searchForm').submit();
});
// 검색어 관련 작업
var aSearchKey = ReWriteSearchKey();
if (aSearchKey !== false) {
if (aSearchKey){//ECHOSTING-44000
var oSearchHeader = $(".xans-layout-searchheader").parent("form");
oSearchHeader.find("#banner_action").val(aSearchKey.banner_action);
oSearchHeader.find("#keyword").val(aSearchKey.msb_contents);
}
};
if (mobileWeb === true) {
$('#search_cancel').bind('click', function(){
$('html, body').css({'overflowY': 'auto', height: 'auto', width: '100%'});
$('.dimmed').toggle();
$('.xans-layout-searchheader').hide();
});
$('.xans-layout-searchheader').find('button.btnDelete').bind('click', function(){
$('#keyword').attr('value', '').focus();
$('#banner_action').attr('value', ''); //ECQAINT-8961 Delete버튼 클릭시 value 초기화
});
// 검색페이지에서 삭제
$('.xans-search-form').find('button.btnDelete').bind('click', function(){
$('#searchForm').find('input#keyword').attr('value', '').focus();
});
$('.header .search button').bind('click', function() {
if ($('#search_box').size() > 0) {
$('html, body').css({'overflowY': 'hidden', height: '100%', width: '100%'});
$('.dimmed').toggle();
$('#header .xans-layout-searchheader').toggle();
} else {
$('#header .xans-layout-searchheader').toggle();
}
});
}
});
function ReWriteSearchKey()
{
if (typeof(sSearchBannerUseFlag) == "undefined") return false;
if (sSearchBannerUseFlag == 'F') return false;
if (typeof(aSearchBannerData) == "undefined") return false;
if (aSearchBannerData.length === 0) return false;
if (sSearchBannerType != 'F') return aSearchBannerData[Math.floor(Math.random() * aSearchBannerData.length)];
var aResultData = null;
var sSearchKey = $.cookie('iSearchKey');
var iSearchKey = 0;
// if ( sSearchKey !== null ) {//ECHOSTING-44000
if ( sSearchKey != undefined ) {
iSearchKey = parseInt(sSearchKey) + parseInt(1);
if ( iSearchKey >= aSearchBannerData.length ) {
iSearchKey = 0;
}
}
$.cookie('iSearchKey', iSearchKey, {path : '/'});
return aSearchBannerData[iSearchKey];
}
var popProduct = {
selProduct: function(product_no,iPrdImg, sPrdName,sPrdPrice, sCategoryName, iCategoryNo)
{
if (this.isGiftProduct(product_no) === false) {
alert(sErrorMessage);
return false;
}
try {
opener.document.getElementById('aPrdLink').href = this.getUrl(product_no);
opener.document.getElementById('aPrdNameLink').href = this.getUrl(product_no);
opener.document.getElementById('product_no').value = product_no;
opener.document.getElementById('iPrdImg').src = iPrdImg;
opener.document.getElementById('sPrdName').innerHTML = sPrdName.replace(/[\"]/g, '"');
opener.document.getElementById('sPrdPrice').innerHTML = sPrdPrice;
opener.document.getElementById('sPrdCommonImg').innerHTML = '';
opener.$('#iPrdView').removeClass('displaynone').css('display', 'inline');
} catch (e) {}
// ECHOSTING-61590
var iSelectedOptionIndex = $('#subject', opener.document).attr('selectedIndex');
$('#subject option', opener.document).remove();
$('input[name^="fix_title_form_"]', opener.document).each(function (iIndex) {
var sSubject = popProduct.getConvertString($(this).val(), sPrdName, sCategoryName);
var sOptionTag = '<option value="'+sSubject+'">'+sSubject+'</option>';
$('#subject', opener.document).append(sOptionTag);
});
$('#subject', opener.document).attr('selectedIndex', iSelectedOptionIndex);
$('#cate_no', opener.document).val(iCategoryNo);
/**
* thunmail이미지에 링크가 걸렸을경우 링크 처리
*/
var eAnchor = opener.document.getElementById('iPrdImg').parentNode;
if ('A' === eAnchor.tagName.toUpperCase()) {
eAnchor.href = this.getUrl(product_no);
}
window.close();
},
getUrl: function(product_no)
{
var aPrdLink = opener.document.getElementById('aPrdLink').href;
var iUrlIndex = aPrdLink.indexOf('product_no=');
var aPrdLinkSplit = aPrdLink.split('product_no=');
var aPrdParamSplit = aPrdLinkSplit[1].split('&');
aPrdParamSplit.shift();
return aPrdLink.substr(0, iUrlIndex)+'product_no='+product_no+(aPrdParamSplit.length > 0 ? '&'+aPrdParamSplit.join('&') : '');
},
// ECHOSTING-61590
getConvertString : function(sSubject, sPrdName, sCategoryName)
{
sSubject = sSubject.replace('PRODUCT_NAME', sPrdName);
return sSubject.replace('CATEGORY_NAME', sCategoryName);
},
isGiftProduct : function(iProductNum)
{
if (typeof aGiftReview === 'object') {
if (aGiftReview[iProductNum] === 'F') {
return false;
}
}
return true;
},
END : function() {}
};
/**
* 상품 검색 배너
*/
var SEARCH_BANNER = {
/**
* 상품 검색 Submit
*/
submitSearchBanner : function(obj)
{
var form = $(obj).parents('form');
if (form.find('#banner_action').val() != '') {
// ECHOSTING-98878 상품검색키워드로 검색시에 폼전송이 되어 연결페이지로 이동이 안되고 검색페이지로 이동되는 오류 수정
form.submit(function () {
return false;
});
// 배너 연결 페이지 이동
location.replace(form.find('#banner_action').val());
} else {
if ($.trim(form.find('#keyword').val())=='') {
alert(__('검색어를 입력해주세요'));
form.find('#keyword').focus();
return;
}
form.submit();
}
},
/**
* 검색어 입력폼 클릭
*/
clickSearchForm : function(obj)
{
//ECHOSTING-105207 상품검색 키워드설정시 모바일에서 검색 결과 없음
var form = $(obj).parents('form');
if (mobileWeb == true && form.find('#banner_action').val() != '') {
// ECHOSTING-98878 상품검색키워드로 검색시에 폼전송이 되어 연결페이지로 이동이 안되고 검색페이지로 이동되는 오류 수정
form.submit(function () {
return false;
});
// 배너 연결 페이지 이동
location.replace(form.find('#banner_action').val());
}
form.find('#banner_action').val('');
if (mobileWeb !== true) { $(obj).val(''); }
}
};
/**
* 최근검색어
*/
var $Recentword = {
// recent length
recentNum : 10,
// cookie expires
expires : 10,
// duplication key
duplicateKey : 0,
// recent string
string : '',
// recent string
prefix : 'RECENT_WORD_',
// sModuel
sModule : 'xans-search-recentkeyword',
// recent
$recent : null,
// recent list
$recentList : null,
// list size
size : 0,
// remove
$remove : null,
/**
* save recent word
*/
init : function()
{
this.setObj();
this.action();
this.dimmed();
},
dimmed : function()
{
try {
$('.xans-layout-searchheader').after('<div class="dimmed"></div>');
} catch(e) { }
},
setObj : function()
{
this.$recent = $('.' + this.sModule);
this.$recentList = this.$recent.find('ul').find('li');
this.size = this.$recentList.size();
this.$remove = this.$recent.find('p');
},
action : function()
{
var $hot = $('.xans-search-hotkeyword'), $title = $('#keyword_title');
if ($('.xans-layout-searchheader').find('ul.searchTab').hasClass('displaynone') === false) {
this.$recent.hide();
$title.hide();
} else {
$hot.hide();
}
$('.xans-layout-searchheader').find('ul.searchTab').find('li').click(function(){
var index = $(this).index();
$(this).addClass('selected').siblings().removeClass('selected');
if (index == 0) { $Recentword.$recent.hide(); $hot.show(); }
else { $Recentword.$recent.show(); $hot.hide(); }
});
},
saveRecentWord : function(s)
{
this.string = s;
// 중복처리
if (this.duplication() === false) { this.cookieOrder(); }
// 저장
this.save();
},
save : function()
{
var bFull = true;
for (var i=1; i<=this.recentNum; i++) {
if ($.cookie(this.prefix + i) == null) {
bFull = false;
this.add(i);
break;
}
}
if (bFull == true) {
this.removeFrist();
this.add(this.recentNum);
}
},
duplication : function()
{
for (var k=1; k<=this.recentNum; k++) {
if ($.cookie(this.prefix + k) == this.string) {
this.duplicateKey = k;
$.cookie(this.prefix + k, null, { path: '/' });
return false;
}
}
},
cookieOrder : function()
{
var s = this.duplicateKey + 1;
for (var i=this.duplicateKey; i<=this.recentNum; i++) {
if ($.cookie(this.prefix + s) != null) {
this.add(i, $.cookie(this.prefix + s));
this.removeCookie(s);
s++;
}
}
},
removeFrist : function()
{
for (var i=2, k=1; i<=this.recentNum; i++,k++) {
$.cookie(this.prefix + k, $.cookie(this.prefix + i), { expires: this.expires, path: '/'});
}
},
add : function(key, duplicateString)
{
$.cookie(this.prefix + key, duplicateString || this.string, { expires: this.expires, path: '/'});
},
removeCookie : function(key)
{
$.cookie(this.prefix + key, null, { path: '/' });
},
removeAll : function()
{
for (var i=1; i<=this.recentNum; i++) { $.cookie(this.prefix + i, null, { path: '/' }); }
this.setNoList();
},
removeOne : function(key)
{
try {
this.removeCookie(key);
this.$recentList.each(function(){ if ($(this).data('index') == key) { $(this).remove(); } });
this.size--;
if (this.size == 0) { this.setNoList(); }
} catch(e) {
}
},
setNoList : function()
{
try {
this.$recentList.each(function(){ $(this).remove(); });
this.$remove.removeClass('displaynone');
} catch(e) {
}
}
};
/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
* Licensed under the MIT License (LICENSE.txt).
*
* Version 3.0.0
*/
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
$.fn.bgiframe = function(s) {
s = $.extend({
top : 'auto', // auto == borderTopWidth
left : 'auto', // auto == borderLeftWidth
width : 'auto', // auto == offsetWidth
height : 'auto', // auto == offsetHeight
opacity : true,
src : 'javascript:false;',
conditional : /MSIE 6.0/.test(navigator.userAgent) // expresion or function. return false to prevent iframe insertion
}, s);
// wrap conditional in a function if it isn't already
if (!$.isFunction(s.conditional)) {
var condition = s.conditional;
s.conditional = function() { return condition; };
}
var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
'style="display:block;position:absolute;z-index:-1;"/>');
return this.each(function() {
var $this = $(this);
if ( s.conditional(this) === false ) { return; }
var existing = $this.children('iframe.bgiframe');
var $el = existing.length === 0 ? $iframe.clone() : existing;
$el.css({
'top': s.top == 'auto' ?
((parseInt($this.css('borderTopWidth'),10)||0)*-1)+'px' : prop(s.top),
'left': s.left == 'auto' ?
((parseInt($this.css('borderLeftWidth'),10)||0)*-1)+'px' : prop(s.left),
'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width),
'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height),
'opacity': s.opacity === true ? 0 : undefined
});
if ( existing.length === 0 ) {
$this.prepend($el);
}
});
};
// old alias
$.fn.bgIframe = $.fn.bgiframe;
function prop(n) {
return n && n.constructor === Number ? n + 'px' : n;
}
}));
/**
* Cookie plugin
*
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
/**
* Create a cookie with the given name and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String name The name of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given name.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String name The name of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
}
// NOTE Needed to parenthesize options.path and options.domain
// in the following expressions, otherwise they evaluate to undefined
// in the packed version for some reason...
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else { // only name given, get cookie
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
* $Rev: 4259 $
*
* Version: 1.2
*
* Requires: jQuery 1.2+
*/
(function($){
$.dimensions = {
version: '1.2'
};
// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){
// innerHeight and innerWidth
$.fn[ 'inner' + name ] = function() {
if (!this[0]) return;
var torl = name == 'Height' ? 'Top' : 'Left', // top or left
borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
};
// outerHeight and outerWidth
$.fn[ 'outer' + name ] = function(options) {
if (!this[0]) return;
var torl = name == 'Height' ? 'Top' : 'Left', // top or left
borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
options = $.extend({ margin: false }, options || {});
var val = this.is(':visible') ?
this[0]['offset' + name] :
num( this, name.toLowerCase() )
+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
+ num(this, 'padding' + torl) + num(this, 'padding' + borr);
return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
};
});
// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
$.fn[ 'scroll' + name ] = function(val) {
if (!this[0]) return;
return val != undefined ?
// Set the scroll offset
this.each(function() {
this == window || this == document ?
window.scrollTo(
name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
name == 'Top' ? val : $(window)[ 'scrollTop' ]()
) :
this[ 'scroll' + name ] = val;
}) :
// Return the scroll offset
this[0] == window || this[0] == document ?
self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
$.boxModel && document.documentElement[ 'scroll' + name ] ||
document.body[ 'scroll' + name ] :
this[0][ 'scroll' + name ];
};
});
$.fn.extend({
position: function() {
var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
if (elem) {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
parentOffset = offsetParent.offset();
// Subtract element margins
offset.top -= num(elem, 'marginTop');
offset.left -= num(elem, 'marginLeft');
// Add offsetParent borders
parentOffset.top += num(offsetParent, 'borderTopWidth');
parentOffset.left += num(offsetParent, 'borderLeftWidth');
// Subtract the two offsets
results = {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
}
return results;
},
offsetParent: function() {
var offsetParent = this[0].offsetParent;
while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
offsetParent = offsetParent.offsetParent;
return $(offsetParent);
}
});
function num(el, prop) {
return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};
})(jQuery);
/*
* jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php
*
* Uses the built in easing capabilities added in jQuery 1.1
* to offer multiple easing options
*
* Copyright (c) 2007 George Smith
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
jQuery.extend(jQuery.easing, {
easein: function(x, t, b, c, d) {
return c*(t/=d)*t + b; // in
},
easeinout: function(x, t, b, c, d) {
if (t < d/2) return 2*c*t*t/(d*d) + b;
var ts = t - d/2;
return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;
},
easeout: function(x, t, b, c, d) {
return -c*t*t/(d*d) + 2*c*t/d + b;
},
expoin: function(x, t, b, c, d) {
var flip = 1;
if (c < 0) {
flip *= -1;
c *= -1;
}
return flip * (Math.exp(Math.log(c)/d * t)) + b;
},
expoout: function(x, t, b, c, d) {
var flip = 1;
if (c < 0) {
flip *= -1;
c *= -1;
}
return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b;
},
expoinout: function(x, t, b, c, d) {
var flip = 1;
if (c < 0) {
flip *= -1;
c *= -1;
}
if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b;
return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b;
},
bouncein: function(x, t, b, c, d) {
return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b;
},
bounceout: function(x, t, b, c, d) {
if ((t/=d) < (1/2.75)) {
return c*(7.5625*t*t) + b;
} else if (t < (2/2.75)) {
return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
} else if (t < (2.5/2.75)) {
return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
} else {
return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
}
},
bounceinout: function(x, t, b, c, d) {
if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
},
elasin: function(x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
},
elasout: function(x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3;
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
},
elasinout: function(x, t, b, c, d) {
var s=1.70158;var p=0;var a=c;
if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5);
if (a < Math.abs(c)) { a=c; var s=p/4; }
else var s = p/(2*Math.PI) * Math.asin (c/a);
if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
},
backin: function(x, t, b, c, d) {
var s=1.70158;
return c*(t/=d)*t*((s+1)*t - s) + b;
},
backout: function(x, t, b, c, d) {
var s=1.70158;
return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
},
backinout: function(x, t, b, c, d) {
var s=1.70158;
if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
}
});
/*
* Metadata - jQuery plugin for parsing metadata from elements
*
* Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id$
*
*/
/**
* Sets the type of metadata to use. Metadata is encoded in JSON, and each property
* in the JSON will become a property of the element itself.
*
* There are three supported types of metadata storage:
*
* attr: Inside an attribute. The name parameter indicates *which* attribute.
*
* class: Inside the class attribute, wrapped in curly braces: { }
*
* elem: Inside a child element (e.g. a script tag). The
* name parameter indicates *which* element.
*
* The metadata for an element is loaded the first time the element is accessed via jQuery.
*
* As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
* matched by expr, then redefine the metadata type and run another $(expr) for other elements.
*
* @name $.metadata.setType
*
* @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("class")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from the class attribute
*
* @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
* @before $.metadata.setType("attr", "data")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a "data" attribute
*
* @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
* @before $.metadata.setType("elem", "script")
* @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
* @desc Reads metadata from a nested script element
*
* @param String type The encoding type
* @param String name The name of the attribute to be used to get metadata (optional)
* @cat Plugins/Metadata
* @descr Sets the type of encoding to be used when loading metadata for the first time
* @type undefined
* @see metadata()
*/
(function($) {
$.extend({
metadata : {
defaults : {
type: 'class',
name: 'metadata',
cre: /({.*})/,
single: 'metadata'
},
setType: function( type, name ){
this.defaults.type = type;
this.defaults.name = name;
},
get: function( elem, opts ){
var settings = $.extend({},this.defaults,opts);
// check for empty string in single property
if ( !settings.single.length ) settings.single = 'metadata';
var data = $.data(elem, settings.single);
// returned cached data if it already exists
if ( data ) return data;
data = "{}";
if ( settings.type == "class" ) {
var m = settings.cre.exec( elem.className );
if ( m )
data = m[1];
} else if ( settings.type == "elem" ) {
if( !elem.getElementsByTagName )
return undefined;
var e = elem.getElementsByTagName(settings.name);
if ( e.length )
data = $.trim(e[0].innerHTML);
} else if ( elem.getAttribute != undefined ) {
var attr = elem.getAttribute( settings.name );
if ( attr )
data = attr;
}
if ( data.indexOf( '{' ) <0 )
data = "{" + data + "}";
data = eval("(" + data + ")");
$.data( elem, settings.single, data );
return data;
}
}
});
/**
* Returns the metadata object for the first member of the jQuery object.
*
* @name metadata
* @descr Returns element's metadata object
* @param Object opts An object contianing settings to override the defaults
* @type jQuery
* @cat Plugins/Metadata
*/
$.fn.metadata = function( opts ){
return $.metadata.get( this[0], opts );
};
})(jQuery);
/**
* FwValidator
*
* @package jquery
* @subpackage validator
*/
var FwValidator = {
/**
* 디버그 모드
*/
DEBUG_MODE : false,
/**
* 결과 코드
*/
CODE_SUCCESS : true,
CODE_FAIL : false,
/**
* 어트리뷰트 명
*/
ATTR_FILTER : 'fw-filter',
ATTR_MSG : 'fw-msg',
ATTR_LABEL : 'fw-label',
ATTR_FIREON : 'fw-fireon',
ATTR_ALONE : 'fw-alone',
/**
* 응답객체들
*/
responses : {},
/**
* 엘리먼트별 필수 입력 에러 메세지
*/
requireMsgs : {},
/**
* 엘리먼트의 특정 필터별 에러 메세지
*/
elmFilterMsgs : {},
/**
* Validator 기본 이벤트 등록
*/
bind : function(formId, expand) {
var self = this;
var formInfo = this.Helper.getFormInfo(formId);
if (formInfo === false) {
alert('The form does not exist - bind');
return false;
}
var elmForm = formInfo.instance;
var Response = this._response(formId);
this._fireon(formId, elmForm, Response);
this._submit(formId, elmForm, expand);
return true;
},
/**
* Validator 검사 진행
*
* @param string formId
* @return object | false
*/
inspection : function(formId, expand) {
expand = (expand === true) ? true : false;
var self = this;
var Response = this._response(formId);
if (Response === false) {
alert('The form does not exist - inspection');
return false;
}
if (Response.elmsTarget.length == 0) {
return this.Helper.getResult(Response, this.CODE_SUCCESS);
}
Response.elmsTarget.each(function(){
self._execute(Response, this);
});
if (Response.elmsCurrErrorField.length > 0) {
if (expand !== true) {
this.Handler.errorHandler(Response.elmsCurrErrorField[0]);
} else {
this.Handler.errorHandlerByExapnd(Response);
}
return Response.elmsCurrErrorField[0];
}
return this.Helper.getResult(Response, this.CODE_SUCCESS);
},
/**
* submit 이벤트 등록
*
* @param string formId
* @param object elmForm
*/
_submit : function(formId, elmForm, expand) {
var self = this;
elmForm.unbind('submit');
elmForm.bind('submit', function(){
var result = false;
try{
result = self.inspection(formId, expand);
}catch(e){
alert(e);
return false;
}
if(!result || result.passed === self.CODE_FAIL){
return false;
};
var callback = self._beforeSubmit(elmForm);
return callback !== false ? true : false;
});
},
/**
* fireon 이벤트 등록
*
* @param string formId
* @param object elmForm
* @param FwValidator.Response Response
*/
_fireon : function(formId, elmForm, Response) {
var self = this;
var formInfo = this.Helper.getFormInfo(formId);
$(formInfo.selector).find('*['+this.ATTR_FILTER+']['+this.ATTR_FIREON+']').each(function(){
var elm = $(this);
var evtName = $.trim(elm.attr(self.ATTR_FIREON));
var elmMsg = '';
elm.unbind(evtName);
elm.bind(evtName, function(){
var result = self._execute(Response, this);
var targetField = Response.elmCurrField;
//에러 메세지가 출력되 있다면 일단 지우고 체킹을 시작한다.
if(typeof elmMsg == 'object'){
elmMsg.remove();
}
if(result > -1){
elmMsg = self.Handler.errorHandlerByFireon(Response.elmsCurrErrorField[result]);
}else{
self.Handler.successHandlerByFireon(self.Helper.getResult(Response, self.CODE_FAIL));
}
});
});
},
/**
* Response 객체 생성
*
* @param string formId
* @return FwValidator.Response | false
*/
_response : function(formId) {
var formInfo = this.Helper.getFormInfo(formId);
if (formInfo === false) {
alert('The form does not exist - find');
return false;
}
var elmForm = formInfo.instance;
var elmsTarget = $(formInfo.selector).find('*[' + this.ATTR_FILTER + ']');
this.responses[formId] = new FwValidator.Response();
this.responses[formId].formId = formId;
this.responses[formId].elmForm = elmForm;
this.responses[formId].elmsTarget = elmsTarget;
return this.responses[formId];
},
/**
* BeforeExecute 콜백함수 실행
*
* @param FwValidator.Response Response
*/
_beforeExecute : function(Response) {
var count = this.Handler.beforeExecute.length;
if (count == 0) return;
for (var i in this.Handler.beforeExecute) {
this.Handler.beforeExecute[i].call(this, Response);
}
},
/**
* BeforeSubmit 콜백함수 실행
*
* @param object elmForm (jquery 셀렉터 문법으로 찾아낸 폼 객체)
*/
_beforeSubmit : function(elmForm) {
if(typeof this.Handler.beforeSubmit != 'function') return true;
return this.Handler.beforeSubmit.call(this, elmForm);
},
/**
* 엘리먼트별 유효성 검사 실행
*
* @param FwValidator.Response Response
* @param htmlElement elmTarget
* @return int(에러가 발생한 elmCurrField 의 인덱스값) | -1(성공)
*/
_execute : function(Response, elmTarget) {
var RESULT_SUCCESS = -1;
Response.elmCurrField = $(elmTarget);
Response.elmCurrLabel = Response.elmCurrField.attr(this.ATTR_LABEL);
Response.elmCurrFieldType = this.Helper.getElmType(Response.elmCurrField);
Response.elmCurrFieldDisabled = elmTarget.disabled;
Response.elmCurrValue = this.Helper.getValue(Response.formId, Response.elmCurrField);
Response.elmCurrErrorMsg = Response.elmCurrField.attr(this.ATTR_MSG);
//_beforeExecute 콜백함수 실행
this._beforeExecute(Response);
//필드가 disabled 일 경우는 체크하지 않음.
if (Response.elmCurrFieldDisabled === true) {
return RESULT_SUCCESS;
}
var filter = $.trim( Response.elmCurrField.attr(this.ATTR_FILTER) );
if (filter == '') {
return RESULT_SUCCESS;
}
//is로 시작하지 않는것들은 정규표현식으로 간주
if (/^is/i.test(filter)) {
var filters = filter.split('&');
var count = filters.length;
//필수항목이 아닌경우 빈값이 들어왔을경우는 유효성 체크를 통과시킴
if ((/isFill/i.test(filter) === false) && !Response.elmCurrValue) {
return RESULT_SUCCESS;
}
for (var i=0; i < count; ++i) {
var filter = filters[i];
var param = '';
var filtersInfo = this.Helper.getFilterInfo(filter);
filter = Response.elmCurrFilter = filtersInfo.id;
param = filtersInfo.param;
//필수 입력 필터의 경우 항목관리에서 사용자가 메세지를 직접 지정하는 부분이 있어 이렇게 처리
if (filter == 'isFill') {
Response.elmCurrValue = $.trim(Response.elmCurrValue);
Response.elmCurrErrorMsg = this.requireMsgs[elmTarget.id] ? this.requireMsgs[elmTarget.id] : this.msgs['isFill'];
} else {
var msg = Response.elmCurrField.attr(this.ATTR_MSG);
if (msg) {
Response.elmCurrErrorMsg = msg;
} else if (this.Helper.getElmFilterMsg(elmTarget.id, filter)) {
Response.elmCurrErrorMsg = this.Helper.getElmFilterMsg(elmTarget.id, filter);
} else {
Response.elmCurrErrorMsg = this.msgs[filter];
}
}
//존재하지 않는 필터인 경우 에러코드 반환
if(this.Filter[filter] === undefined){
Response.elmCurrErrorMsg = this.msgs['notMethod'];
var result = this.Helper.getResult(Response, this.CODE_FAIL);
Response.elmsCurrErrorField.push(result);
return Response.elmsCurrErrorField.length - 1;
}
//필터 실행
var result = this.Filter[filter](Response, param);
if (result == undefined || result.passed === this.CODE_FAIL) {
Response.elmsCurrErrorField.push(result);
//Debug를 위해 넣어둔 코드(확장형 필터를 잘못 등록해서 return값이 없는 경우를 체크하기 위함)
if (result == undefined) {
alert('Extension Filter Return error - ' + filter);
}
return Response.elmsCurrErrorField.length - 1;
}
}
} else {
var msg = Response.elmCurrErrorMsg;
Response.elmCurrErrorMsg = msg ? msg : this.msgs['isRegex'];
var result = this.Filter.isRegex(Response, filter);
if(result.passed === this.CODE_FAIL){
Response.elmsCurrErrorField.push(result);
return Response.elmsCurrErrorField.length - 1;
}
}
return RESULT_SUCCESS;
}
};
/**
* FwValidator.Response
*
* @package jquery
* @subpackage validator
*/
FwValidator.Response = function() {
this.formId = null;
this.elmForm = null;
this.elmsTarget = null;
this.elmsCurrErrorField = [];
this.elmCurrField = null;
this.elmCurrFieldType = null;
this.elmCurrFieldDisabled = null;
this.elmCurrLabel = null;
this.elmCurrValue = null;
this.elmCurrFilter = null;
this.elmCurrErrorMsg = null;
this.requireMsgs = {};
};
/**
* FwValidator.Helper
*
* @package jquery
* @subpackage validator
*/
FwValidator.Helper = {
parent : FwValidator,
/**
* 메세지 엘리먼트의 아이디 prefix
*/
msgIdPrefix : 'msg_',
/**
* 메세지 엘리먼트의 클래스 명 prefix
*/
msgClassNamePrefix : 'msg_error_mark_',
/**
* 결과 반환
*/
getResult : function(Response, code, param) {
//특수 파라미터 정보(특정 필터에서만 사용함)
param = param != undefined ? param : {};
var msg = '';
if (code === this.parent.CODE_FAIL) {
try {
msg = Response.elmCurrErrorMsg.replace(/\{label\}/i, Response.elmCurrLabel);
} catch(e) {
msg = 'No Message';
}
} else {
msg = 'success';
}
var result = {};
result.passed = code;
result.formid = Response.formId;
result.msg = msg;
result.param = param;
try {
result.element = Response.elmCurrField;
result.elmid = Response.elmCurrField.attr('id');
result.filter = Response.elmCurrFilter;
} catch(e) {}
return result;
},
/**
* 필터 정보 반환(필터이름, 파라미터)
*/
getFilterInfo : function(filter) {
var matches = filter.match(/(is[a-z]*)((?:\[.*?\])*)/i);
return {
id : matches[1],
param : this.getFilterParams(matches[2])
};
},
/**
* 필터의 파라미터 스트링 파싱
* isFill[a=1][b=1][c=1] 이런식의 멀티 파라미터가 지정되어 있는 경우는 배열로 반환함
* isFill[a=1] 단일 파라미터는 파라미터로 지정된 스트링값만 반환함
*/
getFilterParams : function(paramStr) {
if (paramStr == undefined || paramStr == null || paramStr == '') {
return '';
}
var matches = paramStr.match(/\[.*?\]/ig);
if (matches == null) {
return '';
}
var count = matches.length;
var result = [];
for (var i=0; i < count; i++) {
var p = matches[i].match(/\[(.*?)\]/);
result.push(p[1]);
}
if (result.length == 1) {
return result[0];
}
return result;
},
/**
* 필드 타입 반환(select, checkbox, radio, textbox)
*/
getElmType : function(elmField) {
elmField = $(elmField);
var elTag = elmField[0].tagName;
var result = null;
switch (elTag) {
case 'SELECT' :
result = 'select';
break;
case 'INPUT' :
var _type = elmField.attr('type').toLowerCase();
if(_type == 'checkbox') result = 'checkbox';
else if(_type =='radio') result = 'radio';
else result = 'textbox';
break;
case 'TEXTAREA' :
result = 'textbox';
break;
default :
result = 'textbox';
break;
}
return result;
},
/**
* 필드 값 반환
*/
getValue : function(formId, elmField) {
var result = '';
var elmName = elmField.attr('name');
var fieldType = this.getElmType(elmField);
//checkbox 나 radio 박스는 value값을 반환하지 않음
if (fieldType == 'checkbox' || fieldType == 'radio') {
if(elmField.get(0).checked === true){
result = elmField.val();
}
return result;
}
//alonefilter 속성이 Y 로 되어 있다면 해당 엘리먼트의 값만 반환함
var aloneFilter = elmField.attr(this.parent.ATTR_ALONE);
if(aloneFilter == 'Y' || aloneFilter == 'y'){
return elmField.val();
}
//name이 배열형태로 되어 있다면 값을 모두 합쳐서 반환
if( /\[.*?\]/.test(elmName) ){
var formInfo = this.getFormInfo(formId);
var groupElms = $(formInfo.selector +' [name="'+elmName+'"]');
groupElms.each(function(i){
var elm = $(this);
result += elm.val();
});
}else{
result = elmField.val();
}
return result;
},
/**
* 에러메세지 엘리먼트 생성
*/
createMsg : function(elm, msg, formId) {
var elmMsg = document.createElement('span');
elmMsg.id = this.msgIdPrefix + elm.attr('id');
elmMsg.className = this.msgClassNamePrefix + formId;
elmMsg.innerHTML = msg;
return $(elmMsg);
},
/**
* 에러메세지 엘리먼트 제거
*/
removeMsg : function(elm) {
var id = this.msgIdPrefix + elm.attr('id');
var elmErr = $('#'+id);
if (elmErr) elmErr.remove();
},
/**
* 에러메세지 엘리먼트 모두 제거
*/
removeAllMsg : function(formId) {
var className = this.msgClassNamePrefix + formId;
$('.' + className).remove();
},
/**
* 문자열의 Byte 수 반환
*/
getByte : function(str) {
var encode = encodeURIComponent(str);
var totalBytes = 0;
var chr;
var bytes;
var code;
for(var i = 0; i < encode.length; i++)
{
chr = encode.charAt(i);
if(chr != "%") totalBytes++;
else
{
code = parseInt(encode.substr(i+1,2),16);
if(!(code & 0x80)) totalBytes++;
else
{
if((code & 0xE0) == 0xC0) bytes = 2;
else if((code & 0xF0) == 0xE0) bytes = 3;
else if((code & 0xF8) == 0xF0) bytes = 4;
else return -1;
i += 3 * (bytes - 1);
totalBytes += 2;
}
i += 2;
}
}
return totalBytes;
},
/**
* 지정한 엘리먼트의 필터 메세지가 존재하는가
*
* @param elmId (엘리먼트 아이디)
* @param filter (필터명)
* @return string | false
*/
getElmFilterMsg : function(elmId, filter) {
if (this.parent.elmFilterMsgs[elmId] == undefined) return false;
if (this.parent.elmFilterMsgs[elmId][filter] == undefined) return false;
return this.parent.elmFilterMsgs[elmId][filter];
},
/**
* 폼 정보 반환
*
* @param formId (폼 아이디 혹은 네임)
* @return array(
* 'selector' => 셀렉터 문자,
* 'instance' => 셀렉터 문법으로 검색해낸 폼 객체
* ) | false
*/
getFormInfo : function(formId) {
var result = {};
var selector = '#' + formId;
var instance = $(selector);
if (instance.length > 0) {
result.selector = selector;
result.instance = instance;
return result;
}
selector = 'form[name="' + formId + '"]';
instance = $(selector);
if (instance.length > 0) {
result.selector = selector;
result.instance = instance;
return result;
}
return false;
},
/**
* 숫자형태의 문자열로 바꿔줌
* 123,123,123
* 123123,123
* 123%
* 123 %
* 123.4
* -123
* ,123
*
* @param value
* @return float
*/
getNumberConv : function(value) {
if (!value || value == undefined || value == null) return '';
value = value + "";
value = value.replace(/,/g, '');
value = value.replace(/%/g, '');
value = value.replace(/[\s]/g, '');
if (this.parent.Verify.isFloat(value) === false) return '';
return parseFloat(value);
}
};
/**
* FwValidator.Handler
*
* @package jquery
* @subpackage validator
*/
FwValidator.Handler = {
parent : FwValidator,
/**
* 사용자 정의형 에러핸들러(엘리먼트 아이디별로 저장됨)
*/
customErrorHandler : {},
/**
* 사용자 정의형 에러핸들러(필터별로 저장됨)
*/
customErrorHandlerByFilter : {},
/**
* 사용자 정의형 성공핸들러(엘리먼트 아이디별로 저장됨)
*/
customSuccessHandler : {},
/**
* 사용자 정의형 성공핸들러(필터별로 저장됨)
*/
customSuccessHandlerByFilter : {},
/**
* FwValidator._execute에 의해 검사되기 전 실행되는 콜백함수
*/
beforeExecute : [],
/**
* FwValidator._submit에서 바인딩한 onsubmit 이벤트 발생후 실행되는 콜백함수
* {폼아이디 : 콜백함수, ...}
*/
beforeSubmit : {},
/**
* 기본 메세지 전체를 오버라이딩
*/
overrideMsgs : function(msgs) {
if (typeof msgs != 'object') return;
this.parent.msgs = msgs;
},
/**
* 필드에 따른 필수 입력 에러메세지 설정
*/
setRequireErrorMsg : function(field, msg) {
this.parent.requireMsgs[field] = msg;
},
/**
* 필터 타입에 따른 에러메세지 설정
*/
setFilterErrorMsg : function(filter, msg) {
this.parent.msgs[filter] = msg;
},
/**
* 엘리먼트의 특정 필터에만 에러메세지를 설정
*/
setFilterErrorMsgByElement : function(elmId, filter, msg) {
if (this.parent.elmFilterMsgs[elmId] == undefined) {
this.parent.elmFilterMsgs[elmId] = {};
}
this.parent.elmFilterMsgs[elmId][filter] = msg;
},
/**
* 엘리먼트 아이디별 사용자정의형 에러핸들러 등록
*/
setCustomErrorHandler : function(elmId, func) {
if (typeof func != 'function') return;
this.customErrorHandler[elmId] = func;
},
/**
* 필터 타입별 사용자정의형 에러핸들러 등록
*/
setCustomErrorHandlerByFilter : function(filter, func) {
if (typeof func != 'function') return;
this.customErrorHandlerByFilter[filter] = func;
},
/**
* 엘리먼트 아이디별 사용자정의형 성공핸들러 등록
*/
setCustomSuccessHandler : function(elmId, func) {
if (typeof func != 'function') return;
this.customSuccessHandler[elmId] = func;
},
/**
* 필터 타입별 사용자정의형 성공핸들러 등록
*/
setCustomSuccessHandlerByFilter : function(filter, func) {
if (typeof func != 'function') return;
this.customSuccessHandlerByFilter[filter] = func;
},
/**
* 확장형 필터 등록
*/
setExtensionFilter : function(filter, func) {
if (typeof func != 'function') return;
if (this.parent.Filter[filter] == undefined) {
this.parent.Filter[filter] = func;
}
},
/**
* 각 엘리먼트가 FwValidator._execute에 의해 검사되기 전 실행되는 콜백함수 등록
*/
setBeforeExecute : function(func) {
if (typeof func != 'function') return;
this.beforeExecute.push(func);
},
/**
* FwValidator._submit 에서 바인딩된 onsubmit 이벤트의 콜백함수 등록(유효성 검사가 성공하면 호출됨)
*/
setBeforeSubmit : function(func) {
if (typeof func != 'function') return;
this.beforeSubmit = func;
},
/**
* 에러핸들러 - 기본
*/
errorHandler : function(resultData) {
if (this._callCustomErrorHandler(resultData) === true) return;
alert(resultData.msg);
resultData.element.focus();
},
/**
* 에러핸들러 - 전체 펼침 모드
*/
errorHandlerByExapnd : function(Response) {
var count = Response.elmsCurrErrorField.length;
//해당 폼에 출력된 에러메세지를 일단 모두 지운다.
this.parent.Helper.removeAllMsg(Response.formId);
for (var i=0; i < count; ++i) {
var resultData = Response.elmsCurrErrorField[i];
if (this._callCustomErrorHandler(resultData) === true) continue;
var elmMsg = this.parent.Helper.createMsg(resultData.element, resultData.msg, resultData.formid).css({'color':'#FF3300'});
elmMsg.appendTo(resultData.element.parent());
}
},
/**
* 에러핸들러 - fireon
*/
errorHandlerByFireon : function(resultData) {
if (this._callCustomErrorHandler(resultData) === true) return;
//해당 항목의 에러메세지 엘리먼트가 있다면 먼저 삭제한다.
this.parent.Helper.removeMsg(resultData.element);
var elmMsg = this.parent.Helper.createMsg(resultData.element, resultData.msg, resultData.formid).css({'color':'#FF3300'});
elmMsg.appendTo(resultData.element.parent());
return elmMsg;
},
/**
* 성공핸들러 - fireon
*/
successHandlerByFireon : function(resultData) {
this._callCustomSuccessHandler(resultData);
},
/**
* 정의형 에러 핸들러 호출
*
* @return boolean (정의형 에러핸들러를 호출했을 경우 true 반환)
*/
_callCustomErrorHandler : function(resultData) {
//resultData 가 정의되어 있지 않은 경우
if (resultData == undefined) {
alert('errorHandler - resultData is not found');
return true;
}
//해당 엘리먼트에 대한 Custom에러핸들러가 등록되어 있다면 탈출
if (this.customErrorHandler[resultData.elmid] != undefined) {
this.customErrorHandler[resultData.elmid].call(this.parent, resultData);
return true;
}
//해당 필터에 대한 Custom에러핸들러가 등록되어 있다면 탈출
if (this.customErrorHandlerByFilter[resultData.filter] != undefined) {
this.customErrorHandlerByFilter[resultData.filter].call(this.parent, resultData);
return true;
}
return false;
},
/**
* 정의형 성공 핸들러 호출 - 기본적으로 fireon 속성이 적용된 엘리먼트에만 적용됨.
*/
_callCustomSuccessHandler : function(resultData) {
if (this.customSuccessHandler[resultData.elmid] != undefined) {
this.customSuccessHandler[resultData.elmid].call(this.parent, resultData);
return;
}
if (this.customSuccessHandlerByFilter[resultData.filter] != undefined) {
this.customSuccessHandlerByFilter[resultData.filter].call(this.parent, resultData);
return;
}
}
};
/**
* FwValidator.Verify
*
* @package jquery
* @subpackage validator
*/
FwValidator.Verify = {
parent : FwValidator,
isNumber : function(value, cond) {
if (value == '') return true;
if (!cond) {
cond = 1;
}
cond = parseInt(cond);
pos = 1;
nga = 2;
minpos = 4;
minnga = 8;
result = 0;
if ((/^[0-9]+$/).test(value) === true) {
result = pos;
} else if ((/^[-][0-9]+$/).test(value) === true) {
result = nga;
} else if ((/^[0-9]+[.][0-9]+$/).test(value) === true) {
result = minpos;
} else if ((/^[-][0-9]+[.][0-9]+$/).test(value) === true) {
result = minnga;
}
if (result & cond) {
return true;
}
return false;
},
isFloat : function(value) {
if (value == '') return true;
return (/^[\-0-9]([0-9]+[\.]?)*$/).test(value);
},
isIdentity : function(value) {
if (value == '') return true;
return (/^[a-z]+[a-z0-9_]+$/i).test(value);
},
isKorean : function(value) {
if (value == '') return true;
var count = value.length;
for(var i=0; i < count; ++i){
var cCode = value.charCodeAt(i);
//공백은 무시
if(cCode == 0x20) continue;
if(cCode < 0x80){
return false;
}
}
return true;
},
isAlpha : function(value) {
if (value == '') return true;
return (/^[a-z]+$/i).test(value);
},
isAlphaUpper : function(value) {
if (value == '') return true;
return (/^[A-Z]+$/).test(value);
},
isAlphaLower : function(value) {
if (value == '') return true;
return (/^[a-z]+$/).test(value);
},
isAlphaNum : function(value) {
if (value == '') return true;
return (/^[a-z0-9]+$/i).test(value);
},
isAlphaNumUpper : function(value) {
if (value == '') return true;
return (/^[A-Z0-9]+$/).test(value);
},
isAlphaNumLower : function(value) {
if (value == '') return true;
return (/^[a-z0-9]+$/).test(value);
},
isAlphaDash : function(value) {
if (value == '') return true;
return (/^[a-z0-9_-]+$/i).test(value);
},
isAlphaDashUpper : function(value) {
if (value == '') return true;
return (/^[A-Z0-9_-]+$/).test(value);
},
isAlphaDashLower : function(value) {
if (value == '') return true;
return (/^[a-z0-9_-]+$/).test(value);
},
isSsn : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
if ( (/[0-9]{2}[01]{1}[0-9]{1}[0123]{1}[0-9]{1}[1234]{1}[0-9]{6}$/).test(value) === false ) {
return false;
}
var sum = 0;
var last = value.charCodeAt(12) - 0x30;
var bases = "234567892345";
for (var i=0; i<12; i++) {
sum += (value.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
};
var mod = sum % 11;
if ( (11 - mod) % 10 != last ) {
return false;
}
return true;
},
isForeignerNo : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
if ( (/[0-9]{2}[01]{1}[0-9]{1}[0123]{1}[0-9]{1}[5678]{1}[0-9]{1}[02468]{1}[0-9]{2}[6789]{1}[0-9]{1}$/).test(value) === false ) {
return false;
}
var sum = 0;
var last = value.charCodeAt(12) - 0x30;
var bases = "234567892345";
for (var i=0; i<12; i++) {
sum += (value.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
};
var mod = sum % 11;
if ( (11 - mod + 2) % 10 != last ) {
return false;
}
return true;
},
isBizNo : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
if ( (/[0-9]{3}[0-9]{2}[0-9]{5}$/).test(value) === false ) {
return false;
}
var sum = parseInt(value.charAt(0));
var chkno = [0, 3, 7, 1, 3, 7, 1, 3];
for (var i = 1; i < 8; i++) {
sum += (parseInt(value.charAt(i)) * chkno[i]) % 10;
}
sum += Math.floor(parseInt(parseInt(value.charAt(8))) * 5 / 10);
sum += (parseInt(value.charAt(8)) * 5) % 10 + parseInt(value.charAt(9));
if (sum % 10 != 0) {
return false;
}
return true;
},
isJuriNo : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
if ( (/^([0-9]{6})-?([0-9]{7})$/).test(value) === false ) {
return false;
}
var sum = 0;
var last = parseInt(value.charAt(12), 10);
for (var i=0; i<12; i++) {
if (i % 2 == 0) { // * 1
sum += parseInt(value.charAt(i), 10);
} else { // * 2
sum += parseInt(value.charAt(i), 10) * 2;
};
};
var mod = sum % 10;
if( (10 - mod) % 10 != last ){
return false;
}
return true;
},
isPhone : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
return (/^(02|0[0-9]{2,3})[1-9]{1}[0-9]{2,3}[0-9]{4}$/).test(value);
},
isMobile : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
return (/^01[016789][1-9]{1}[0-9]{2,3}[0-9]{4}$/).test(value);
},
isZipcode : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
return (/^[0-9]{3}[0-9]{3}$/).test(value);
},
isIp : function(value) {
if (value == '') return true;
return (/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){2,}$/).test(value);
},
isEmail : function(value) {
if (value == '') return true;
return (/^([a-z0-9\_\-\.]+)@([a-z0-9\_\-]+\.)+[a-z]{2,6}$/i).test(value);
},
isUrl : function(value) {
if (value == '') return true;
return (/http[s]?:\/\/[a-z0-9_\-]+(\.[a-z0-9_\-]+)+/i).test(value);
},
isDate : function(value) {
value = value.replace(/-/g, '');
if (value == '') return true;
return (/^[12][0-9]{3}(([0]?[1-9])|([1][012]))[0-3]?[0-9]$/).test(value);
},
isPassport : function(value) {
if (value == '') return true;
//일반 여권
if ( (/^[A-Z]{2}[0-9]{7}$/).test(value) === true ) {
return true;
}
//전자 여권
if ( (/^[A-Z]{1}[0-9]{8}$/).test(value) === true ) {
return true;
}
return false;
},
isNumberMin : function(value, limit) {
value = this.parent.Helper.getNumberConv(value);
limit = this.parent.Helper.getNumberConv(limit);
if (value < limit) {
return false;
}
return true;
},
isNumberMax : function(value, limit) {
value = this.parent.Helper.getNumberConv(value);
limit = this.parent.Helper.getNumberConv(limit);
if (value > limit) {
return false;
}
return true;
},
isNumberRange : function(value, min, max) {
value = this.parent.Helper.getNumberConv(value);
min = this.parent.Helper.getNumberConv(min);
max = this.parent.Helper.getNumberConv(max);
if (value < min || value > max) {
return false;
}
return true;
}
};
/**
* FwValidator.Filter
*
* @package jquery
* @subpackage validator
*/
FwValidator.Filter = {
parent : FwValidator,
isFill : function(Response, cond) {
if (typeof cond != 'string') {
var count = cond.length;
var result = this.parent.Helper.getResult(Response, parent.CODE_SUCCESS);
for (var i = 0; i < count; ++i) {
result = this._fillConditionCheck(Response, cond[i]);
if (result.passed === true) {
return result;
}
}
return result;
}
return this._fillConditionCheck(Response, cond);
},
isMatch : function(Response, sField) {
if(Response.elmCurrValue == ''){
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
}
//Radio 나 Checkbox의 경우 무시
if(Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox'){
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
}
var elmTarget = $('#'+sField);
var elmTargetValue = elmTarget.val();
if (Response.elmCurrValue != elmTargetValue) {
var label = elmTarget.attr(this.parent.ATTR_LABEL);
var match = label ? label : sField;
Response.elmCurrErrorMsg = Response.elmCurrErrorMsg.replace(/\{match\}/i, match);
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isMax : function(Response, iLen) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
if (Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox') {
var chkCount = 0;
var sName = Response.elmCurrField.attr('name');
$('input[name="'+sName+'"]').each(function(i){
if ($(this).get(0).checked === true) {
++chkCount;
}
});
if (chkCount > iLen) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
} else {
var len = Response.elmCurrValue.length;
if (len > iLen) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
}
if (result.passed === this.parent.CODE_FAIL) {
result.msg = result.msg.replace(/\{max\}/i, iLen);
}
return result;
},
isMin : function(Response, iLen) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
if(Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox'){
var chkCount = 0;
var sName = Response.elmCurrField.attr('name');
$('input[name="'+sName+'"]').each(function(i){
if($(this).get(0).checked === true){
++chkCount;
}
});
if (chkCount < iLen) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
}else{
var len = Response.elmCurrValue.length;
if(len < iLen){
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
}
if(result.passed === this.parent.CODE_FAIL){
result.msg = result.msg.replace(/\{min\}/i, iLen);
}
return result;
},
isNumber : function(Response, iCond) {
var result = this.parent.Verify.isNumber(Response.elmCurrValue, iCond);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isIdentity : function(Response){
var result = this.parent.Verify.isIdentity(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isKorean : function(Response){
var result = this.parent.Verify.isKorean(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlpha : function(Response){
var result = this.parent.Verify.isAlpha(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaLower : function(Response){
var result = this.parent.Verify.isAlphaLower(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaUpper : function(Response){
var result = this.parent.Verify.isAlphaUpper(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaNum : function(Response){
var result = this.parent.Verify.isAlphaNum(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaNumLower : function(Response){
var result = this.parent.Verify.isAlphaNumLower(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaNumUpper : function(Response){
var result = this.parent.Verify.isAlphaNumUpper(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaDash : function(Response){
var result = this.parent.Verify.isAlphaDash(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaDashLower : function(Response){
var result = this.parent.Verify.isAlphaDashLower(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isAlphaDashUpper : function(Response){
var result = this.parent.Verify.isAlphaDashUpper(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isSsn : function(Response){
var result = this.parent.Verify.isSsn(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isForeignerNo : function(Response){
var result = this.parent.Verify.isForeignerNo(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isBizNo : function(Response){
var result = this.parent.Verify.isBizNo(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isJuriNo : function(Response){
var result = this.parent.Verify.isJuriNo(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isPhone : function(Response){
var result = this.parent.Verify.isPhone(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isMobile : function(Response){
var result = this.parent.Verify.isMobile(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isZipcode : function(Response){
var result = this.parent.Verify.isZipcode(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isIp : function(Response){
var result = this.parent.Verify.isIp(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isEmail : function(Response){
var result = this.parent.Verify.isEmail(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isUrl : function(Response){
var result = this.parent.Verify.isUrl(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isDate : function(Response){
var result = this.parent.Verify.isDate(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isRegex : function(Response, regex){
regex = eval(regex);
if( regex.test(Response.elmCurrValue) === false ){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isPassport : function(Response){
var result = this.parent.Verify.isPassport(Response.elmCurrValue);
if(result === false){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isSimplexEditorFill : function(Response){
var result = eval(Response.elmCurrValue + ".isEmptyContent();");
if(result === true){
return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
}
return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
},
isMaxByte : function(Response, iLen) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
var len = this.parent.Helper.getByte(Response.elmCurrValue);
if (len > iLen) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{max\}/i, iLen);
}
return result;
},
isMinByte : function(Response, iLen) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
var len = this.parent.Helper.getByte(Response.elmCurrValue);
if (len < iLen) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{min\}/i, iLen);
}
return result;
},
isByteRange : function(Response, range) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
var rangeInfo = this._getRangeNum(range);
var iMin = rangeInfo.min;
var iMax = rangeInfo.max;
var len = this.parent.Helper.getByte(Response.elmCurrValue);
if (len < iMin || len > iMax) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{min\}/i, iMin);
result.msg = result.msg.replace(/\{max\}/i, iMax);
}
return result;
},
isLengthRange : function(Response, range) {
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
var rangeInfo = this._getRangeNum(range);
var iMin = rangeInfo.min;
var iMax = rangeInfo.max;
var resultMin = this.isMin(Response, iMin);
var resultMax = this.isMax(Response, iMax);
if (resultMin.passed === this.parent.CODE_FAIL || resultMax.passed === this.parent.CODE_FAIL) {
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{min\}/i, iMin);
result.msg = result.msg.replace(/\{max\}/i, iMax);
}
return result;
},
isNumberMin : function(Response, iLimit) {
var check = this.parent.Verify.isNumberMin(Response.elmCurrValue, iLimit);
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
if(check === false){
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{min\}/i, iLimit);
}
return result;
},
isNumberMax : function(Response, iLimit) {
var check = this.parent.Verify.isNumberMax(Response.elmCurrValue, iLimit);
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
if(check === false){
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{max\}/i, iLimit);
}
return result;
},
isNumberRange : function(Response, range) {
var iMin = range[0];
var iMax = range[1];
var check = this.parent.Verify.isNumberRange(Response.elmCurrValue, iMin, iMax);
var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
if(check === false){
result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
result.msg = result.msg.replace(/\{min\}/i, iMin);
result.msg = result.msg.replace(/\{max\}/i, iMax);
}
return result;
},
_getRangeNum : function(range) {
var result = {};
result.min = range[0] <= 0 ? 0 : parseInt(range[0]);
result.max = range[1] <= 0 ? 0 : parseInt(range[1]);
return result;
},
_fillConditionCheck : function(Response, cond) {
cond = $.trim(cond);
var parent = this.parent;
//조건식이 들어오면 조건식에 맞을 경우만 필수값을 체크함
if (cond) {
var conditions = cond.split('=');
var fieldId = $.trim(conditions[0]);
var fieldVal = $.trim(conditions[1]);
try {
var val = parent.Helper.getValue(Response.formId, $('#'+fieldId));
val = $.trim(val);
if(fieldVal != val) {
return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
}
} catch(e) {
if (parent.DEBUG_MODE == true) {
Response.elmCurrErrorMsg = parent.msgs['isFillError'];
Response.elmCurrErrorMsg = Response.elmCurrErrorMsg.replace(/\{condition\}/i, cond);
return parent.Helper.getResult(Response, parent.CODE_FAIL);
}
return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
}
}
//Radio 나 Checkbox의 경우 선택한값이 있는지 여부를 체크함
if (Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox') {
var sName = Response.elmCurrField.attr('name');
var result = parent.Helper.getResult(Response, parent.CODE_FAIL);
$('input[name="'+sName+'"]').each(function(i){
if ($(this).get(0).checked === true) {
result = parent.Helper.getResult(Response, parent.CODE_SUCCESS);
}
});
return result;
}
//일반 텍스트 박스
if (Response.elmCurrValue != '') {
return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
}
return parent.Helper.getResult(Response, parent.CODE_FAIL);
}
};
FwValidator.msgs = {
//기본
'isFill' : '{label} 항목은 필수 입력값입니다.',
'isNumber' : '{label} 항목이 숫자 형식이 아닙니다.',
'isEmail' : '{label} 항목이 이메일 형식이 아닙니다.',
'isIdentity' : '{label} 항목이 아이디 형식이 아닙니다.',
'isMax' : '{label} 항목이 {max}자(개) 이하로 해주십시오.',
'isMin' : '{label} 항목이 {min}자(개) 이상으로 해주십시오 .',
'isRegex' : '{label} 항목이 올바른 입력값이 아닙니다.',
'isAlpha' : '{label} 항목이 영문이 아닙니다',
'isAlphaLower' : '{label} 항목이 영문 소문자 형식이 아닙니다',
'isAlphaUpper' : '{label} 항목이 영문 대문자 형식이 아닙니다',
'isAlphaNum' : '{label} 항목이 영문이나 숫자 형식이 아닙니다.',
'isAlphaNumLower' : '{label} 항목이 영문 소문자 혹은 숫자 형식이 아닙니다.',
'isAlphaNumUpper' : '{label} 항목이 영문 대문자 혹은 숫자 형식이 아닙니다.',
'isAlphaDash' : '{label} 항목이 [영문,숫자,_,-] 형식이 아닙니다.',
'isAlphaDashLower' : '{label} 항목이 [영문 소문자,숫자,_,-] 형식이 아닙니다.',
'isAlphaDashUpper' : '{label} 항목이 [영문 대문자,숫자,_,-] 형식이 아닙니다.',
'isKorean' : '{label} 항목이 한국어 형식이 아닙니다.',
'isUrl' : '{label} 항목이 URL 형식이 아닙니다.',
'isSsn' : '{label} 항목이 주민등록번호 형식이 아닙니다.',
'isForeignerNo' : '{label} 항목이 외국인등록번호 형식이 아닙니다.',
'isBizNo' : '{label} 항목이 사업자번호 형식이 아닙니다.',
'isPhone' : '{label} 항목이 전화번호 형식이 아닙니다.',
'isMobile' : '{label} 항목이 핸드폰 형식이 아닙니다.',
'isZipcode' : '{label} 항목이 우편번호 형식이 아닙니다.',
'isJuriNo' : '{label} 항목이 법인번호 형식이 아닙니다.',
'isIp' : '{label} 항목이 아이피 형식이 아닙니다.',
'isDate' : '{label} 항목이 날짜 형식이 아닙니다.',
'isMatch' : '{label} 항목과 {match} 항목이 같지 않습니다.',
'isSuccess' : '{label} 항목의 데이터는 전송할 수 없습니다.',
'isSimplexEditorFill' : '{label}(을/를) 입력하세요',
'isPassport' : '{label} 항목이 여권번호 형식이 아닙니다.',
'isMaxByte' : '{label} 항목은 {max}bytes 이하로 해주십시오.',
'isMinByte' : '{label} 항목은 {min}bytes 이상으로 해주십시오.',
'isByteRange' : '{label} 항목은 {min} ~ {max}bytes 범위로 해주십시오.',
'isLengthRange' : '{label} 항목은 {min} ~ {max}자(개) 범위로 해주십시오.',
'isNumberMin' : '{label} 항목은 {min} 이상으로 해주십시오.',
'isNumberMax' : '{label} 항목은 {max} 이하로 해주십시오.',
'isNumberRange' : '{label} 항목은 {min} ~ {max} 범위로 해주십시오.',
//디버깅
'notMethod' : '{label} 항목에 존재하지 않는 필터를 사용했습니다.',
'isFillError' : "[{label}] 필드의 isFill {condition} 문장이 잘못되었습니다.\r\n해당 필드의 아이디를 확인하세요."
};
FwValidator.Handler.overrideMsgs({
//기본
'isFill' : sprintf(__('%s 항목은 필수 입력값입니다.'), '{label}'),
'isNumber' : sprintf(__('%s 항목이 숫자 형식이 아닙니다.'), '{label}'),
'isEmail' : sprintf(__('%s 항목이 이메일 형식이 아닙니다.'), '{label}'),
'isIdentity' : sprintf(__('%s 항목이 아이디 형식이 아닙니다.'), '{label}'),
'isMax' : sprintf(__('%1$s 항목이 %2$s자(개) 이하로 해주십시오.'), '{label}', '{max}'),
'isMin' : sprintf(__('%1$s 항목이 %2$s자(개) 이상으로 해주십시오.'), '{label}', '{min}'),
'isRegex' : sprintf(__('%s 항목이 올바른 입력값이 아닙니다.'), '{label}'),
'isAlpha' : sprintf(__('%s 항목이 영문이 아닙니다.'), '{label}'),
'isAlphaLower' : sprintf(__('%s 항목이 영문 소문자 형식이 아닙니다.'), '{label}'),
'isAlphaUpper' : sprintf(__('%s 항목이 영문 대문자 형식이 아닙니다.'), '{label}'),
'isAlphaNum' : sprintf(__('%s 항목이 영문이나 숫자 형식이 아닙니다.'), '{label}'),
'isAlphaNumLower' : sprintf(__('%s 항목이 영문 소문자 혹은 숫자 형식이 아닙니다.'), '{label}'),
'isAlphaNumUpper' : sprintf(__('%s 항목이 영문 대문자 혹은 숫자 형식이 아닙니다.'), '{label}'),
'isAlphaDash' : sprintf(__('%s 항목이 [영문,숫자,_,-] 형식이 아닙니다.'), '{label}'),
'isAlphaDashLower' : sprintf(__('%s 항목이 [영문 소문자,숫자,_,-] 형식이 아닙니다.'), '{label}'),
'isAlphaDashUpper' : sprintf(__('%s 항목이 [영문 대문자,숫자,_,-] 형식이 아닙니다.'), '{label}'),
'isKorean' : sprintf(__('%s 항목이 한국어 형식이 아닙니다.'), '{label}'),
'isUrl' : sprintf(__('%s 항목이 URL 형식이 아닙니다.'), '{label}'),
'isSsn' : sprintf(__('%s 항목이 주민등록번호 형식이 아닙니다.'), '{label}'),
'isForeignerNo' : sprintf(__('%s 항목이 외국인등록번호 형식이 아닙니다.'), '{label}'),
'isBizNo' : sprintf(__('%s 항목이 사업자번호 형식이 아닙니다.'), '{label}'),
'isPhone' : sprintf(__('%s 항목이 전화번호 형식이 아닙니다.'), '{label}'),
'isMobile' : sprintf(__('%s 항목이 핸드폰 형식이 아닙니다.'), '{label}'),
'isZipcode' : sprintf(__('%s 항목이 우편번호 형식이 아닙니다.'), '{label}'),
'isJuriNo' : sprintf(__('%s 항목이 법인번호 형식이 아닙니다.'), '{label}'),
'isIp' : sprintf(__('%s 항목이 아이피 형식이 아닙니다.'), '{label}'),
'isDate' : sprintf(__('%s 항목이 날짜 형식이 아닙니다.'), '{label}'),
'isMatch' : sprintf(__('%1$s 항목과 %2$s 항목이 같지 않습니다.'), '{label}', '{match}'),
'isSuccess' : sprintf(__('%s 항목의 데이터는 전송할 수 없습니다.'), '{label}'),
'isSimplexEditorFill' : sprintf(__('%s(을/를) 입력하세요.'), '{label}'),
'isPassport' : sprintf(__('%s 항목이 여권번호 형식이 아닙니다.'), '{label}'),
'isMaxByte' : sprintf(__('%1$s 항목은 %2$sbytes 이하로 해주십시오.'), '{label}', '{max}'),
'isMinByte' : sprintf(__('%1$s 항목은 %2$sbytes 이상으로 해주십시오.'), '{label}', '{min}'),
'isByteRange' : sprintf(__('%1$s 항목은 %2$s ~ %3$sbytes 범위로 해주십시오.'), '{label}', '{min}', '{max}'),
'isLengthRange' : sprintf(__('%1$s 항목은 %2$s ~ %3$s자(개) 범위로 해주십시오.'), '{label}', '{min}', '{max}'),
'isNumberMin' : sprintf(__('%1$s 항목은 %2$s 이상으로 해주십시오.'), '{label}', '{min}'),
'isNumberMax' : sprintf(__('%1$s 항목은 %2$s 이하로 해주십시오.'), '{label}', '{max}'),
'isNumberRange' : sprintf(__('%1$s 항목은 %2$s ~ %3$s 범위로 해주십시오.'), '{label}', '{min}', '{max}'),
//디버깅
'notMethod' : sprintf(__('%s 항목에 존재하지 않는 필터를 사용했습니다.'), '{label}'),
'isFillError' : sprintf(__('[%1$s] 필드의 isFill %2$s 문장이 잘못되었습니다.\r\n해당 필드의 아이디를 확인하세요.'), '{label}', '{condition}')
});
$(document).ready(function(){
getMyShoppingInfo();
});
function getMyShoppingInfo()
{
$.ajax({
url : '/exec/front/Myshop/ApiShoppinginfo',
type : 'POST',
cache : false,
dataType: 'json',
success : function(data){
if (data.rtn_code='0000') {
var aData = data.rtn_data;
$('#xans_myshop_mileage').html( aData['mileage'] );
$('#xans_myshop_deposit').html( aData['deposit'] );
$('#xans_myshop_basket_cnt').html( aData['basket_cnt'] );
$('#xans_myshop_basket_price').html( aData['basket_price'] );
$('#xans_myshop_coupon_cnt').html( aData['coupon_cnt'] );
$('#xans_myshop_interest_prd_cnt').html( aData['interest_prd_cnt'] );
}
}
});
}
/**
* 게시판 관련 JS
*/
$(document).ready(function(){
BOARD.event_bind();
// 게시판메뉴 이미지 롤오버
BOARD.board_img_over();
});
var BOARD = {
/**
* 이벤트 바인딩을 합니다.
*/
event_bind : function ()
{
$(".eReplyStatusChangeBtn, #eReplyStatusChangeBtn").click(function (event) {
event.preventDefault(); // 기존 a 태그 href 동작 해제
BOARD.setReplyStatus();
});
},
/**
* ECHOSTING-70918
* 처리상태에 대한 값을 UPDATE 합니다.
*/
setReplyStatus : function()
{
$.ajax({
type : 'post',
dataType : 'json',
url : getMultiShopUrl("/exec/admin/board/ReplyStatusAjax"),
data : {
mode : 'UPDATE',
board_no : $("#board_no").val(),
no : $("#no").val(),
reply_status : $("#eReplyStatusChangeTarget").val()
},
success : function(aOutputData) {
if (aOutputData['result'] == 'T') {
BOARD.setSuccessResult(aOutputData);
} else {
alert("잘못된 접근입니다.");
}
},
error : function() {
alert("네트워크 상태가 불안정 합니다. 잠시 후 다시 시도해주세요");
}
});
},
/**
* ECHOSTING-70918
* 성공 결과에 대한 피드백을 합니다.
*/
setSuccessResult : function (aResult)
{
switch (aResult['status']) {
case "N" :
alert("처리중 상태가 해제되었습니다.");
break;
default :
alert("처리중으로 변경되었습니다.");
break;
}
// 새로운 상태로 갱신
$("#eReplyStatusText, .eReplyStatusText").html(aResult['new_status_icon']); // 상태
$("#eReplyStatusText, .eReplyStatusText").attr("class", aResult['new_status_style']); // 상태 스타일
$("#eReplyStatusChangeBtn, .eReplyStatusChangeBtn").html(aResult['new_status_btn_icon']); // 버튼 텍스트
$("#eReplyStatusChangeTarget").val(aResult['new_target_status']); // 변경될 값
},
/**
* 공지글 보기
*/
show_notice : function()
{
var bFlag = $('input:[type="checkbox"][name="showNotice"]')[0].checked;
if (bFlag === true) {
$('.mNoticeFlag').each(function(index, node){
$(node).show();
});
} else {
$('.mNoticeFlag').each(function(index, node){
$(node).hide();
});
}
},
/**
* 게시물 복사
* @param link
* @param board_no
* @param listName
*/
article_copy : function(link, board_no, listName, aNo, return_url)
{
if (!aNo) {
var aNo = this.check_nos( listName );
if ( aNo.length <= 0 ) {
alert(__('복사할 글을 선택하여 주세요.'));
return;
}
}
var dest_board_no = $("#boardGroup option:selected").val();
if ( confirm(__("복사하시겠습니까?"))) {
location.href = link + "?board_no=" + board_no + "&board_target=" + aNo + "&dest_board_no=" + dest_board_no + "&return_url=" + return_url;
}
},
/**
* 게시물 이동
* @param link
* @param board_no
* @param listName
*/
article_move : function(link, board_no, listName, aNo, return_url)
{
if (!aNo) {
var aNo = this.check_nos( listName );
if ( aNo.length <= 0 ) {
alert(__('이동할 글을 선택하여 주세요.'));
return;
}
}
var dest_board_no = $("#boardGroup option:selected").val();
if (board_no == dest_board_no) {
alert(__('동일한 게시판으로 게시물을 이동 할 수 없습니다.'));
return false;
}
location.href = link + "?board_no=" + board_no + "&board_target=" + aNo + "&dest_board_no=" + dest_board_no + "&return_url=" + return_url;
},
/**
* 카테고리 이동
* @param link
* @param board_no
* @param listName
*/
category_move : function(link, board_no, listName, return_url)
{
var aNo = this.check_nos( listName );
if ( aNo.length <= 0 ) {
alert(__('이동할 글을 선택하여 주세요.'));
return;
}
var dest_category = $("#board_category_move option:selected").val();
location.href = link + "?board_no=" + board_no + "&board_target=" + aNo + "&dest_category=" + dest_category + "&return_url=" + return_url;
},
is_spam : function(mode, bbs_no, bbs_type, listName, return_url)
{
if (bbs_no == ''){
var bbs_no = this.check_nos(listName);
if (bbs_no.length <= 0) {
alert(__('댓글을 선택하여 주세요.'));
return;
}
}
if (mode == 'move') {
return_url = (return_url)? '&return_url='+return_url : '';
this.OpenWindow('/admin/php/b/board_spam_regist.php?mode='+mode+'&bbs_type='+bbs_type+'&bbs_no='+bbs_no+return_url, 'spamRegist', '450', '350','no');
} else {
this.OpenWindow('/admin/php/b/board_spam_restore.php?mode='+mode+'&bbs_type='+bbs_type+'&bbs_no='+bbs_no, 'spamRestore', '470', '350','yes');
}
},
/**
* 관리자 설정에 따른 제목, 컨텐츠 고정하기
*/
fix_subject_content : function(sAgent)
{
$("select[name='subject']").change(function(){
if ($("#fix_content_" + this.selectedIndex).val() != undefined) {
var content = $("#fix_content_" + this.selectedIndex).val() + $("#fix_add_content").val();
} else {
if ($("#fix_add_content").val() != undefined) {
var content = $("#fix_add_content").val();
} else {
var content = '';
}
}
// 답변, 수정 모드에서는 컨텐츠 영역이 수정되지 않도록 한다.
if ($('#no').length == 0 && content != '') {
if (sAgent == true) {
$("#content").val(content);
} else {
$("#content_IFRAME").get(0).contentWindow.document.body.innerHTML = content;
}
}
});
},
/**
* 항상 비밀글 사용하기
*/
disable_secret : function()
{
$("#secure0").attr({
"checked": "",
"disabled" : "disabled"
});
$("#secure1").attr("checked", "checked");
},
/**
* 게시판메뉴 이미지 롤오버
*/
board_img_over : function()
{
$(".board_img_over").hover(function(){
var tmpImgOver = $(this).attr('eImgOver');
var tmpSrc = $(this).attr('src');
$(this).attr('eImgOver', tmpSrc)
$(this).attr('src',tmpImgOver)
}, function(){
var tmpImgOver = $(this).attr('eImgOver');
var tmpSrc = $(this).attr('src');
$(this).attr('eImgOver', tmpSrc)
$(this).attr('src',tmpImgOver)
})
},
/**
* 폼 submit
* @param string sFormName 폼 name
*/
form_submit : function(sFormName)
{
// 서밋 위치를 BOARD_WRITE로 변경
$('#'+sFormName).submit();
},
/**
* 리스트 정렬 submit
* @param string sFormName 폼 name
*/
change_sort : function(sFormName, obj)
{
$('#'+sFormName+' [id="board_sort"]').val(obj.value);
$('#'+sFormName).submit();
},
/**
* 답변여부 선택 select
* @param element obj select element
*/
change_reply_sort: function(obj)
{
var sQueryString = document.location.search.substr(1);
var aParams = {};
$.each(sQueryString.split('&'), function(i, str){
var sKey = str.substr(0, str.indexOf('='));
if ('page' !== sKey) {
var sVal = str.substr(str.indexOf('=')+1);
aParams[sKey] = sVal;
}
});
aParams['is_reply_sort'] = $(obj).val();
var aUrls = [];
$.each(aParams, function(sKey, sVal){
if ('' !== $.trim(sVal)) {
aUrls.push(sKey+'='+$.trim(sVal));
}
});
document.location.href = document.location.pathname+'?'+aUrls.join('&');
},
/**
* 상품후기 리스트 펼침
* @param int iNo 글번호
* @param int iBoardNo 게시판번호
* @param object obj
*/
viewTarget : function(iNo, iBoardNo, obj) {
var self = this;
var elmTarget = $(obj);
if (elmTarget.parents('tr').next().attr('id') == 'content_view') {
elmTarget.find('img').attr('src', function() {
return this.src.replace('_fold','_unfold');
});
self.changeFoldImg(obj);
$('#content_view').remove();
return;
} else {
$('#content_view').remove();
var aData = {
'no' : iNo,
'board_no' : iBoardNo
}
$.get('/exec/front/board/Get/'+iBoardNo, aData, function(req) {
if (req.failed == false) {
var rData = req.data;
elmTarget.find('img').attr('src', function() {
return this.src.replace('_unfold','_fold');
});
self.changeFoldImg(obj);
var aHtml = [];
aHtml.push('<tr id="content_view">');
aHtml.push(' <td colspan='+elmTarget.parents('tr').find('td').length+'>');
if (rData.content_image != null) aHtml.push(''+rData.content_image+'<br />');
aHtml.push(' '+rData.content);
aHtml.push(' </td>');
aHtml.push('</tr>');
elmTarget.parents('tr').after(aHtml.join(''));
} else {
BOARD.setBulletinSpreadFail(req.data);
};
}, 'json');
}
},
setBulletinSpreadFail : function (sFailType)
{
switch(sFailType) {
case 'S' :
alert(__('비밀글은 미리보기가 불가 합니다.'));
break;
case 'M' :
alert(__('회원에게만 읽기 권한이 있습니다'));
break;
case 'A' :
alert(__('관리자에게만 읽기 권한이 있습니다'));
break;
}
},
/**
* 폴딩 이미지 변환
* 현재 클릭한 이미지 이외에는 모두 '닫힘' 이미지로 만들기 위함
*
* @param HtmlElement obj
*/
changeFoldImg : function(obj) {
var elmEventList = $('[onclick*="BOARD.viewTarget"]');
elmEventList.each(function(){
if (obj !== this) {
$(this).find('img').attr('src', function() {
return this.src.replace('_fold','_unfold');
});
}
});
},
/**
* 관리자 댓글보기 (관리자전용)
*/
pre_comment : function()
{
this.OpenWindow('/admin/php/b/board_admin_pre_comment_l.php?mode=popup', 'pre_comment', '800', '500','auto');
},
/**
* 첨부이미지 미리보기
* @param sId
* @param sFlag
*/
afile_display : function (sId, sFlag)
{
if (sFlag == 1) {
$('#'+sId).css('display', '');
$('#'+sId).css('position', 'absolute');
} else {
$('#'+sId).css('display', 'none');
}
},
/**
* 게시판 목록 선택 갯수 체크
* @param listName
* @returns {Array}
*/
check_nos : function(listName)
{
var aNo = [];
$("." + listName).each(function(){
if ( this.checked ) {
aNo.push( this.value );
}
});
return aNo;
},
/**
* window.open
* @param StrPage
* @param StrName
* @param w
* @param h
* @param scrolls
*/
OpenWindow : function(StrPage, StrName, w, h,scrolls)
{
var win = null;
var winl = (screen.width-w)/2;
var wint = (screen.height-h)/3;
settings = 'height='+h+',';
settings += 'width='+w+',';
settings += 'top='+wint+',';
settings += 'left='+winl+',';
settings += 'scrollbars='+scrolls+',';
settings += 'resizable=no,';
settings += 'status=no';
win = window.open(StrPage, StrName, settings);
if (parseInt(navigator.appVersion)>=4) {
win.window.focus();
}
},
END : function() {}
};
$(document).ready(function(){
// 캘린더 쓰기/수정 날짜 선택 캘린더 보기
if ($('#date').val() != undefined) {
if (SHOP.getLanguage() == 'ko_KR') {
$('#date').Calendar({
input_target:'#date',
days: ['일','월','화','수','목','금','토']
});
} else {
$('#date').Calendar({
input_target:'#date',
days: ['S','M','T','W','T','F','S']
});
}
}
});
var CALENDAR = {
/**
* 캘린더 카테고리 변경
*/
setCalendarChange : function(sYear, sMonth, sDay)
{
var url = '?currentYear=' + sYear + '&currentMonth=' + sMonth + '&currentDay=' + sDay;
window.location.href = url;
},
/**
* 내용 쓰기 (팝업)
*/
popupWrite : function(sUrl)
{
sUrl += '?cl_date='+$('#hiddenDate').val();
CALENDAR.OpenWindow(sUrl, 'CalendarWrite', '536', '313','no');
},
/**
* 내용 보기 (팝업)
*/
popupView : function(sUrl)
{
CALENDAR.OpenWindow(sUrl, 'CalendarView', '604', '425','yes');
},
/**
* 내용 수정 (팝업)
*/
popupModify : function(url)
{
window.location.href = url;
resizeTo(567, 450);
},
/**
* 추가정보 캘린더 내용보기 (레이어)
*/
layerView : function(obj)
{
$('div').each(function(e) {
if (this.style.display == 'block') {
$(this).hide(100);
}
});
$(obj).next('div').append('<input type="hidden" id="focus_div">')
$(obj).next('div').show(100);
$(obj).next('div').css('display', 'block');
},
/**
* 추가정보 캘린더 내용닫기 (레이어)
*/
layerClose : function(obj)
{
if ($(obj).parent('div').css('display') == 'block') {
$(obj).parent('div').hide(100);
return;
}
},
/**
* 일 선택
*/
setSelectDay : function(id)
{
$('[id|="dateArea"]').each(function() {
$(this).attr('class', 'cal_day');
})
$('#hiddenDate').val(id.replace('dateArea-', ''));
$('#'+id).attr('class', 'cal_day_select');
},
/**
* window.open
* @param StrPage
* @param StrName
* @param w
* @param h
* @param scrolls
*/
OpenWindow : function(StrPage, StrName, w, h,scrolls)
{
var win = null;
var winl = (screen.width-w)/2;
var wint = (screen.height-h)/3;
settings = 'height='+h+',';
settings += 'width='+w+',';
settings += 'top='+wint+',';
settings += 'left='+winl+',';
settings += 'scrollbars='+scrolls+',';
settings += 'resizable=no,';
settings += 'status=no';
win = window.open(StrPage, StrName, settings);
if (parseInt(navigator.appVersion)>=4) {
win.window.focus();
}
},
/**
* 카테고리 변경
*/
changeCategory : function(obj)
{
$(obj).submit();
},
/**
* 게시글 내용 보기
*/
viewContent : function(seq)
{
if ($('.'+seq).next().attr('id') == 'content_view') {
$('#content_view').remove();
return;
} else {
$('#content_view').remove();
var aHtml = [];
aHtml.push('<tr id="content_view" class="calendar_view_contents">');
aHtml.push(' <td colspan='+$('.'+seq+' td').length+'>');
aHtml.push(' '+contents[seq]['list_content']+'<br>'+contents[seq]['list_add_info']);
aHtml.push(' </td>');
aHtml.push('</tr>');
$('.'+seq).after(aHtml.join(''));
}
},
/**
* write submit
*/
setWrite : function(sFormName)
{
$('#category_no').val(opener.$('#category_no').val());
$('#'+sFormName).submit();
},
/**
* Modify submit
*/
setModify : function(sFormName, sAction)
{
$('#'+sFormName).attr('action', sAction);
$('#'+sFormName).submit();
},
/**
* Delete submit
*/
setDelete : function(sFormName, sAction)
{
if (confirm(__('삭제 하시겠습니까?'))) {
$('#'+sFormName).attr('action', sAction);
$('#'+sFormName).submit();
}
},
/**
* 내용 자르기
*/
cutContent : function(obj)
{
var content_value = $(obj).val();
var content_max = $('#content_max').val();
if (content_max > 0) {
if (content_value.length > content_max) {
alert(__('내용이 너무 깁니다'));
$(obj).val(content_value.substring(0, content_max));
return false;
}
}
},
END : function() {}
};
/**
* 쇼핑몰 금액 라이브러리
*/
var SHOP_PRICE = {
/**
* iShopNo 쇼핑몰의 결제화폐에 맞게 리턴합니다.
* @param float fPrice 금액
* @param bool bIsNumberFormat number_format 적용 유무
* @param int iShopNo 쇼핑몰번호
* @return float|string
*/
toShopPrice: function(fPrice, bIsNumberFormat, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 결제화폐 정보
var aCurrencyInfo = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo;
return SHOP_PRICE.toPrice(fPrice, aCurrencyInfo, bIsNumberFormat);
},
/**
* iShopNo 쇼핑몰의 참조화폐에 맞게 리턴합니다.
* @param float fPrice 금액
* @param bool bIsNumberFormat number_format 적용 유무
* @param int iShopNo 쇼핑몰번호
* @return float|string
*/
toShopSubPrice: function(fPrice, bIsNumberFormat, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 참조화폐 정보
var aSubCurrencyInfo = SHOP_CURRENCY_INFO[iShopNo].aShopSubCurrencyInfo;
if ( ! aSubCurrencyInfo) {
// 참조화폐가 없으면
return '';
} else {
// 결제화폐 정보
var aCurrencyInfo = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo;
if (aSubCurrencyInfo.currency_code === aCurrencyInfo.currency_code) {
// 결제화폐와 참조화폐가 동일하면
return '';
} else {
return SHOP_PRICE.toPrice(fPrice, aSubCurrencyInfo, bIsNumberFormat);
}
}
},
/**
* 쇼핑몰의 기준화폐에 맞게 리턴합니다.
* @param float fPrice 금액
* @param bool bIsNumberFormat number_format 적용 유무
* @param int iShopNo 쇼핑몰번호
* @return float
*/
toBasePrice: function(fPrice, bIsNumberFormat, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 기준화폐 정보
var aBaseCurrencyInfo = SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo;
return SHOP_PRICE.toPrice(fPrice, aBaseCurrencyInfo, bIsNumberFormat);
},
/**
* 결제화폐 금액을 참조화폐 금액으로 변환하여 리턴합니다.
* @param float fPrice 금액
* @param bool bIsNumberFormat number_format 적용 유무
* @param int iShopNo 쇼핑몰번호
* @return float 참조화폐 금액
*/
shopPriceToSubPrice: function(fPrice, bIsNumberFormat, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 결제화폐 금액 => 참조화폐 금액
fPrice = fPrice * (SHOP_CURRENCY_INFO[iShopNo].fExchangeSubRate || 0);
return SHOP_PRICE.toShopSubPrice(fPrice, bIsNumberFormat, iShopNo);
},
/**
* 결제화폐 대비 기준화폐 환율 리턴
* @param int iShopNo 쇼핑몰번호
* @return float 결제화폐 대비 기준화폐 환율
*/
getRate: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
return SHOP_CURRENCY_INFO[iShopNo].fExchangeRate;
},
/**
* 결제화폐 대비 참조화폐 환율 리턴
* @param int iShopNo 쇼핑몰번호
* @return float 결제화폐 대비 참조화폐 환율 (참조화폐가 없는 경우 null을 리턴합니다.)
*/
getSubRate: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
return SHOP_CURRENCY_INFO[iShopNo].fExchangeSubRate;;
},
/**
* 금액을 원하는 화폐코드의 제약조건(소수점 절삭)에 맞춰 리턴합니다.
* @param float fPrice 금액
* @param string aCurrencyInfo 원하는 화폐의 화폐 정보
* @param bool bIsNumberFormat number_format 적용 유무
* @return float|string
*/
toPrice: function(fPrice, aCurrencyInfo, bIsNumberFormat)
{
// 소수점 아래 절삭
var iPow = Math.pow(10, aCurrencyInfo['decimal_place']);
fPrice = fPrice * iPow;
if (aCurrencyInfo['round_method_type'] === 'F') {
fPrice = Math.floor(fPrice);
} else if (aCurrencyInfo['round_method_type'] === 'C') {
fPrice = Math.ceil(fPrice);
} else {
fPrice = Math.round(fPrice);
}
fPrice = fPrice / iPow;
if ( ! fPrice) {
// 가격이 없는 경우
return 0;
} else if (bIsNumberFormat === true) {
// 3자리씩 ,로 끊어서 리턴
var sPrice = fPrice.toFixed(aCurrencyInfo['decimal_place']);
var regexp = /^(-?[0-9]+)([0-9]{3})($|\.|,)/;
while (regexp.test(sPrice)) {
sPrice = sPrice.replace(regexp, "$1,$2$3");
}
return sPrice;
} else {
// 숫자만 리턴
return fPrice;
}
}
};
/**
* 화폐 포맷
*/
var SHOP_CURRENCY_FORMAT = {
/**
* 어드민 페이지인지
* @var bool
*/
_bIsAdmin: /^\/(admin\/php|disp\/admin|exec\/admin)\//.test(location.pathname) ? true : false,
/**
* iShopNo 쇼핑몰의 결제화폐 포맷을 리턴합니다.
* @param int iShopNo 쇼핑몰번호
* @return array head,tail
*/
getShopCurrencyFormat: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 결제화폐 코드
var sCurrencyCode = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.currency_code;
if (SHOP_CURRENCY_FORMAT._bIsAdmin === true) {
// 어드민
// 기준화폐 코드
var sBaseCurrencyCode = SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.currency_code;
if (sCurrencyCode === sBaseCurrencyCode) {
// 결제화폐와 기준화폐가 동일한 경우
return {
'head': '',
'tail': ''
};
} else {
return {
'head': sCurrencyCode + ' ',
'tail': ''
};
}
} else {
// 프론트
return SHOP_CURRENCY_INFO[iShopNo].aFrontCurrencyFormat;
}
},
/**
* iShopNo 쇼핑몰의 참조화폐의 포맷을 리턴합니다.
* @param int iShopNo 쇼핑몰번호
* @return array head,tail
*/
getShopSubCurrencyFormat: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 참조화폐 정보
var aSubCurrencyInfo = SHOP_CURRENCY_INFO[iShopNo].aShopSubCurrencyInfo;
if ( ! aSubCurrencyInfo) {
// 참조화폐가 없으면
return {
'head': '',
'tail': ''
};
} else if (SHOP_CURRENCY_FORMAT._bIsAdmin === true) {
// 어드민
return {
'head': '(' + aSubCurrencyInfo.currency_code + ' ',
'tail': ')'
};
} else {
// 프론트
return SHOP_CURRENCY_INFO[iShopNo].aFrontSubCurrencyFormat;
}
},
/**
* 쇼핑몰의 기준화폐의 포맷을 리턴합니다.
* @param int iShopNo 쇼핑몰번호
* @return array head,tail
*/
getBaseCurrencyFormat: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
// 기준화폐 코드
var sBaseCurrencyCode = SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.currency_code;
// 결제화폐 코드
var sCurrencyCode = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.currency_code;
if (sCurrencyCode === sBaseCurrencyCode) {
// 기준화폐와 결제화폐가 동일하면
return {
'head': '',
'tail': ''
};
} else {
// 어드민
return {
'head': '(' + sBaseCurrencyCode + ' ',
'tail': ')'
};
}
},
/**
* 금액 입력란 화폐 포맷용 head,tail
* @param int iShopNo 쇼핑몰번호
* @return array head,tail
*/
getInputFormat: function(iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var sCurrencyCode = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo;
// 멀티쇼핑몰이 아니고 단위가 '원화'인 경우
if (SHOP.isMultiShop() === false && sCurrencyCode === 'KRW') {
return {
'head': '',
'tail': '원'
};
} else {
return {
'head': '',
'tail': sCurrencyCode
};
}
}
};
/**
* 금액 포맷
*/
var SHOP_PRICE_FORMAT = {
/**
* iShopNo 쇼핑몰의 결제화폐에 맞도록 하고 포맷팅하여 리턴합니다.
* @param float fPrice 금액
* @param int iShopNo 쇼핑몰번호
* @return string
*/
toShopPrice: function(fPrice, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var aFormat = SHOP_CURRENCY_FORMAT.getShopCurrencyFormat(iShopNo);
var sPrice = SHOP_PRICE.toShopPrice(fPrice, true, iShopNo);
return aFormat.head + sPrice + aFormat.tail;
},
/**
* iShopNo 쇼핑몰의 참조화폐에 맞도록 하고 포맷팅하여 리턴합니다.
* @param float fPrice 금액
* @param int iShopNo 쇼핑몰번호
* @return string
*/
toShopSubPrice: function(fPrice, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var aFormat = SHOP_CURRENCY_FORMAT.getShopSubCurrencyFormat(iShopNo);
var sPrice = SHOP_PRICE.toShopSubPrice(fPrice, true, iShopNo);
return aFormat.head + sPrice + aFormat.tail;
},
/**
* 쇼핑몰의 기준화폐에 맞도록 하고 포맷팅하여 리턴합니다.
* @param float fPrice 금액
* @param int iShopNo 쇼핑몰번호
* @return string
*/
toBasePrice: function(fPrice, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var aFormat = SHOP_CURRENCY_FORMAT.getBaseCurrencyFormat(iShopNo);
var sPrice = SHOP_PRICE.toBasePrice(fPrice, true, iShopNo);
return aFormat.head + sPrice + aFormat.tail;
},
/**
* 결제화폐 금액을 참조화폐 금액으로 변환하고 포맷팅하여 리턴합니다.
* @param float fPrice 금액
* @param int iShopNo 쇼핑몰번호
* @return string
*/
shopPriceToSubPrice: function(fPrice, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var aFormat = SHOP_CURRENCY_FORMAT.getShopSubCurrencyFormat(iShopNo);
var sPrice = SHOP_PRICE.shopPriceToSubPrice(fPrice, true, iShopNo);
return aFormat.head + sPrice + aFormat.tail;
},
/**
* 금액을 적립금 단위 명칭 설정에 따라 반환
* @param float fPrice 금액
* @return float|string
*/
toShopMileagePrice: function (fPrice) {
if (typeof sMileageUnit != 'undefined' || $.trim(sMileageUnit) != '') {
return fPrice + sMileageUnit;
} else {
return SHOP_PRICE_FORMAT.toShopPrice(fPrice);
}
},
/**
* 금액을 예치금 단위 명칭 설정에 따라 반환
* @param float fPrice 금액
* @return float|string
*/
toShopDepositPrice: function (fPrice) {
if (typeof sDepositUnit != 'undefined' || $.trim(sDepositUnit) != '') {
return fPrice + sDepositUnit;
} else {
return SHOP_PRICE_FORMAT.toShopPrice(fPrice);
}
}
};
var SHOP_PRICE_UTIL = {
/**
* iShopNo 쇼핑몰의 결제화폐 금액 입력폼으로 만듭니다.
* @param Element elem 입력폼
*/
toShopPriceInput: function(elem, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var iDecimalPlace = SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.decimal_place;
SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
},
/**
* iShopNo 쇼핑몰의 참조화폐 금액 입력폼으로 만듭니다.
* @param Element elem 입력폼
*/
toShopSubPriceInput: function(elem, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var iDecimalPlace = SHOP_CURRENCY_INFO[iShopNo].aShopSubCurrencyInfo.decimal_place;
SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
},
/**
* iShopNo 쇼핑몰의 기준화폐 금액 입력폼으로 만듭니다.
* @param Element elem 입력폼
*/
toBasePriceInput: function(elem, iShopNo)
{
iShopNo = parseInt(iShopNo) || EC_SDE_SHOP_NUM;
var iDecimalPlace = SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.decimal_place;
SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
},
/**
* 소수점 iDecimalPlace까지만 입력 가능하도록 처리
* @param Element elem 입력폼
* @param int iDecimalPlace 허용 소수점
*/
_toPriceInput: function(elem, iDecimalPlace)
{
attachEvent(elem, 'keyup', function(e) {
e = e || window.event;
replaceToPrice(e.srcElement);
});
attachEvent(elem, 'blur', function(e) {
e = e || window.event;
replaceToPrice(e.srcElement);
});
function replaceToPrice(target)
{
var value = target.value;
var regExpTest = new RegExp('^[0-9]*' + (iDecimalPlace ? '' : '\\.[0-9]{0, ' + iDecimalPlace + '}' ) + '$');
if (regExpTest.test(value) === false) {
value = value.replace(/[^0-9.]/g, '');
if (parseInt(iDecimalPlace)) {
value = value.replace(/^([0-9]+\.[0-9]+)\.+.*$/, '$1');
value = value.replace(new RegExp('(\\.[0-9]{' + iDecimalPlace + '})[0-9]*$'), '$1');
} else {
value = value.replace(/\.+[0-9]*$/, '');
}
target.value = value;
}
}
function attachEvent(elem, sEventName, fn)
{
if ( elem.addEventListener ) {
elem.addEventListener( sEventName, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + sEventName, fn );
}
}
}
};
if (window.jQuery !== undefined) {
$.fn.extend({
toShopPriceInput : function(iShopNo)
{
return this.each(function(){
var iElementShopNo = $(this).data('shop_no') || iShopNo;
SHOP_PRICE_UTIL.toShopPriceInput(this, iElementShopNo);
});
},
toShopSubPriceInput : function(iShopNo)
{
return this.each(function(){
var iElementShopNo = $(this).data('shop_no') || iShopNo;
SHOP_PRICE_UTIL.toShopSubPriceInput(this, iElementShopNo);
});
},
toBasePriceInput : function(iShopNo)
{
return this.each(function(){
var iElementShopNo = $(this).data('shop_no') || iShopNo;
SHOP_PRICE_UTIL.toBasePriceInput(this, iElementShopNo);
});
}
});
}
/**
* jQuery JSON Plugin
* version: 2.3 (2011-09-17)
*
* This document is licensed as free software under the terms of the
* MIT License: http://www.opensource.org/licenses/mit-license.php
*
* Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
* website's http://www.json.org/json2.js, which proclaims:
* "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
* I uphold.
*
* It is also influenced heavily by MochiKit's serializeJSON, which is
* copyrighted 2005 by Bob Ippolito.
*/
(function( $ ) {
var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
/**
* jQuery.toJSON
* Converts the given argument into a JSON respresentation.
*
* @param o {Mixed} The json-serializble *thing* to be converted
*
* If an object has a toJSON prototype, that will be used to get the representation.
* Non-integer/string keys are skipped in the object, as are keys that point to a
* function.
*
*/
$.toJSON = typeof JSON === 'object' && JSON.stringify
? JSON.stringify
: function( o ) {
if ( o === null ) {
return 'null';
}
var type = typeof o;
if ( type === 'undefined' ) {
return undefined;
}
if ( type === 'number' || type === 'boolean' ) {
return '' + o;
}
if ( type === 'string') {
return $.quoteString( o );
}
if ( type === 'object' ) {
if ( typeof o.toJSON === 'function' ) {
return $.toJSON( o.toJSON() );
}
if ( o.constructor === Date ) {
var month = o.getUTCMonth() + 1,
day = o.getUTCDate(),
year = o.getUTCFullYear(),
hours = o.getUTCHours(),
minutes = o.getUTCMinutes(),
seconds = o.getUTCSeconds(),
milli = o.getUTCMilliseconds();
if ( month < 10 ) {
month = '0' + month;
}
if ( day < 10 ) {
day = '0' + day;
}
if ( hours < 10 ) {
hours = '0' + hours;
}
if ( minutes < 10 ) {
minutes = '0' + minutes;
}
if ( seconds < 10 ) {
seconds = '0' + seconds;
}
if ( milli < 100 ) {
milli = '0' + milli;
}
if ( milli < 10 ) {
milli = '0' + milli;
}
return '"' + year + '-' + month + '-' + day + 'T' +
hours + ':' + minutes + ':' + seconds +
'.' + milli + 'Z"';
}
if ( o.constructor === Array ) {
var ret = [];
for ( var i = 0; i < o.length; i++ ) {
ret.push( $.toJSON( o[i] ) || 'null' );
}
return '[' + ret.join(',') + ']';
}
var name,
val,
pairs = [];
for ( var k in o ) {
type = typeof k;
if ( type === 'number' ) {
name = '"' + k + '"';
} else if (type === 'string') {
name = $.quoteString(k);
} else {
// Keys must be numerical or string. Skip others
continue;
}
type = typeof o[k];
if ( type === 'function' || type === 'undefined' ) {
// Invalid values like these return undefined
// from toJSON, however those object members
// shouldn't be included in the JSON string at all.
continue;
}
val = $.toJSON( o[k] );
pairs.push( name + ':' + val );
}
return '{' + pairs.join( ',' ) + '}';
}
};
/**
* jQuery.evalJSON
* Evaluates a given piece of json source.
*
* @param src {String}
*/
$.evalJSON = typeof JSON === 'object' && JSON.parse
? JSON.parse
: function( src ) {
return eval('(' + src + ')');
};
/**
* jQuery.secureEvalJSON
* Evals JSON in a way that is *more* secure.
*
* @param src {String}
*/
$.secureEvalJSON = typeof JSON === 'object' && JSON.parse
? JSON.parse
: function( src ) {
var filtered =
src
.replace( /\\["\\\/bfnrtu]/g, '@' )
.replace( /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace( /(?:^|:|,)(?:\s*\[)+/g, '');
if ( /^[\],:{}\s]*$/.test( filtered ) ) {
return eval( '(' + src + ')' );
} else {
throw new SyntaxError( 'Error parsing JSON, source is not valid.' );
}
};
/**
* jQuery.quoteString
* Returns a string-repr of a string, escaping quotes intelligently.
* Mostly a support function for toJSON.
* Examples:
* >>> jQuery.quoteString('apple')
* "apple"
*
* >>> jQuery.quoteString('"Where are we going?", she asked.')
* "\"Where are we going?\", she asked."
*/
$.quoteString = function( string ) {
if ( string.match( escapeable ) ) {
return '"' + string.replace( escapeable, function( a ) {
var c = meta[a];
if ( typeof c === 'string' ) {
return c;
}
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
})( jQuery );
/**
* 상품연동형 js - for 프론트
*/
;(function($) {
var $Olnk = {
iOlinkTotalPrice : 0, // 저장형 옵션의 가격
iAddOptionTotalPrice : 0, // 추가 구성상품의 가격
/**
* 최종가격 표시 핸들링 - 상품상세
*/
handleTotalPrice : function(sOptionStockData, iProductPrice, sDispNonePrice) {
var aStockData = $.parseJSON(sOptionStockData);
var iPrdPrice = SHOP_PRICE.toShopPrice(iProductPrice);
var iOptPrice = 0;
var iTotalPrice = 0;
var iCnt = 1;
var sQuantity = '('+sprintf(__('%s개'), iCnt)+')';
var sPrice = '';
// 운영방식설정 > 회원/비회원 가격표시 설정 반영
if (sDispNonePrice == 'T') {
iTotalPrice = 0;
} else {
$('select[id^="product_option_id"]').each(function() {
var iValNo = parseInt($(this).val());
if (isNaN(iValNo) === true) {
return;
}
iOptPrice += SHOP_PRICE.toShopPrice(aStockData[iValNo].stock_price);
});
iTotalPrice = iPrdPrice + iOptPrice;
}
this.iOlinkTotalPrice = iTotalPrice;
iTotalPrice = this.iAddOptionTotalPrice + iTotalPrice;
sPrice = SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
$('#totalProducts')
.find('.total')
.html('<strong><em>'+sPrice+'</em></strong> '+sQuantity+'</span>');
setTotalPriceRef(iTotalPrice, sQuantity);
},
/**
* 장바구니 담기시 필요한 파라미터 생성
*/
getSelectedItemForBasket : function(sProductCode, oTargets, iQuantity) {
var options = {};
oTargets.each(function() {
var optCode = $(this).attr('option_code');
var optValNo = parseInt($(this).val());
if (optCode == '' || optCode == null) {
return null;
}
if (isNaN(optValNo) === true) {
optValNo = '';
}
options[optCode] = optValNo;
});
return {
'product_code' : sProductCode,
'quantity' : iQuantity,
'options' : options
};
},
/**
* 관심상품 담기시 필요한 파라미터 생성
*/
getSelectedItemForWish : function(sProductCode, oTargets) {
var options = {};
var isReturn = true;
oTargets.each(function() {
if (isReturn === false) {
isReturn = false;
return;
}
var optCode = $(this).attr('option_code');
var optValNo = parseInt($(this).val());
//
// 필수입력값 체크
//
if (Boolean($(this).attr('required')) === true) {
if (isNaN(optValNo) === true) {
isReturn = false;
return;
}
}
if (optCode == '' || optCode == null) {
isReturn = false;
return;
}
if (isNaN(optValNo) === true) {
optValNo = '';
}
options[optCode] = optValNo;
});
if (isReturn === true) {
return {
'product_code' : sProductCode,
'options' : options
};
}
return false;
},
/**
* 선택된 품목정보 반환
* 상품연동형에서는 item_code 가 선택한 옵션을 뜻하지 않으므로
* 호환성을 위한 모조 값만 할당해준다.
*/
getMockItemInfo : function(aInfo) {
var aResult = {
'product_no' : aInfo.product_no,
'item_code' : aInfo.product_code + '000A',
'opt_id' : '000A',
'opt_str' : ''
};
return aResult;
},
/**
* 상품연동형 옵션인지 여부 반환
*/
isLinkageType : function(sOptionType) {
if (typeof sOptionType == 'string' && sOptionType == 'E') {
return true;
}
return false;
},
/**
* 상품상세(NewProductAction) 관련 js 스크립트를 보면, create_layer 라는 함수가 있다.
* 해당 함수는 ajax 콜을 해서 레이어 팝업으로 띄울 소스코드를 불러오게 되는데, 이때 스크립트 태그도 같이 따라온다.
* 해당 스크립트 태그에서 불러오는 js 파일내부에는 동일한 jquery 코드가 다시한번 오버라이딩이 되는데
* 이렇게 되면 기존에 물려있던 extension 메소드들은 초기화되어 날아가게 된다.
*
* 레이어 팝업이 뜨고 나서, $ 내에 존재해야할 메소드나 멤버변수들이 사라졌다면 이와 같은 현상때문이다.
* 가장 이상적인 처리는 스크립트 태그를 없애는게 가장 좋으나 호출되는 스크립트에 의존적인 코드가 존재하는것으로 보인다.
* 해당영역이 완전히 파악되기 전까진 필요한 부분에서만 예외적으로 동작할 수 있도록 한다.
*/
bugfixCreateLayerForWish : function() {
var __nil = jQuery.noConflict(true);
},
/**
* 장바구니 담기시 필요한 파라미터를 일부 조작
*/
hookParamForBasket : function(aParam, aInfo) {
if (aInfo.option_type != 'E') {
return aParam;
}
var aItemCode = this.getSelectedItemForBasket(aInfo.product_code, aInfo.targets, aInfo.quantity);
aParam['item_code_before'] = '';
aParam['option_type'] = 'E';
aParam['selected_item_by_etype[]'] = $.toJSON(aItemCode);
return aParam;
},
/**
* 관심상품 담기시 필요한 파라미터를 일부 조작
*/
hookParamForWish : function(aParam, aInfo) {
if (aInfo.option_type != 'E') {
return aParam;
}
var aItemCode = {};
//
// aInfo.targets 는 구스킨을 사용했을 때 출력되는 옵션 셀렉트 박스의 엘리먼트 객체인데,
// 현재 뉴스킨과 구스킨 구분을 아이디값이 wishlist_option_modify_layer_ 에 해당되는 노드가
// 있는지로 판별하기 때문에 모호함이 존재한다.
// 즉, 뉴스킨을 사용해도 해당 노드가 존재하지 않는 조건이 발생할 수 있기 때문이다.
// 예를 들면, 관심상품상에 담긴 리스트가 모두 옵션이 없는 상품만 있는 경우이거나 아니면
// 옵션이 존재하지만 아무것도 선택되지 않은 상품인 경우 발견이 되지 않을 수 있다.
// 그러므로 이런 경우엔 셀렉트박스를 통해 선택된 옵션을 파악하는 것이 아니라,
// 현재 할당되어 있는 데이터를 기준으로 파라미터를 세팅하도록 한다.
//
if (aInfo.targets.length > 0) {
aItemCode = this.getSelectedItemForBasket(aInfo.product_code, aInfo.targets, aInfo.quantity);
} else {
aItemCode = aInfo.selected_item_by_etype;
}
aParam.push('option_type=E');
aParam.push('selected_item_by_etype[]=' + $.toJSON(aItemCode));
return aParam;
}
};
//
// 공개 인터페이스
//
window['Olnk'] = $Olnk;
})($);
//수량 input id
var quantity_id = '#quantity';
var bRestockChange = false;
$(document).ready(function()
{
// ECHOSTING-90301 모바일 zoom.html 페이지에서 에러 - 예외처리
try { TotalAddSale.setParam('product_no', iProductNo); } catch (e) {}
$("select[id*='product_option_id']").each ( function () {
$(this).val('*');
});
// 디자인 마이그레이션 - 이걸 여기서 해야할까..
if ($('#NewProductQuantityDummy').length > 0 && $('#totalProducts').length > 0) {
$('#NewProductQuantityDummy').parents('tr').remove();
}
// 수량 초기화
$(quantity_id).val(product_min);
// 판매가 초기화
setPrice(true, false, '');
// 배송타입 초기화
if (delvtype == 'A') {
$('#delv_type_A').attr('checked','checked');
}
// 배송타입 선택
$('[id^="delv_type_"]').change(function()
{
delvtype = $(this).val();
// 해외배송이면 선결제 고정
if (delvtype == 'B') {
$('#delivery_cost_prepaid').val('P');
$('.delv_price_B').hide();
$('.delv_price_C').show();
} else {
$('.delv_price_B').show();
$('.delv_price_C').hide();
}
});
// 해외 배송 전용 상품은 hidden값 처리
if ($('[name="delv_type"]:hidden:not(:radio)').length > 0) {
delvtype = 'B';
}
// 옵션박스 수량 증감 버튼
$('.quantity_opt' + ',' + '.option_box_up' + ',' + '.option_box_down').live({
click: function() {
if ($(this).attr('class') != 'quantity_opt') {
setOptionBoxQuantity('click', this);
}
},
change: function() {
setOptionBoxQuantity('change', this);
}
});
// 옵션박스 선택상품 삭제
$('.option_box_del').live('click', function() {
// onlyone 옵션 셀렉트 박스 원복
var eSelectedItem = $('#'+$(this).attr('id').replace('_del','_id'));
$('option[value="'+eSelectedItem.val()+'"]').parent().removeAttr('is_selected');
$(this).parents('tr,li').eq(0).remove();
var sDelId = $(this).attr('id');
if (bPrdOptLayer == 'T' && parent.$('#opt_layer_window').css('display') == 'block') {
parent.$('option[value="'+eSelectedItem.val()+'"]').parent().removeAttr('is_selected');
parent.$('#'+sDelId+'').parents('tr,li').eq(0).remove();
}
if (typeof($('#opt_layer_window')) == 'object' && $('#opt_layer_window').length == 1) {
if ($('#opt_layer_window').css('display') == 'none') {
$("#productOptionIframe").contents().find('option[value="'+eSelectedItem.val()+'"]').parent().removeAttr('is_selected');
$("#productOptionIframe").contents().find('#'+sDelId+'').parents('tr,li').eq(0).remove();
}
}
if (typeof product_sale_price != 'undefined' && product_sale_price > 0) {
oProductList = TotalAddSale.getProductList();
// 옵션삭제후 재계산
delete oProductList[eSelectedItem.val()];
// 선택옵션없을시 ajax호출안함
if (jQuery.isEmptyObject(oProductList)) {
TotalAddSale.setParam('product', oProductList);
TotalAddSale.setTotalAddSalePrice(0);
setTotalData();
} else if ($(this).parents().find('.quantity > input').val() > 0) {
TotalAddSale.setParam('product', oProductList);
TotalAddSale.getCalculatorSalePrice(function(){
setTotalData();
});
}
} else {
setTotalData();
}
try {
if ($('#NaverChk_Button').length > 0) {
if ($('#NaverChk_Button').children().length < 1) {
return;
}
var iSoldOut = 0;
$('.option_box_id, .soldout_option_box_id').each(function() {
if ( checkSoldOut($(this).val()) === true ) {
iSoldOut++;
}
});
if (iSoldOut > 0) {
$('#NaverChk_Button').css('display', 'none');
} else {
$('#NaverChk_Button').css('display', 'block');
}
}
} catch (e) {}
});
// 수량 증감 버튼(옵션 없는 상품)
$('.QuantityUp' + ',' + '.QuantityDown' + ',' + quantity_id).live({
click: function() {
setQuantity('click', this);
},
change: function() {
setQuantity('change', this);
}
});
// qr코드 상품 url 복사
$('a.' + qrcode_class).unbind().click(function()
{
if (window.clipboardData.setData('Text',qrcode_url)) {
alert(__('코드URL 주소가 복사되었습니다\r\n붙여넣기(ctrl+v)하세요.'));
}
});
// 차등 배송비 사용시 ToolTip 열기
$('.btnTooltip > a').unbind().click(function() {
$('.btnTooltip > .differentialShipping').show();
});
// 차등 배송비 사용시 ToolTip 닫기
$('.btnTooltip > .differentialShipping a').unbind().click(function() {
$('.btnTooltip > .differentialShipping').hide();
});
// 차등 배송비 사용시 ToolTip 열기 (모바일)
$('.differentialShipping > .btnHelp').unbind().click(function() {
$('.differentialShipping > .layerShipping').show();
});
// 차등 배송비 사용시 ToolTip 닫기 (모바일)
$('.differentialShipping > .layerShipping > a').unbind().click(function() {
$('.differentialShipping > .layerShipping').hide();
});
// 추가입력옵션 글자 길이 체크
$('.input_addoption').live('keyup', function() {
var iLimit = $(this).attr('maxlength');
addOptionWord($(this).attr('id'), $(this).val(), iLimit);
});
$('ul.discountMember img').mouseover(function() {
$('ul.discountMember li > div.discount_layer').hide();
$('ul.discountMember li > span.arrow').hide();
if ($(this).parent().parent().has('div.discount_layer').length == 0) {
var sBenefitType = $(this).attr('benefit');
var oObj = $(this);
var oHtml = $('<div>');
oHtml.addClass('discount_layer');
//회원등급관리의 등급할인인 경우 class추가
if (sBenefitType == 'MG') {
oHtml.addClass('member_rating');
}
$(this).parent().parent().append(oHtml);
$.post('/exec/front/Product/Benefitinfo', 'benefit_type='+sBenefitType+'&product_no=' + iProductNo, function(sHtml) {
oHtml.html(sHtml);
});
if (mobileWeb === false) {
var oHtmlSpan = $('<span>');
oHtmlSpan.addClass('arrow');
oHtmlSpan.html('<img src="//img.echosting.cafe24.com/skin/base_ko_KR/product/ico_option_arrow.gif" alt="arrow"/>');
$(this).parent().parent().append(oHtmlSpan);
}
} else {
$(this).parent().parent().find('div.discount_layer').show();
$(this).parent().parent().find('span.arrow').show();
}
});
$('div.discount_layer .close').live('click', function() {
$(this).parent().hide();
$(this).parent().parent().find('span.arrow').hide();
return false;
});
// 구매옵션레이어
if (mobileWeb === true) {
try {
if ($('#fixedActionButton').size() > 0) {
if (bPrdOptLayer == '' && has_option == 'T') {
getPurchaseOptLayer(iProductNo);
}
}
} catch (e) {}
}
});
/**
* 모바일 상품옵션Layer 노출
* @param int iProductNo 상품번호
*/
function getPurchaseOptLayer(iProductNo)
{
$.ajax({
url : '/product/layer_option.html?product_no='+iProductNo,
success : function (data) {
if (data.indexOf('404 페이지 없음') == -1) {
try {
$('#opt_layer_window').remove();
} catch ( e ) {}
var sPrdOptUrl = "/product/layer_option.html?product_no="+iProductNo+"&bPrdOptLayer=T";
var aPrdOptLayerHtml = [];
aPrdOptLayerHtml.push('<div id="opt_layer_window" style="display:none">');
aPrdOptLayerHtml.push('<div id="opt_layer_background" style="position:absolute; top:0; left:0; width:100%; height:100%; background:#000; opacity:0.3; filter:alpha(opacity=30); z-index:9994;"></div>');
aPrdOptLayerHtml.push('<div id="opt_layer_iframe_parent" style="position:absolute; top:0; left:0; width:100%; z-index:9995;">');
aPrdOptLayerHtml.push('<iframe src="'+sPrdOptUrl+'" id="productOptionIframe" style="width:100%; height:100%; border:0;"></iframe>');
aPrdOptLayerHtml.push('<script>$(function(){$("#productOptionIframe").load(function(){$("#productOptionIframe").css("height", $("#productOptionIframe").contents().find("#product_detail_option_layer").height());});});');
aPrdOptLayerHtml.push('</script>');
aPrdOptLayerHtml.push('</div>');
aPrdOptLayerHtml.push('</div>');
$('body').append(aPrdOptLayerHtml.join(''));
}
}
});
}
// 모바일 상품옵션Layer 닫기
function closeBuyLayer()
{
var iTotalOptCnt = $('select[id^="' + product_option_id + '"]:visible').length;
$('select[id^="' + product_option_id + '"]:visible').each(function(i) {
var sSelectOptionId = $(this).attr('id');
var sParentVal = $(this).val();
parent.$('#'+sSelectOptionId+'').val(sParentVal);
if (i < iTotalOptCnt - 1) {
parent.$('#'+sSelectOptionId+'').trigger('change');
}
});
parent.$('html, body').css({'overflowY':'auto', height:'auto', width:'100%'});
parent.$('#opt_layer_window').hide();
}
/**
* 선택한 옵션 품절여부 체크
* @param sOptionId 옵션 id
* @returns 품절여부
*/
function checkSoldOut(sOptionId)
{
var aStockData = $.parseJSON(option_stock_data);
var bSoldOut = false;
// get_stock_info
if (aStockData[sOptionId] == undefined) {
iStockNumber = -1;
iOptionPrice = 0;
bStock = false;
sIsDisplay = 'T';
sIsSelling = 'T';
} else {
iStockNumber = aStockData[sOptionId].stock_number;
iOptionPrice = aStockData[sOptionId].option_price;
bStock = aStockData[sOptionId].use_stock;
sIsDisplay = aStockData[sOptionId].is_display;
sIsSelling = aStockData[sOptionId].is_selling;
}
if (sIsSelling == 'F' || ((iStockNumber < buy_unit || iStockNumber <= 0) && (bStock === true || sIsDisplay == 'F'))) {
bSoldOut = true;
}
return bSoldOut;
}
/**
* 옵션없는 구매수량 체크
* @param sEventType 이벤트 타입
* @param oObj Object정보
*/
function setQuantity(sEventType, oObj)
{
var iQuantity = parseInt($(quantity_id).val(),10);
var iBuyUnit = parseInt(buy_unit);
if (sEventType == 'click') {
var iProductCustom = $('#product_custom').val();
var sQuantityClass = '.' + oObj.className;
if (sQuantityClass.indexOf('.QuantityUp') >= 0) {
iQuantity = iQuantity + iBuyUnit;
} else if (sQuantityClass.indexOf('.QuantityDown') >= 0) {
iQuantity = iQuantity - iBuyUnit;
}
}
if (iQuantity > product_max && product_max > 0) {
alert(sprintf(__('최대 구매가능 수량은 %s개 입니다.'), product_max));
if (iBuyUnit == 1) {
$(quantity_id).val(product_max);
} else {
$(quantity_id).val($(quantity_id).val());
}
return;
}
if (iQuantity < product_min) {
alert(sprintf(__('최소 구매 수량은 %s개 이상입니다.'), product_min));
$(quantity_id).val(product_min);
return;
}
$(quantity_id).val(iQuantity);
setPrice(false, false, '');
// 총 주문금액/수량 처리
setTotalData();
// 구스킨인경우 판매금액 계산
if (isNewProductSkin() === false) {
setOldTotalPrice();
}
}
/**
* 옵션박스 구매수량 체크
* @param sEventType 이벤트별 수량 체크
* @param oObj Object정보
*/
function setOptionBoxQuantity(sEventType, oObj)
{
var sOptionId = '', sOptionBoxId = '', sProductPrice = '';
var iQuantity = 0;
var iBuyUnit = parseInt(buy_unit);
if (sEventType == 'click') {
// 구매수량 화살표로 선택
var sType = $(oObj).attr('id').indexOf('_up') > 0 ? '_up' : '_down';
sOptionBoxId = '#' + $(oObj).attr('id').substr(0, $(oObj).attr('id').indexOf(sType));
iQuantity = parseInt($(sOptionBoxId + '_quantity').val(), 10);
sOptionId = $(sOptionBoxId + '_id').val();
if (sType == '_up') {
iQuantity = iQuantity + iBuyUnit;
} else if (sType == '_down') {
iQuantity = iQuantity - iBuyUnit;
}
} else if (sEventType == 'change') {
// 구매수량 직접 입력
sOptionBoxId = '#' + $(oObj).attr('id').substr(0, $(oObj).attr('id').indexOf('_quantity'));
iQuantity = parseInt($(oObj).val(), 10);
sOptionId = $(sOptionBoxId + '_id').val();
}
var aStockData = $.parseJSON(option_stock_data);
var iStockNumber = parseInt(aStockData[sOptionId].stock_number);
var iOptionPrice = parseFloat(aStockData[sOptionId].option_price);
var bUseStock = aStockData[sOptionId].use_stock;
// 최대 재고 수량 체크
if (bUseStock === true && iQuantity > iStockNumber) {
alert(sprintf(__('재고 수량이 %s개 존재합니다. 재고수량 이하로 입력해주세요.'), iStockNumber));
$(oObj).val(iStockNumber);
return;
}
// 최소 구매 수량 체크
if (iQuantity < product_min) {
alert(sprintf(__('최소 구매수량은 %s개 이상입니다.'), product_min));
iQuantity = product_min;
$(oObj).val(iQuantity);
return;
}
if (iQuantity > product_max && product_max > 0) {
alert(sprintf(__('최대 구매가능 수량은 %s개 입니다.'), product_max));
iQuantity = product_max;
$(oObj).val(iQuantity);
return;
}
iProductPrice = getProductPrice(iQuantity, iOptionPrice, sOptionId, null, function(iProductPrice){
sProductPrice = SHOP_PRICE_FORMAT.toShopPrice(iProductPrice);
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sProductPrice = sNonmemberPrice;
iProductPrice = 0;
}
$(sOptionBoxId + '_quantity').val(iQuantity);
$(sOptionBoxId + '_price').find('span').html(sProductPrice);
$(sOptionBoxId + '_price').find('input').val(iProductPrice);
// 적립금 계산
if (typeof (mileage_val) != 'undefined') {
var mileage_price = set_mileage_value(iOptionPrice, iQuantity);
if (mobileWeb === true) {
$(sOptionBoxId + '_mileage').html(SHOP_PRICE_FORMAT.toShopPrice(mileage_price));
} else {
if (mileage_price > 0) {
$(sOptionBoxId + '_mileage').html(SHOP_PRICE_FORMAT.toShopPrice(mileage_price));
}
}
if (sIsDisplayNonmemberPrice == 'T') {
$(sOptionBoxId + '_mileage').html(sNonmemberPrice);
}
}
// 구매레이어
if (bPrdOptLayer == 'T' && parent.$('#opt_layer_window').css('display') == 'block') {
parent.$(sOptionBoxId + '_quantity').val(iQuantity);
parent.$(sOptionBoxId + '_price').find('span').html(sProductPrice);
parent.$(sOptionBoxId + '_price').find('input').val(iProductPrice);
if (typeof (mileage_val) != 'undefined') {
parent.$(sOptionBoxId + '_mileage').html(SHOP_PRICE_FORMAT.toShopPrice(mileage_price));
if (sIsDisplayNonmemberPrice == 'T') {
parent.$(sOptionBoxId + '_mileage').html(sNonmemberPrice);
}
}
}
if (typeof($('#opt_layer_window')) == 'object' && $('#opt_layer_window').length == 1) {
if ($('#opt_layer_window').css('display') == 'none') {
$("#productOptionIframe").contents().find(sOptionBoxId + '_quantity').val(iQuantity);
$("#productOptionIframe").contents().find(sOptionBoxId + '_price').find('span').html(sProductPrice);
$("#productOptionIframe").contents().find(sOptionBoxId + '_price').find('input').val(iProductPrice);
}
if (typeof (mileage_val) != 'undefined') {
$("#productOptionIframe").contents().find(sOptionBoxId + '_mileage').html(SHOP_PRICE_FORMAT.toShopPrice(mileage_price));
if (sIsDisplayNonmemberPrice == 'T') {
$("#productOptionIframe").contents().find(sOptionBoxId + '_mileage').html(sNonmemberPrice);
}
}
}
// 총 주문금액/수량 처리
setTotalData();
});
}
// 자바스크립트 number_format jsyoon
function number_format(str)
{
str += '';
var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
while (objRegExp.test(str)) {
str = str.replace(objRegExp,'$1,$2');
}
return str;
}
/**
* 가격계산 후 판매가에 반영
* @param bInit 초기값여부
* @param bOption 옵션선택여부
* @param sOptionId 단독구성형일때는 SelectBox가 여러개이므로 선택한 OptionId 필요
*/
function setPrice(bInit, bOption, sOptionId)
{
// 판매가 대체 문구시 가격 계산 안함
if (product_price_content == true) {
if (sIsDisplayNonmemberPrice == 'T') {
$('#totalProducts .total').html('<strong><em>'+sNonmemberPrice+'</em></strong> (0개)</span>');
}
return false;
}
// 옵션이 없는 경우 수량 초기화
if (has_option == 'F' && (isNaN($(quantity_id).val()) === true || $(quantity_id).val() == '' || $(quantity_id).val().indexOf('.') > 0)) {
$(quantity_id).val(product_min);
}
// 모바일 할인 적용 상품일 경우
if ( mobileWeb === true && isMobileDcStatus == 'F' ) {
// 모바일 할인이 적용 되지 않는 상품일 경우 가려준다.
try{ $('#span_product_price_mobile_p_line').hide(); $('#span_product_price_mobile_d_line').hide(); }catch(e){}
}
if (bInit === true) {
setProductPriceText();
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
if (sNonmemberPrice === "") {
sNonmemberPrice = "-";
}
$('#totalProducts .total').html('<strong><em>'+sNonmemberPrice+'</em></strong> (0개)</span>');
}
}
// 옵션이 없을 경우
if (has_option == 'F') {
setPriceHasOptionF();
} else if (has_option == 'T'){
if (typeof sOptionType != 'undefined' && Olnk.isLinkageType(sOptionType) === false) {
setPriceHasOptionT(bOption, sOptionId);
} else {
Olnk.handleTotalPrice(option_stock_data, product_price, sIsDisplayNonmemberPrice);
}
}
// 적립금 처리
setMileage(bInit);
}
/**
* 모바일 할인가 계산 후 리턴
*/
function getMobileDcPrice( iPrice ){
var iReturnMobileDcPrice = 0;
var iTmpBasePrice = 0;
var iPer = 0;
// 정율 할인일 경우
if ( sc_mobile_dc_value_flag == 'P') {
iPer = sc_mobile_dc_value * 0.01;
iTmpBasePrice = iPrice * iPer;
iTmpBasePrice = getMobileDcLimitPrice( iTmpBasePrice );
iReturnMobileDcPrice = Math.ceil( iPrice - iTmpBasePrice );
}
// 금액 할인일 경우
else{
iReturnMobileDcPrice = iPrice - sc_mobile_dc_value;
}
return iReturnMobileDcPrice;
}
/**
* 모바일 할인가 금액 절사 후 리턴
*
*/
function getMobileDcLimitPrice( MobileDcPrice ){
var iFloat = 0;
var iOpp = 0;
switch ( sc_mobile_dc_limit_value ) {
// 절사 안함
case "F" : return MobileDcPrice; break;
// 원단위 절사
case "O" :
iFloat = 0.1;
iOpp = 10;
break;
// 십원단위 절사
case "T" :
iFloat = 0.01;
iOpp = 100;
break;
// 백원단위 절사
case "M" :
iFloat = 0.001;
iOpp = 1000;
break;
}
MobileDcPrice = MobileDcPrice * iFloat;
// 반올림인지 내림인지
if ( sc_mobile_dc_limit_flag == 'L') { MobileDcPrice = Math.floor( MobileDcPrice ) * iOpp; }
else if ( sc_mobile_dc_limit_flag == 'U') { MobileDcPrice = Math.round(MobileDcPrice) * iOpp; }
return MobileDcPrice;
}
/**
* 적립금 계산 후 반영
*/
function setMileage(bInit)
{
var iMileageVal = 0;
var iProductMin = (buy_unit >= product_min ? buy_unit : product_min);
if (typeof (mileage_val) != 'undefined') {
iMileageVal = mileage_val;
}
if (bInit === true && mobileWeb === true) {
$('#span_mileage_text').html(SHOP_PRICE_FORMAT.toShopPrice(iMileageVal));
if (sIsDisplayNonmemberPrice == 'T') {
$('#span_mileage_text').html(sNonmemberPrice);
}
}
}
/**
* 싸이월드 스크랩 하기
* @param sMallId 몰아이디
* @param iPrdNo 상품번호
* @param iCateNo 카테번호
* @param iSid 승인번호
* @author 김성주 <sjkim@simplexi.com>
*/
function cyConnect(sMallId, iPrdNo, iCateNo, iSid)
{
var strUrl = "http://api.cyworld.com/openscrap/shopping/v1/?";
//strUrl += "xu=" + escape("http://www2.1300k.com/shop/makeGoodsXml/makeGoodsXml.php?f_goodsno="+prdNo+"&cate_no="+cate_no);
//strUrl += "&sid=s0200002";
strUrl += "xu=" + escape("http://"+sMallId+".cafe24.com/front/php/ghost_mall/makeCyworldPrdXml.php?product_no="+iPrdNo+"&cate_no="+iCateNo+"&sid="+iSid);
strUrl += "&sid="+iSid;
var strOption = "width=450,height=410";
var objWin = window.open(strUrl, 'cyopenscrap', strOption);
objWin.focus();
}
/**
* 싸이월드 스크랩 설명 보여주기
* @author 김성주 <sjkim@simplexi.com>
*/
function openNateInfo(num)
{
if (num == "1"){
document.getElementById('divNate').style.display="none";
}else{
document.getElementById('divNate').style.display="";
}
}
/**
* 판매가 표시설정
*/
function setProductPriceText()
{
var sString = SHOP_PRICE_FORMAT.toShopPrice(product_price);
if (typeof product_price_ref != 'undefined' && product_price_ref > 0) {
// 화폐 노출 순서 설정 ECHOSTING-56540
if (currency_disp_type == 'P') {
sString += ' ' + txt_product_price_ref;
} else {
sString = txt_product_price_ref + ' ' + sString;
}
}
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sString = sNonmemberPrice;
}
// ECHOSTING-67418 구상품일때도 판매가 영역이 바뀌게 처리 (초기화시 최소 구매수량 개수에 맞게 노출)
if (isNewProductSkin() === false && sIsDisplayNonmemberPrice !== 'T') {
iPrice = getProductPrice(product_min, product_price, null, null, function(iPrice) {
sString = SHOP_PRICE_FORMAT.toShopPrice(iPrice);
$('#span_product_price_text').html(sString);
});
} else {
$('#span_product_price_text').html(sString);
}
}
/**
* 전체 금액 리턴
* @returns {Number}
*/
function getTotalPrice()
{
var iTotalPrice = 0;
$('.option_box_price').each(function() {
iTotalPrice += parseInt($(this).val());
});
return iTotalPrice;
}
/**
* 금액설정(옵션이 없는 경우)
*/
function setPriceHasOptionF()
{
var iQuantity = 1;
try {
iQuantity = parseInt($(quantity_id).val().replace(/^[\s]+|[\s]+$/g,'').match(/[\d\-]+/),10);
}catch(e) {}
var iMaxCnt = 999999;
if (iQuantity > iMaxCnt) {
$(quantity_id).val(iMaxCnt);
iQuantity = iMaxCnt;
}
// 모바일 할인가 추가.
if ( typeof ( $('#span_product_price_mobile_text') ) != 'undefined' ) {
try{
var iPriceMobile = parseFloat(product_price_mobile,10);
}
catch(e){ var iPriceMobile = product_price; }
}
var iTotalPrice = getProductPrice(iQuantity, product_price, item_code, null, function(iTotalPrice){
var sTotalPrice = SHOP_PRICE_FORMAT.toShopPrice( iTotalPrice );
var sTotalSalePrice = sTotalPrice;
iTotalAddSalePrice = TotalAddSale.getTotalAddSalePrice();
if (typeof(iTotalAddSalePrice) != 'undefined' && iTotalAddSalePrice != 0) {
iTotalSalePrice = iTotalPrice - parseFloat(iTotalAddSalePrice, 10);
sTotalSalePrice = SHOP_PRICE_FORMAT.toShopPrice( iTotalSalePrice );
}
var sQuantityString = '('+sprintf(__('%s개'),iQuantity)+')';
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sTotalPrice = sNonmemberPrice;
sTotalSalePrice = sNonmemberPrice;
}
if (mobileWeb === true) {
$('#totalProducts .total').html('<strong class="price">'+sTotalSalePrice+' '+sQuantityString+'</strong>');
$('#quantity').html('<input type="hidden" name="option_box_price" class="option_box_price" value="'+iTotalPrice+'">');
} else {
$('#totalProducts .total').html('<strong><em>'+sTotalSalePrice+'</em></strong> '+sQuantityString+'</span>');
$('#totalProducts').find('.quantity_price').html(sTotalPrice + '<input type="hidden" name="option_box_price" class="option_box_price" value="'+iTotalPrice+'">');
if (typeof (mileage_val) != 'undefined') {
var mileage_price = mileage_val * iQuantity;
if (mileage_price > 0) {
if (sIsDisplayNonmemberPrice == 'T') {
$('#totalProducts').find('.mileage_price').html(sNonmemberPrice);
} else {
$('#totalProducts').find('.mileage_price').html(SHOP_PRICE_FORMAT.toShopPrice( mileage_price ));
}
}
}
}
setTotalPriceRef(iTotalPrice, sQuantityString);
try {
$('#spnViewPriceOrg').html(SHOP_PRICE_FORMAT.toShopPrice(_iPrdtPriceOrg*iQuantity));
} catch(e) {}
try {
$('#spnViewPriceTax').html(SHOP_PRICE_FORMAT.toShopPrice(_iPrdtPriceTax*iQuantity));
} catch(e) {}
});
}
/**
* 금액설정(옵션이 있는 경우)
* 복합/조합 - 단독/일체 구분없이 item_code만으로 처리하도록 변경
*/
function setPriceHasOptionT(bOption, sOptionId)
{
if (typeof(option_stock_data) == 'undefined') {
return;
}
if ( sIsDisplayNonmemberPrice === 'T') {
return;
}
if (bOption !== true) {
return;
}
var sSelectElementId = sOptionId;
var temp_product_option_id = product_option_id;
//뉴상품+구스킨 : 옵션추가버튼을 이용해 추가된 옵션 select box id 예외처리
if ( sOptionId.split('_')[0] == 'add') {
temp_product_option_id = sOptionId.split('_')[0]+'_'+sOptionId.split('_')[1]+'_'+temp_product_option_id;
}
var aStockData = $.parseJSON(option_stock_data);
// bItemSelected : 모든 셀렉트 박스가 선택됐는지 여부
var bItemSelected, bSoldOut = false;
var sOptionId, sOptionText = null;
var iPrice = 0;
// 조합구성 & 분리선택형
if (option_type == 'T' && item_listing_type == 'S') {
var aOption = new Array();
$('select[id^="' + temp_product_option_id + '"]:visible').each(function() {
var cVal = $(this).val();
if (cVal.indexOf('|') > -1) {
cVal = cVal.split('|')[0];
}
aOption.push(cVal);
});
var aOptionValue = new Array();
$.each(aOption, function(index, value) {
aOptionValue.push($('#' + temp_product_option_id+(index+1) + ' option[value="'+value+'"]').val());
});
// 아직 totalProduct에 Element추가가 안되서 getItemCode를 사용할 수 없다.
sOptionId = ITEM.getOldProductItemCode('[id^="'+temp_product_option_id+'"]');
sOptionValue = aOptionValue.join('/');
sOptionText = aOptionValue.join('#$%');
if (ITEM.isOptionSelected(aOption) === true) {
bItemSelected = true;
}
if (typeof(aStockData[sOptionId]) != 'undefined' && aStockData[sOptionId].stock_price != 0) {
sOptionText += '(' + getOptionPrice(aStockData[sOptionId].stock_price) + ')';
}
if (bItemSelected === true && sOptionId === false) {
alert(sprintf(__("선택하신 '%s' 옵션은 판매하지 않은 옵션입니다.\n다른 옵션을 선택해 주세요."),sOptionValue));
throw e;
return false;
}
} else {
var sElementId = sOptionId;
var oSelect = $('#'+sElementId);
if (oSelect.attr('is_selected') !== 'T') {
sOptionText = $('#' + sOptionId + ' option:selected').text();
sOptionId = $('#' + sOptionId + ' option:selected').val();
bItemSelected = true;
} else {
if (isNewProductSkin() === true && NEWPRD_OPTION.isOptionSelectTitleOrDivider(oSelect.val()) !== true) {
alert(__('이미 선택되어 있는 옵션입니다.'));
NEWPRD_OPTION.resetSelectElement(oSelect);
return false;
}
sOptionId = '*'
}
// 독립선택형 옵션별로 한개씩 선택시
if (typeof(is_onlyone) === 'string' && is_onlyone === 'T' && isNewProductSkin() === true) {
if (NEWPRD_OPTION.isOptionSelectTitleOrDivider(oSelect.val()) !== true) {
$('#'+sElementId).attr('is_selected','T');
}
}
if (ITEM.isOptionSelected(sOptionId) === false) {
bItemSelected = false;
}
}
// get_stock_info
if (aStockData[sOptionId] == undefined) {
iStockNumber = -1;
iOptionPrice = 0;
bStock = false;
sIsDisplay = 'T';
sIsSelling = 'T';
} else {
iStockNumber = aStockData[sOptionId].stock_number;
iOptionPrice = aStockData[sOptionId].option_price;
bStock = aStockData[sOptionId].use_stock;
sIsDisplay = aStockData[sOptionId].is_display;
sIsSelling = aStockData[sOptionId].is_selling;
}
if (sIsSelling == 'F' || ((iStockNumber < buy_unit || iStockNumber <= 0) && (bStock === true || sIsDisplay == 'F'))) {
//뉴상품+구스디 스킨 (옵션추가 버튼나오는 디자인 - 옵션선택시 재고체크)
if ($('#totalProducts').length <= 0) {
var aOptionName = new Array();
var aOptionText = new Array();
aOptionName = option_name_mapper.split('/');
aOptionText = sOptionText.split('#$%');
for ( var i = 0 ; i < aOptionName.length ; i++) {
aOptionText[i] = aOptionName[i]+':'+aOptionText[i];
}
option_text = aOptionText.join('\n');
alert(__('이 상품은 현재 재고가 부족하여 판매가 잠시 중단되고 있습니다.') + '\n\n' + __('제품명') + ' : ' + product_name + '\n\n' + __('재고없는 제품옵션') + ' : \n' + option_text);
$('select[id^="' + product_option_id + '"]').val('');
}
bSoldOut = true;
sOptionText = sOptionText.split('#$%').join('/').replace('['+__('품절')+']', '') + ' <span class="soldOut">['+__('품절')+']</span>';
} else {
sOptionText = sOptionText.split('#$%').join('/');
}
iPrice = getProductPrice(product_min, iOptionPrice, sOptionId, bSoldOut, function(iPrice){
// 옵션박스 호출
if (bItemSelected === true) {
// 구상품스킨일때는 옵션박스 호출안함
if (isNewProductSkin() === false) {
if (sIsDisplayNonmemberPrice == 'T') {
$('#span_product_price_text').html(sNonmemberPrice);
} else {
$('#span_product_price_text').html(SHOP_PRICE_FORMAT.toShopPrice(iPrice));
}
} else {
setOptionBox(sOptionId, sOptionText, iPrice, bSoldOut, sSelectElementId);
}
}
});
}
/**
* 옵션 사용가능 체크
*/
function checkOptionBox(sOptionId)
{
var bSelected = false;
// 이미 선택된 옵션은 아무 처리도 하지 않도록 처리한다.
$('.option_box_id').each(function(i) {
if ($(this).val() == sOptionId) {
bSelected = true;
}
});
$('.soldout_option_box_id').each(function(i) {
if ($(this).val() == sOptionId) {
bSelected = true;
}
});
return bSelected;
}
/*
* 옵션선택 박스 설정
* @todo totalproduct id를 컨트롤러로 밀어야함
*/
function setOptionBox(sOptionId, sOptionText, iPrice, bSoldOut, sSelectElementId)
{
var sReadonly = '';
var oSelect = $("#"+sSelectElementId);
// 필수 추가옵션 작성여부 검증
if (checkAddOption() !== true) {
NEWPRD_ADD_OPTION.resetSelectElement(oSelect);
// 독립선택형 옵션별로 한개씩 선택시
if (typeof(is_onlyone) === 'string' && is_onlyone === 'T' && isNewProductSkin() === true) {
oSelect.removeAttr('is_selected');
}
return false;
}
if (checkOptionBox(sOptionId) === true) {
alert(__('이미 선택되어 있는 옵션입니다.'));
NEWPRD_OPTION.resetSelectElement(oSelect);
return false;
}
if (parseInt(buy_unit) > 1) {
sReadonly = 'readonly';
}
var sStrPrice = SHOP_PRICE_FORMAT.toShopPrice(iPrice);
// 적립금 추가 필요
var iQuantity = (buy_unit >= product_min ? buy_unit : product_min);
var iMileageVal = 0;
var sMileageIcon = (typeof(mileage_icon) != 'undefined') ? mileage_icon : 'http://img.echosting.cafe24.com/design/common/icon_sett04.gif';
var sMileageAlt = (typeof(mileage_icon_alt) != 'undefined') ? mileage_icon_alt : '';
if (typeof (mileage_val) != 'undefined') {
iMileageVal = set_mileage_value(iPrice, iQuantity);
}
var sMileageVal = SHOP_PRICE_FORMAT.toShopPrice(iMileageVal);
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sStrPrice = sNonmemberPrice;
sMileageVal = sNonmemberPrice;
}
var sProductName = product_name;
if (sProductName != null) {
sProductName = product_name.replace(/\\"/g, '"');
}
var aAddOption = NEWPRD_ADD_OPTION.getCurrentAddOption();
var sAddOptionTitle = NEWPRD_ADD_OPTION.getCurrentAddOptionTitle(aAddOption);
if (mobileWeb === true) {
var sOptionBoxId = 'option_box' + parseInt($('#totalProducts > table > tbody > tr').length);
var sTableRow = '<tr class="option_product"><td>';
sOptionText = '<p class="product"><strong>' + sProductName + '</strong><br /> - <span>' + sAddOptionTitle + sOptionText + '</span></p>';
if (bSoldOut === true) {
try {
if ($('#NaverChk_Button').length > 0 && $('#NaverChk_Button').children().length > 0) {
$('#NaverChk_Button').css('display', 'none');
}
} catch(e) {}
sTableRow += '<input type="hidden" class="soldout_option_box_id" id="'+sOptionBoxId+'_id" value="'+sOptionId+'">'+sOptionText;
sTableRow += '<p><input type="number" readonly value="0"/> ';
sTableRow += '<a href="#none"><img width="30" height="27" src="http://img.echosting.cafe24.com/mobileWeb/common/btn_quantity_up.png" class="up"/></a> &nbsp;';
sTableRow += '<a href="#none"><img width="30" height="27" src="http://img.echosting.cafe24.com/mobileWeb/common/btn_quantity_down.png" class="down"/></a></span></p></td>';
sTableRow += '<td><strong class="price">'+sStrPrice+'</strong></td>';
sTableRow += '<td><a href="#none"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_price_delete.gif" alt="삭제" id="'+sOptionBoxId+'_del" class="option_box_del" /></a></td>';
} else {
sTableRow += '<input type="hidden" class="option_box_id" id="'+sOptionBoxId+'_id" value="'+sOptionId+'" name="item_code[]" data-item-add-option="'+escape(aAddOption.join(NEWPRD_OPTION.DELIMITER_SEMICOLON))+'">'+sOptionText;
sTableRow += '<p><input type="number" id="'+sOptionBoxId+'_quantity" name="quantity_opt[]" autocomplete="off" class="quantity_opt" '+sReadonly+' value="'+iQuantity+'"/> ';
sTableRow += '<a href="#none"><img width="30" height="27" src="http://img.echosting.cafe24.com/mobileWeb/common/btn_quantity_up.png" id="'+sOptionBoxId+'_up" class="up option_box_up" alt="up" /></a> &nbsp;';
sTableRow += '<a href="#none"><img width="30" height="27" src="http://img.echosting.cafe24.com/mobileWeb/common/btn_quantity_down.png" id="'+sOptionBoxId+'_down" class="down option_box_down" alt="down" /></a></p></td>';
sTableRow += '<td><strong id="'+sOptionBoxId+'_price" class="price"><input type="hidden" class="option_box_price" value="'+iPrice+'"><span>'+sStrPrice+'</span></strong>';
if (parseInt(iMileageVal) > 0) {
sTableRow += '<span class="mileage">(<img src="'+sMileageIcon+'" alt="'+sMileageAlt+'" /> <span id="'+sOptionBoxId+'_mileage">'+sMileageVal+'</span>)</span>';
}
sTableRow += '</td>';
sTableRow += '<td><a href="#none" class="delete"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_price_delete.gif" alt="삭제" id="'+sOptionBoxId+'_del" class="option_box_del" /></a></td>';
}
sTableRow += '</tr>';
if (bPrdOptLayer == 'T' && parent.$('#opt_layer_window').css('display') == 'block') {
parent.$('#totalProducts > table > tbody:last').append(sTableRow);
}
if (typeof($('#opt_layer_window')) == 'object' && $('#opt_layer_window').length == 1) {
if ($('#opt_layer_window').css('display') == 'none') {
$("#productOptionIframe").contents().find('#totalProducts > table > tbody:last').append(sTableRow);
}
}
} else {
var sOptionBoxId = 'option_box' + parseInt($('#totalProducts > table > tbody > tr').length);
var sTableRow = '<tr class="option_product">';
sOptionText = '<p class="product">' + sProductName + '<br /> - <span>' + sAddOptionTitle + sOptionText + '</span></p>';
if (bSoldOut === true) {
try {
if ($('#NaverChk_Button').length > 0 && $('#NaverChk_Button').children().length > 0) {
$('#NaverChk_Button').css('display', 'none');
}
} catch(e) {}
sTableRow += '<td><input type="hidden" class="soldout_option_box_id" id="'+sOptionBoxId+'_id" value="'+sOptionId+'">'+sOptionText+'</td>';
sTableRow += '<td><span class="quantity" style="width:65px;"><input type="text" '+sReadonly+' value="0"/><a href="#none"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_count_up.gif" class="up" alt="수량증가" /></a><a href="#none"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_count_down.gif" class="down" alt="수량감소" /></a></span>';
sTableRow += '<a href="#none" class="delete"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_price_delete.gif" alt="삭제" id="'+sOptionBoxId+'_del" class="option_box_del" /></a></td>';
sTableRow += '<td class="right"><span id="'+sOptionBoxId+'_price"><span>'+sStrPrice+'</span></span>';
} else {
sTableRow += '<td><input type="hidden" class="option_box_id" id="'+sOptionBoxId+'_id" value="'+sOptionId+'" name="item_code[]" data-item-add-option="'+escape(aAddOption.join(NEWPRD_OPTION.DELIMITER_SEMICOLON))+'">'+sOptionText+'</td>';
sTableRow += '<td><span class="quantity" style="width:65px;"><input type="text" id="'+sOptionBoxId+'_quantity" name="quantity_opt[]" class="quantity_opt" '+sReadonly+' value="'+iQuantity+'"/><a href="#none"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_count_up.gif" id="'+sOptionBoxId+'_up" class="up option_box_up" alt="수량증가" /></a><a href="#none"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_count_down.gif" id="'+sOptionBoxId+'_down" class="down option_box_down" alt="수량감소" /></a></span>';
sTableRow += '<a href="#none" class="delete"><img src="http://img.echosting.cafe24.com/design/skin/default/product/btn_price_delete.gif" alt="삭제" id="'+sOptionBoxId+'_del" class="option_box_del" /></a></td>';
sTableRow += '<td class="right"><span id="'+sOptionBoxId+'_price"><input type="hidden" class="option_box_price" value="'+iPrice+'"><span>'+sStrPrice+'</span></span>';
}
if (typeof (iMileageVal) != 'undefined' && parseInt(iMileageVal) > 0 && sIsMileageDisplay === 'T') {
sTableRow += '<span class="mileage">(<img src="'+sMileageIcon+'" alt="'+sMileageAlt+'" /> <span id="'+sOptionBoxId+'_mileage" class="mileage_price">'+sMileageVal+'</span>)</span>';
}
sTableRow += '</td></tr>';
}
if (0 == $('#totalProducts > table > tbody.option_products').length) {
$('#totalProducts > table > tbody:last').addClass("option_products").after($('<tbody class="add_products"/>'));
}
$('#totalProducts > table > tbody.option_products').append(sTableRow);
// 총 주문금액/수량 처리
setTotalData();
}
/**
* 총 상품금액/수량 적용
*/
function setTotalData()
{
var iTotalCount = 0;
$('input[name="quantity_opt[]"]').each(function() {
iTotalCount += parseInt($(this).val())
});
var iTotalPrice = 0;
$('.option_box_price, .option_add_box_price').each(function() {
iTotalPrice += parseFloat($(this).val());
});
iTotalAddSalePrice = TotalAddSale.getTotalAddSalePrice();
if (typeof(iTotalAddSalePrice) != 'undefined' && iTotalAddSalePrice != 0) {
iTotalPrice -= parseFloat(iTotalAddSalePrice, 10);
}
var sQuantityString = '('+sprintf(__('%s개'),iTotalCount)+')';
var sStrPrice = SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sStrPrice = sNonmemberPrice;
}
if (mobileWeb === true) {
$('#totalProducts .total').html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
if (bPrdOptLayer == 'T' && parent.$('#opt_layer_window').css('display') == 'block') {
parent.$('#totalProducts .total').html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
}
if (typeof($('#opt_layer_window')) == 'object' && $('#opt_layer_window').length == 1) {
if ($('#opt_layer_window').css('display') == 'none') {
$("#productOptionIframe").contents().find('#totalProducts .total').html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
}
}
} else {
$('#totalProducts .total').html('<strong><em>'+sStrPrice+'</em></strong> '+sQuantityString+'</span>');
}
setTotalPriceRef(iTotalPrice, sQuantityString);
}
/**
* 총 상품금액에 참조화폐 추가
* @param iTotalPrice
* @param sQuantityString
*/
function setTotalPriceRef(iTotalPrice, sQuantityString)
{
var sPrePrice = '';
var sPostPrice = '';
var sTotalPrice = SHOP_PRICE_FORMAT.toShopPrice( iTotalPrice );
var sTotalPriceRef = SHOP_PRICE_FORMAT.shopPriceToSubPrice(iTotalPrice);
if (sTotalPriceRef == '') {
return;
}
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
sTotalPrice = sNonmemberPrice;
sTotalPriceRef = sNonmemberPrice;
}
if (mobileWeb === true) {
if (currency_disp_type == 'P') {
$('#totalProducts .total').find('strong').append(' / ' + sTotalPriceRef);
} else {
$('#totalProducts .total').html('<strong class="price">'+ sTotalPriceRef +' '+sQuantityString + '</strong> / ' + sTotalPrice);
}
if (bPrdOptLayer == 'T' && parent.$('#opt_layer_window').css('display') == 'block') {
parent.$('#totalProducts .total').find('strong').append(' / ' + sTotalPriceRef);
}
if (typeof($('#opt_layer_window')) == 'object' && $('#opt_layer_window').length == 1) {
if ($('#opt_layer_window').css('display') == 'none') {
$("#productOptionIframe").contents().find('#totalProducts .total').find('strong').append(' / ' + sTotalPriceRef);
}
}
} else {
if (currency_disp_type == 'P') {
$('#totalProducts .total').append(' / ' + sTotalPriceRef);
} else {
$('#totalProducts .total').html('<strong><em>' + sTotalPriceRef + '</em></strong> ' + sQuantityString + '</span> / ' + sTotalPrice);
}
}
}
/**
* 상품금액 계산 (모바일 및 할인판매가 체크)
* @param iQuantity 수량
* @param iQuantity 가격
* @param sItemCode 옵션코드
* @param bSoldout 품절여부
* @param fCallback 콜백함수
*/
function getProductPrice(iQuantity, iOptionPrice, sItemCode, bSoldOut, fCallback)
{
var fProductPrice = SHOP_PRICE.toShopPrice(product_price);
if (typeof(iQuantity) == 'undefined' || iQuantity == 0) {
iQuantity = 1;
}
if (mobileWeb === true) {
// 모바일
try {
fProductPrice = SHOP_PRICE.toShopPrice(product_price_mobile);
} catch (e) {};
} else {
fProductPrice = iOptionPrice * parseInt(iQuantity, 10);
}
oProductList = TotalAddSale.getProductList();
// 할인판매가
if (bSoldOut !== true && (typeof product_sale_price != 'undefined' && product_sale_price > 0 && sItemCode != 'undefined' && sItemCode != '' && sItemCode != '*' && sItemCode != '**')) {
// 옵션이 있는 경우에는 iOptionPrice가 판매가로 들어가 있어서
// 할인된 금액이 처리되지 않지만 옵션이 없는 경우 이쪽으로 판매가가 할인 판매가로 설정되어버림
// 상품 상세페이지내에서는 할인 판매가로 컨트롤 없음
//fProductPrice = SHOP_PRICE.toShopPrice(product_sale_price);
// 품절시 ajax호출안함
TotalAddSale.setQuantity(sItemCode, iQuantity);
TotalAddSale.setParam('product', oProductList);
TotalAddSale.getCalculatorSalePrice(fCallback, iOptionPrice * parseInt(iQuantity, 10));
} else {
if (bSoldOut) {
TotalAddSale.setQuantity(sItemCode, 0);
TotalAddSale.setParam('product', oProductList);
}
fCallback(fProductPrice);
}
return fProductPrice;
}
/**
* 추가입력옵션 길이 체크
* @param oObj
* @param limit
*/
function addOptionWord(sId, sVal, iLimit)
{
// 영문,한글 상관없이 iLimit 글자만큼 제한하도록 수정 (ECHOSTING-78226)
//var iStrLen = stringByteSize(sVal);
var iStrLen = sVal.length;
if (iStrLen > iLimit) {
alert(sprintf(__('메시지는 %s자 이하로 입력해주세요.'), iLimit));
$('#'+sId).val(sVal.substr(0, sVal.length-1));
return;
}
$('#'+sId).parent().parent().find('.length').html(iStrLen);
}
/**
* 문자열을 UTF-8로 변환했을 경우 차지하게 되는 byte 수를 리턴한다.
*/
function stringByteSize(str)
{
if (str == null || str.length == 0) return 0;
var size = 0;
for (var i = 0; i < str.length; i++) {
size += charByteSize(str.charAt(i));
}
return size;
}
/**
* 글자수 체크
* @param ch
* @returns {Number}
*/
function charByteSize(ch)
{
if ( ch == null || ch.length == 0 ) return 0;
var charCode = ch.charCodeAt(0);
if ( escape(charCode).length > 4 ) {
return 2;
} else {
return 1;
}
}
/**
* 적립금 금액 계산
* @param iProductPrice 판매가
* @param iQuantity 개수
* @returns mileage_value 적립금
*/
function set_mileage_value(iProductPrice, iQuantity)
{
var iMileagePrice = mileage_val * iQuantity;
if (typeof(mileage_data) != 'undefined') {
var oMileageData = $.parseJSON(mileage_data);
if (oMileageData == null) {
return iMileagePrice;
}
// 정액일경우 별도처리 후 리턴
if (oMileageData.type == 'W') {
return parseInt(oMileageData.percent) * iQuantity;
}
// 적립금 기준 (판매가 + 옵션가)
if (typeof(mileage_save_type) != 'undefined' && mileage_save_type == 'O') {
var fMileage = (iProductPrice * oMileageData.percent/100) / (oMileageData.set_mileage * 10);
if (oMileageData.set_type == 'A') {
iMileagePrice = Math.floor(fMileage) * (oMileageData.set_mileage * 10);
} else if (oMileageData.set_type == 'B') {
var iDigit = 1;
if (oMileageData.digit == -2) {
iDigit = 2;
} else if (oMileageData.digit == -3) {
iDigit = 3;
} else if (oMileageData.digit == -4) {
iDigit = 4;
}
iMileagePrice = +(Math.round((iProductPrice * oMileageData.percent/100)+"e-"+iDigit) + "e+"+iDigit);
} else {
iMileagePrice = Math.ceil(fMileage) * (oMileageData.set_mileage*10);
}
iMileagePrice = iMileagePrice * iQuantity;
}
}
return iMileagePrice;
}
/**
* 기존의 SHOP_PRICE_FORMAT.toShopPrice() 의 래핑 함수
* @param fPrice 옵션 추가 금액
* @returns String 옵션 추가 금액(금액이 0보다 클경우 '+' 태그 추가)
*/
function getOptionPrice(fPrice)
{
var sPricePlusTag = '';
if (fPrice > 0) {
sPricePlusTag = '+';
}
var aFormat = SHOP_CURRENCY_FORMAT.getShopCurrencyFormat();
var sPrice = SHOP_PRICE.toShopPrice(fPrice, true);
return aFormat.head + sPricePlusTag + sPrice + aFormat.tail;
}
var SELECTEDITEM = {
iSequence : 0,
sElementIdPrefix : 'option_box',
getElementId : function()
{
return this.sElementIdPrefix+this.getSequence();
},
getSequence : function()
{
return this.iSequence++;
}
};
/**
* SNS 링크 정보
* @param sMedia
* @param iProductNo
*/
function SnsLinkAction(sMedia, iProductNo)
{
window.open(sSocialUrl + '?product_no=' + iProductNo + '&type=' + sMedia,sMedia);
}
/**
* 상품 상세 페이지 이동
* @param iProductNo 상품번호
* @param iCategoryNo 카테고리 번호
* @param iDisplayGroup 진열그룹
* @param sLink URL정보
*/
function product_detail(iProductNo, iCategoryNo, iDisplayGroup, sLink)
{
var sLink = sLink ? sLink : '/product/detail.html';
sLink += '?product_no=' + iProductNo + '&cate_no=' + iCategoryNo + '&display_group=' + iDisplayGroup;
try {
opener.location.href = sLink;
} catch (e) {
location.href = sLink;
}
self.close();
}
/**
* 추천메일보내기
* @param product_no 상품번호
* @param category_no 카테고리번호
* @param display_group 진열그룹
*/
function recommend_mail_pop(product_no, category_no, display_group)
{
option = "'toolbar=no," + "location=no," + "directories=no," + "status=no," + "menubar=no," + "scrollbars=yes," + "resizable=yes," + "width=576," + "height=568," + "top=300," + "left=200"
filename = "/product/recommend_mail.html?product_no=" + product_no + "&category_no=" + category_no;
filename += "&display_group=" + display_group
window.open(filename,"recommend_mail_pop",option);
}
/**
* 상품조르기 팝업 호출
* @param product_no 상품번호
*/
function request_pop(product_no)
{
option = "'toolbar=no," + "location=no," + "directories=no," + "status=no," + "menubar=no," + "scrollbars=yes," + "resizable=yes," + "width=576," + "height=568," + "top=300," + "left=200"
filename = "/product/request.html?product_no[]=" + product_no;
window.open(filename,"request_pop",option);
}
//페이지의 상위
function findMainFrame () {
var $oFrame = null;
if (opener) {
$oFrame = opener;
} else {
var $oParent = window;
var $aFrames = [];
while ($oParent != $oParent.parent) {
$aFrames.unshift($oParent = $oParent.parent);
}
try {
$oParent.location.href;
} catch(e) {
$aFrames.shift();
}
if (0 < $aFrames.length) {
if ($aFrames[0].location.pathname === "/") {
if ($aFrames.length === 1) {
$oFrame = $aFrames[0];
} else
if ($aFrames.length > 1) {
$oFrame = $aFrames.pop();
}
} else {
$oFrame = $aFrames[0];
}
}
}
return $oFrame;
}
// 상품 옵션 id
var product_option_id = 'product_option_id';
// 추가옵션 id
var add_option_id = 'add_option_';
// 선택된 상품만 주문하기
var sIsPrdOverride = 'F';
//모바일로 접속했는지
var bIsMobile = false;
/**
* sType - 1:바로구매, 2:장바구니,naver_checkout:네이버체크아웃 form.submit - 바로구매, 장바구니, 관심상품
* TODO 바로구매 - 장바구니에 넣으면서 주문한 상품 하나만 주문하기
*
* @param string sAction action url
*/
function product_submit(sType, sAction, oObj)
{
// ECHOSTING-58174
if (sIsDisplayNonmemberPrice == 'T') {
switch (sType) {
case 1 :
alert(__('로그인후 상품을 구매해주세요.'));
break;
case 2 :
alert(__('로그인후 장바구니 담기를 해주세요.'));
break
default :
break;
}
btn_action_move_url('/member/login.html');
return false;
}
var sBasketType;
var bIsPriceConentType = checkPriceType();
if (bIsPriceConentType == false) {
alert(sprintf(__('%s 상품은 구매할 수 있는 상품이 아닙니다.'), product_name));
return;
}
if (typeof (basket_type) == 'undefined') {
sBasketType = 'A0000';
} else {
sBasketType = basket_type;
}
// 품절 여부 체크
if (checkSoldout() == false) return;
// 옵션 체크
if (sType != 'sms_restock') {
if (checkOptionRequired() == false) {
var sBuyBtnParent = $(oObj).parent().parent().attr('id');
try {
if (mobileWeb) {
if (sBuyBtnParent != '' && sBuyBtnParent == 'fixedActionButton') {
$('select[id^="' + product_option_id + '"]:visible').each(function() {
var sSelectOptionId = $(this).attr('id');
var sParentVal = $(this).val();
$("#productOptionIframe")[0].contentWindow.$('#product_detail_option_layer #'+sSelectOptionId+'').val(sParentVal).trigger('change');
});
var iTop = parseInt(( $(window).height() - $("#productOptionIframe").height() ) / 2);
$("#opt_layer_iframe_parent").css({"top": iTop, "left": 0});
$('html, body').css({'overflow-y': 'hidden', width: '100%', height: '100%'});
$('#opt_layer_window').show();
return;
}
}
} catch (e) {}
alert(__('필수 옵션을 선택해주세요.'));
return;
}
}
// 추가 옵션 체크 (품목기반 추가옵션일때는 폼제출때 검증 불필요)
if (NEWPRD_ADD_OPTION.isItemBasedAddOptionType() !== true && checkAddOption() === false) {
return false;
}
// 파일첨부 옵션 유효성 체크
if (FileOptionManager.checkValidation() === false) return;
// 수량 체크
var iQuantity = 0;
if (sType != 'sms_restock') {
iQuantity = checkQuantity();
if (iQuantity == false) return;
}
// 폼 세팅
if (iQuantity == undefined || isNaN(iQuantity) === true) {
iQuantity = 1;
}
// basket_type - 컨트롤러에서 변수에 assign 한 값을 그대로 사용하자
var frm = $('#frm_image_zoom');
// 어떤 이유로 서밋이 되지 않았을때 폼이 남아있는 경우에 폼 이하의 내용을 삭제함
frm.find(":hidden").remove();
frm.attr('method', 'POST');
frm.attr('action', '/' + sAction);
frm.append(getInputHidden('product_no', iProductNo));
frm.append(getInputHidden('product_name', product_name));
frm.append(getInputHidden('main_cate_no', iCategoryNo));
frm.append(getInputHidden('display_group', iDisplayGroup));
frm.append(getInputHidden('option_type', option_type));
frm.append(getInputHidden('product_price', product_price));
frm.append(getInputHidden('product_min', product_min));
frm.append(getInputHidden('command', 'add'));
frm.append(getInputHidden('has_option', has_option));
frm.append(getInputHidden('basket_type', sBasketType));
// frm.append(getInputHidden('product_name',product_name)); // 혹시 몰라서 빼봄.
frm.append(getInputHidden('multi_option_schema', $('#multi_option').html()));
frm.append(getInputHidden('multi_option_data', ''));
frm.append(getInputHidden('quantity', iQuantity));
frm.append(getInputHidden('delvType', delvtype));
frm.append(getInputHidden('redirect', sType));
frm.append(getInputHidden('prd_detail_ship_type', $('#delivery_cost_prepaid').val()));
// 최대주문수량
try {
frm.append(getInputHidden('product_max_type', product_max_type));
frm.append(getInputHidden('product_max', product_max));
} catch (e) {}
var count = 1;
var sOptionParam = '';
// 필수값 체크를 여기서 하지 않을수 있다.
// 추이를 지켜보고 제거
$('select[id^="' + product_option_id + '"]:visible').each(function()
{
frm.append(getInputHidden('optionids[]', $(this).attr('name')));
if ($(this).attr('required') == true || $(this).attr('required') == 'required') {
frm.append(getInputHidden('needed[]', $(this).attr('name')));
}
var iSelectedIndex = $(this).get(0).selectedIndex;
if ($(this).attr('required') && iSelectedIndex > 0) iSelectedIndex -= 1;
if (iSelectedIndex > 0) {
sOptionParam += '&option' + count + '=' + iSelectedIndex;
var sValue = $(this).val();
var aValue = sValue.split("|");
frm.append(getInputHidden($(this).attr('name'), aValue[0]));
++count;
}
});
// 추가옵션
if (add_option_name) {
var iAddOptionNo = 0;
var aAddOptionName = new Array();
for ( var i in add_option_name) {
if ($('#' + add_option_id + i).val() == '' || typeof($('#' + add_option_id + i).val()) == 'undefined') {
continue;
}
frm.append(getInputHidden('option_add[]', $('#' + add_option_id + i).val()));
aAddOptionName[iAddOptionNo++] = add_option_name[i];
}
frm.append(getInputHidden('add_option_name', aAddOptionName.join(';')));
}
// 옵션 추가 구매 체크
if (duplicateOptionCheck() === false) return;
// 관련상품이 있을 때
var bReturn = true;
$('input[name="basket_info[]"]:checked').each(function()
{
var iRelationProductNum = $(this).val().substr(0, $(this).val().indexOf('|'));
var eQuantity = $('#quantity_' + iRelationProductNum);
var eOption = $('select[name="option_' + iRelationProductNum + '[]"]');
var aValue = $(this).val().split('|');
var sIsSetProduct = aValue[7];
if (sIsSetProduct == 'T') {
if (sType == '1') {
alert(__('관련상품이 세트상품인 경우, 함께 구매할 수 없습니다.'));
} else if (sType == '2') {
alert(__('관련상품이 세트상품인 경우, 함께 장바구니에 담을 수 없습니다.'));
}
bReturn = false;
return false;
}
if (eQuantity.attr('item_code')) {
// 단품인가
frm.append(getInputHidden('relation_item[]', eQuantity.val()+'||'+eQuantity.attr('item_code')));
} else {
// 품목이 있는가
bReturn = true;
// 조합/분리 형의 경우 value_mapper가 있어야한다. 있으면 가서 쓰고 없어서 undefined가 뜨면 catch를 실행 - 억지코드임.
try {
var aOptionMapper = $.parseJSON(eval('sOptionValueMapper'+iRelationProductNum));
var aOptionValue = new Array();
eOption.each(function() {
if ($(this).is('[required="true"]') === true && ($(this).val() == '*' || $(this).val() == '**')) {
alert(__('필수 옵션을 선택해주세요.'));
$(this).focus();
bReturn = false;
return false;
} else {
aOptionValue.push($(this).val());
}
});
sOptionValue = aOptionValue.join('#$%');
var sItemCode = aOptionMapper[sOptionValue];
} catch(e) {
eOption.each(function() {
if ($(this).is('[required="true"]') === true && ($(this).val() == '*' || $(this).val() == '**')) {
alert(__('필수 옵션을 선택해주세요.'));
$(this).focus();
bReturn = false;
return false;
}
});
var sItemCode = eOption.val();
}
if (bReturn === true) {
if (Olnk.isLinkageType(eQuantity.attr('option_type')) === false) {
frm.append(getInputHidden('relation_item[]', eQuantity.val()+'||'+sItemCode));
} else {
var _sProductCode = eQuantity.attr('product_code');
var _iQuantity = eQuantity.val();
var _sItemCode = _sProductCode + '000A';
var _aItemValueNo = Olnk.getSelectedItemForBasket(_sProductCode, eOption, _iQuantity);
frm.append(getInputHidden('relation_item[]', _iQuantity+'||'+_sItemCode));
frm.append(getInputHidden('relation_item_by_etype[]', $.toJSON(_aItemValueNo)));
}
} else {
return false;
}
}
});
if ($('input[name="basket_info[]"]:checked').length >= 0) {
frm.append(getInputHidden('relation_product', 'yes'));
}
if (bReturn === false) return false;
// 추가입력옵션 체크
var bReturn = true;
$('input[class^="option_add_box_"][name="basket_add_product[]"]').each(function()
{
var sAddOptionId = $(this).attr('id').replace('_id','');
var iAddProductNo = parseInt($(this).attr('class').substr($(this).attr('class').lastIndexOf('_')+1));
$('select[name^="addproduct_option_name_'+iAddProductNo+'"][required="true"]:visible').each(function() {
if ($(this).val() == '*' || $(this).val() == '**') {
alert(__('필수 옵션을 선택해주세요.'));
$(this).focus();
bReturn = false;
return false;
}
});
if (bReturn === false) return false;
frm.append(getInputHidden('selected_add_item[]', $('#'+sAddOptionId+'_quantity').val()+'||'+$(this).val()));
$bResult = checkAddOption('addproduct_add_option_id_'+iAddProductNo);
if (bReturn === false) return false;
});
if ($('.add-product-checked:checked').size() > 0) {
var aAddProduct = $.parseJSON(add_option_data);
var aItemCode = new Array();
var bCheckValidate = true;
$('.add-product-checked:checked').each(function() {
if (bCheckValidate === false) {
return false;
}
var iProductNum = $(this).attr('product-no');
var iQuantity = $('#add-product-quantity-'+iProductNum).val();
var aData = aAddProduct[iProductNum];
if (aData.item_code === undefined) {
if (aData.option_type === 'T') {
if (aData.item_listing_type === 'S') {
var aOptionValue = new Array();
$('[id^="addproduct_option_id_'+iProductNum+'"]').each(function() {
aOptionValue.push($(this).val());
});
if (ITEM.isOptionSelected(aOptionValue) === true) {
sOptionValue = aOptionValue.join('#$%');
aItemCode.push([$.parseJSON(aData.option_value_mapper)[sOptionValue],iQuantity]);
} else {
bCheckValidate = false;
alert(__('필수 옵션을 선택해주세요.'));
return false;
}
} else {
var $eItemSelectbox = $('[name="addproduct_option_name_'+iProductNum+'"]');
if (ITEM.isOptionSelected($eItemSelectbox.val()) === true) {
aItemCode.push([$eItemSelectbox.val(),iQuantity]);
} else {
bCheckValidate = false;
$eItemSelectbox.focus();
alert(__('필수 옵션을 선택해주세요.'));
return false;
}
}
} else {
$('[id^="addproduct_option_id_'+iProductNum+'"]').each(function() {
if ($(this).attr('required') == true && ITEM.isOptionSelected($(this).val()) === false) {
bCheckValidate = false;
$(this).focus();
alert(__('필수 옵션을 선택해주세요.'));
return false;
}
if (ITEM.isOptionSelected($(this).val()) === true) {
aItemCode.push([$(this).val(),iQuantity]);
}
});
}
} else {
aItemCode.push([aData.item_code,iQuantity]);
}
});
if (bCheckValidate === true) {
for (var x = 0 ; x < aItemCode.length ; x++) {
frm.append(getInputHidden('relation_item[]', aItemCode[x][1]+'||'+aItemCode[x][0]));
}
} else {
bReturn = false;
}
}
if (bReturn === false) return false;
// 옵션 추가 구매 - 구상품 스킨에만 존재하는 내용
if ($('.EC_MultipleOption').size() > 0) {
// 원래 하던일은 여기서 하도록 두고(중복체크 같은 부분)
var aMultipleOption = EC_MultipleOption.getMultipleOption();
if (aMultipleOption == -1) return false;
for ( var x = 0 ; x < aMultipleOption.length ; x++) {
var iQuantity = EC_MultipleOption.getMultipleOption()[x].split('|')[7];
var mItemCode = ITEM.getOldProductItemCode('.EC_MultipleOption:eq('+x+') [name^="option"]');
var aItemCode = [];
if (typeof mItemCode === 'string') {
aItemCode.push(mItemCode);
} else {
aItemCode = mItemCode;
}
for (var i = 0 ; i < aItemCode.length ; i++) {
var sItemCode = aItemCode[i];
frm.append(getInputHidden('selected_item[]', iQuantity+'||'+sItemCode));
}
}
// 사용자 지정 옵션
if ($('.' + $.data(document, 'multiple_option_input_class')).size() > 0) {
frm.append(getInputHidden('user_option_name_' + iProductNo, add_option_name.join(',@,')));
var bReturn = true;
var aAddOption = new Array();
$('.' + $.data(document, 'multiple_option_input_class')).each(function()
{
if ($(this).val() == '') {
alert(__('추가 옵션을 입력해주세요.'));
$(this).focus();
bReturn = false;
return false;
} else {
aAddOption.push($(this).val());
}
});
frm.append(getInputHidden('user_option_' + iProductNo, aAddOption.join(',@,')));
}
if (bReturn === false) return false;
}
// 선택한상품만 주문하기
if (sType == 1 || sType == 'naver_checkout') {
var aItemParams = [];
var aItemCode = ITEM.getItemCode();
for (var i = 0, length = aItemCode.length; i < length; i++) {
aItemParams.push("item_code[]=" + aItemCode[i]);
}
sOptionParam = sOptionParam + '&delvtype=' + delvtype + '&' + aItemParams.join("&");
if (sType == 'naver_checkout') { //ECHOSTING-62146
frm.append(getInputHidden('quantity_override_flag', 'T'));
} else {
var sSelectedItemByEtype = '';
if (Olnk.isLinkageType(sOptionType)) {
sSelectedItemByEtype = $.toJSON(Olnk.getSelectedItemForBasket(sProductCode, $('[id^="product_option_id"]'), $('#quantity').val()));
}
selectbuy_action(sOptionParam, iProductNo, sSelectedItemByEtype);
frm.append(getInputHidden('quantity_override_flag', sIsPrdOverride));
}
}
if (typeof ACEWrap != 'undefined') {
ACEWrap.addBasket();
}
// 뉴상품 옵션 선택 구매
if (has_option == 'T') {
if (Olnk.isLinkageType(sOptionType) === false) {
if (isNewProductSkin() === true) {
if ($('[name="quantity_opt[]"][id^="option_box"]').length > 0 && $('[name="quantity_opt[]"][id^="option_box"]').length == $('[name="item_code[]"]').length) {
//품목별 추가옵션 이름 셋팅
NEWPRD_ADD_OPTION.setItemAddOptionName(frm);
$('[name="quantity_opt[]"][id^="option_box"]').each(function(i) {
var oItem = $('[name="item_code[]"]:eq('+i+')');
var sItemCode = oItem.val();
frm.prepend(getInputHidden('selected_item[]', $(this).val()+'||'+sItemCode));
//품목별 추가옵션 셋팅
var sItemAddOption = unescape(oItem.attr('data-item-add-option'));
NEWPRD_ADD_OPTION.setItemAddOption(sItemCode, sItemAddOption, frm);
});
}
} else {
// 뉴 상품 + 구스디 스킨
var aItemCode = ITEM.getItemCode();
for (var i = 0 ; i < aItemCode.length ; i++) {
frm.prepend(getInputHidden('selected_item[]', getQuantity()+'||'+aItemCode[i]));
}
}
} else {
var _sItemCode = sProductCode + '000A';
var _iQuantity = $('#quantity').val();
// 연동형이거나 수량이 없는 경우에는 최소 구매 수량으로 던진다!!
if ( _iQuantity != 'undefined' && Olnk.isLinkageType(sOptionType) === true ) {
_iQuantity = product_min;
}
var _aItemValueNo = Olnk.getSelectedItemForBasket(sProductCode, $('[id^="product_option_id"]'), _iQuantity);
frm.prepend(getInputHidden('selected_item[]', _iQuantity+'||'+_sItemCode));
frm.prepend(getInputHidden('selected_item_by_etype[]', $.toJSON(_aItemValueNo)));
}
} else {
if (item_code === undefined) {
var sItemCode = product_code+'000A';
} else {
var sItemCode = item_code;
}
if (sType != 'sms_restock') {
frm.prepend(getInputHidden('selected_item[]', $(quantity_id).val()+'||'+sItemCode));
}
}
// 파일첨부 옵션의 파일업로드가 없을 경우 바로 장바구니에 넣기
if (FileOptionManager.existsFileUpload() === false) {
action_basket(sType, 'detail', sAction, frm.serialize(), sBasketType);
// 파일첨부 옵션의 파일업로드가 있으면
} else{
FileOptionManager.upload(function(mResult){
// 파일업로드 실패
if (mResult===false) return false;
// 파일업로드 성공
for (var sId in mResult) {
frm.append(getInputHidden(sId, FileOptionManager.encode(mResult[sId])));
}
action_basket(sType, 'detail', sAction, frm.serialize(), sBasketType);
});
}
}
/*
* 판매가 대체 문구 상품 체크
*/
function checkPriceType ()
{
if (typeof product_price_content == 'undefined') {
return true;
}
var sProductcontent = product_price_content.replace(/\s/g, '').toString();
if (sProductcontent === '1') {
return false;
}
return true;
}
/**
* 품절 상품 체크
*/
function checkSoldout()
{
// 품절 품목만 추가된 경우
if ($('.option_box_id').length == 0 && $('.soldout_option_box_id').length > 0) {
alert(__('품절된 상품은 구매가 불가능합니다.'));
return false;
}
return true;
}
/**
* 선택한상품만 주문하기
*
* @param string sOptionParam 옵션 파람값
* @param int iProductNo 상품번호
* @param string sSelectedItemByEtype 상품연동형의 경우 입력되는 선택된옵션 json 데이터
*/
function selectbuy_action(sOptionParam, iProductNo, sSelectedItemByEtype)
{
var sAddParam = '';
if (typeof sSelectedItemByEtype != 'undefined' && sSelectedItemByEtype != '') {
sAddParam = '&selected_item_by_etype=' + sSelectedItemByEtype;
}
var sUrl = '/exec/front/order/basket/?command=select_prdcnt&product_no=' + iProductNo + '&option_type=' + (window['option_type'] || '') + sOptionParam + sAddParam;
$.ajax(
{
url : sUrl,
dataType : 'json',
async : false,
success : function(data)
{
if (data.result > 0 && !confirm(sprintf(__('동일상품이 장바구니에 %s개 있습니다.'), data.result) +'\n'+ __('함께 구매하시겠습니까?'))) {
sIsPrdOverride = 'T';
}
}
});
}
/**
* 장바구니 담기(카테고리)
*
* @param int iProductNo 상품번호
* @param int iCategoryNo 카테고리 번호
* @param int iDisplayGroup display_group
* @param string sBasketType 무이자 설정(A0000:일반, A0001:무이자)
* @param string iQuantity 주문수량
* @param string sItemCode 아이템코드
* @param string sDelvType 배송타입
*/
function category_add_basket(iProductNo, iCategoryNo, iDisplayGroup, sBasketType, bList, iQuantity, sItemCode, sDelvType, sProductMaxType, sProductMax)
{
if (iQuantity == undefined) {
iQuantity = 1;
}
if (bList == true) {
try {
if ($.type(EC_ListAction) == 'object') {
EC_ListAction.getOptionSelect(iProductNo, iCategoryNo, iDisplayGroup, sBasketType);
}
} catch (e) {
alert(__('장바구니에 담을 수 없습니다.'));
return false;
}
} else {
var sAction = '/exec/front/order/basket/';
var sData = 'command=add&quantity=' + iQuantity + '&product_no=' + iProductNo + '&main_cate_no=' + iCategoryNo + '&display_group='
+ iDisplayGroup + '&basket_type=' + sBasketType + '&delvtype=' + sDelvType + '&product_max_type=' + sProductMaxType + '&product_max=' + sProductMax;
// 장바구니 위시리스트인지 여부
if (typeof (basket_page_flag) != 'undefined' && basket_page_flag == 'T') {
sData = sData + '&basket_page_flag=' + basket_page_flag;
}
// 뉴상품 옵션 선택 구매
sData = sData + '&selected_item[]='+iQuantity+'||' + sItemCode + '000A';
action_basket(2, 'category', sAction, sData, sBasketType);
}
}
/**
* 구매하기
*
* @param int iProductNo 상품번호
* @param int iCategoryNo 카테고리 번호
* @param int iDisplayGroup display_group
* @param string sBasketType 무이자 설정(A0000:일반, A0001:무이자)
* @param string iQuantity 주문수량
*/
function add_order(iProductNo, iCategoryNo, iDisplayGroup, sBasketType, iQuantity)
{
if (iQuantity == undefined) {
iQuantity = 1;
}
var sAction = '/exec/front/order/basket/';
var sData = 'command=add&quantity=' + iQuantity + '&product_no=' + iProductNo + '&main_cate_no=' + iCategoryNo + '&display_group='
+ iDisplayGroup + '&basket_type=' + sBasketType;
action_basket(1, 'wishlist', sAction, sData, sBasketType);
}
/**
* 레이어 생성
*
* @param layerId
* @param sHtml
*/
function create_layer(layerId, sHtml, bBuyLayer)
{
if (bBuyLayer == true) {
parent.$('body').append($('<div id="' + layerId + '"></div>'));
parent.$('#' + layerId).html(sHtml);
parent.$('#' + layerId).show();
} else {
$('<div id="' + layerId + '"></div>').appendTo('body');
$('#' + layerId).html(sHtml);
$('#' + layerId).show();
}
// set delvtype to basket
try {
$(".xans-product-basketadd").find("a[href='/order/basket.html']").attr("href", "/order/basket.html?delvtype=" + delvtype);
} catch (e) {}
try {
$(".xans-order-layerbasket").find("a[href='/order/basket.html']").attr("href", "/order/basket.html?delvtype=" + delvtype);
} catch (e) {}
}
/**
* 레이어 위치 조정
*
* @param layerId
*/
function position_layer(layerId)
{
var obj = $('#' + layerId);
var x = 0;
var y = 0;
try {
var hWd = parseInt(document.body.clientWidth / 2 + $(window).scrollLeft());
var hHt = parseInt(document.body.clientHeight / 2 + $(window).scrollTop() / 2);
var hBW = parseInt(obj.width()) / 2;
var hBH = parseInt(hHt - $(window).scrollTop());
x = hWd - hBW;
if (x < 0) x = 0;
y = hHt - hBH;
if (y < 0) y = 0;
} catch (e) {}
obj.css(
{
position : 'absolute',
display : 'block',
top : y + "px",
left : x + "px"
});
}
// 장바구니 담기 처리중인지 체크 - (ECHOSTING-85853, 2013.05.21 by wcchoi)
var bIsRunningAddBasket = false;
/**
* 장바구니/구매 호출
*
* @param sType
* @param sGroup
* @param sAction
* @param sParam
* @param aBasketType
* @param bNonDuplicateChk
*/
function action_basket(sType, sGroup, sAction, sParam, sBasketType, bNonDuplicateChk)
{
// 장바구니 담기에 대해서만 처리
// 중복 체크 안함 이 true가 아닐경우(false나 null)에만 중복체크
if (sType == 2 && bNonDuplicateChk != true) {
if (bIsRunningAddBasket) {
alert(__('처리중입니다. 잠시만 기다려주세요.'));
return;
} else {
bIsRunningAddBasket = true;
}
}
if (sType == 'sms_restock') {
action_sms_restock(sParam);
return ;
}
$.post(sAction, sParam, function(data)
{
basket_result_action(sType, sGroup, data, sBasketType);
bIsRunningAddBasket = false; // 장바구니 담기 처리 완료
}, 'json');
// 관신상품 > 전체상품 주문 ==> 장바구니에 들어가기도 전에 /exec/front/order/order/ 호출하게 되어 오류남
// async : false - by wcchoi
// 다시 async모드로 원복하기로 함 - ECQAINT-7857
/*
$.ajax({
type: "POST",
url: sAction,
data: sParam,
async: false,
success: function(data) {
basket_result_action(sType, sGroup, data, sBasketType);
bIsRunningAddBasket = false; // 장바구니 담기 처리 완료
},
dataType: 'json'
});
*/
}
/**
* 리스트나 상세에서 장바구니 이후의 액션을 처리하고 싶을 경우 이변수를 파라미터로 지정해줌
*/
var sProductLink = null;
/**
* 장바구니 결과 처리
*
* @param sType
* @param sGroup
* @param aData
* @param aBasketType
*/
function basket_result_action(sType, sGroup, aData, sBasketType)
{
var sHtml = '';
var bOpener = false;
var oOpener = findMainFrame();
var sLocation = location;
var bBuyLayer = false;
if (aData == null) return;
if (aData.result >= 0) {
try {
if (oOpener != null && typeof (oOpener) != 'undefined' && oOpener.location.hostname == self.location.hostname) {
if (oOpener.location.pathname.indexOf('coupon_product_list') < 0 && oOpener.location.pathname.indexOf('admin') < 0) {
bOpener = true;
}
}
} catch (e) {}
try {
if (mobileWeb == true && parent.$('#opt_layer_window').length > 0 && typeof(window.parent) == 'object') {
parent.$('html, body').css('overflowY', 'auto');
parent.$('#opt_layer_window').hide();
sLocation = parent.location;
bBuyLayer = true;
}
} catch (e) {}
// 네이버 체크아웃
if (sType == 'naver_checkout') {
var sUrl = '/exec/front/order/navercheckout';
// inflow param from naver common JS to Checkout Service
try {
if (typeof(wcs) == 'object') {
var inflowParam = wcs.getMileageInfo();
if (inflowParam != false) {
sUrl = sUrl + '?naver_inflow_param=' + inflowParam;
}
}
} catch (e) {}
if (is_order_page == 'N' && bIsMobile == false) {
window.open(sUrl);
return false;
} else {
sLocation.href = sUrl;
return false;
}
}
// 배송유형
var sDelvType = '';
if (typeof(delvtype) != 'undefined') {
if (typeof(delvtype) == 'object') {
sDelvType = $(delvtype).val();
} else {
sDelvType = delvtype;
}
} else if (aData.sDelvType != null) {
sDelvType = aData.sDelvType;
}
if (sType == 1) { // 바로구매하기
if (aData.isLogin == 'T') { // 회원
if (bOpener) {
oOpener.location.href = "/order/orderform.html?basket_type=" + sBasketType + "&delvtype=" + sDelvType;
} else {
sLocation.href = "/order/orderform.html?basket_type=" + sBasketType + "&delvtype=" + sDelvType;
}
} else { // 비회원
sUrl = '/member/login.html?noMember=1&returnUrl=' + encodeURIComponent('/order/orderform.html?basket_type=' + sBasketType + "&delvtype=" + sDelvType);
sUrl += '&delvtype=' + sDelvType;
if (bOpener) {
oOpener.location.href = sUrl;
} else {
sLocation.href = sUrl;
// parent.location.href = sUrl;
}
}
} else { // 장바구니담기
if (sGroup == 'detail') {
if (mobileWeb === true) {
if (typeof (basket_page_flag) != 'undefined' && basket_page_flag == 'T') {
sLocation.reload();
return;
}
} else {
if (bOpener) {
oOpener.location.href = "/order/basket.html" + "?delvtype=" + sDelvType;
}
}
var oSearch = /basket.html/g;
if (typeof(aData.isDisplayBasket) != "undefined" && aData.isDisplayBasket == 'T' && oSearch.test(window.location.pathname) == false) {
if ((typeof(aData.isDisplayLayerBasket) != "undefined" && aData.isDisplayLayerBasket == 'T') && (typeof(aData.isBasketPopup) != "undefined" && aData.isBasketPopup == 'T')) {
if (!bOpener) layer_basket2(sDelvType);
} else {
layer_basket(sDelvType, bBuyLayer);
}
} else {
sLocation.href = "/order/basket.html?" + "&delvtype=" + sDelvType;
}
} else {
// from으로 위시리스트에서 요청한건지 판단.
var bIsFromWishlist = false;
if (typeof(aData.from) != "undefined" && aData.from == "wishlist") {
bIsFromWishlist = true;
}
// 장바구니 위시리스트인지 여부
if (typeof (basket_page_flag) != 'undefined' && basket_page_flag == 'T' || bIsFromWishlist == true) {
sLocation.reload();
return;
}
if ((typeof(aData.isDisplayLayerBasket) != "undefined" && aData.isDisplayLayerBasket == 'T') && (typeof(aData.isBasketPopup) != "undefined" && aData.isBasketPopup == 'T')) {
layer_basket2(sDelvType);
} else {
layer_basket(sDelvType, bBuyLayer);
}
}
}
} else {
var msg = aData.alertMSG.replace('\\n', '\n');
try {
msg = decodeURIComponent(decodeURIComponent(msg));
} catch (err) {}
alert(msg);
if (aData.result == -111) {
if (sProductLink !== null) {
sLocation.href = '/product/detail.html?' + sProductLink;
}
}
if (aData.result == -101) {
sUrl = '/member/login.html?noMember=1&returnUrl=' + encodeURIComponent(location.href);
if (bOpener) {
oOpener.location.href = sUrl;
} else {
sLocation.href = sUrl;
}
}
}
if (bOpener === true && opener) {
self.close();
}
}
function layer_basket(sDelvType, bBuyLayer)
{
$('.xans-product-basketoption').remove();
$.get('/product/add_basket.html?delvtype='+sDelvType,'', function(sHtml)
{
create_layer('confirmLayer', sHtml, bBuyLayer);
});
}
function layer_basket2(sDelvType)
{
$('.xans-order-layerbasket').remove();
$.get('/product/add_basket2.html?delvtype=' + sDelvType + '&layerbasket=T', '', function(sHtml)
{
create_layer('confirmLayer', sHtml, false);
});
}
function layer_wishlist(bBuyLayer)
{
$('.layerWish').remove();
$.get('/product/layer_wish.html','' ,function(sHtml)
{
create_layer('confirmLayer', sHtml, bBuyLayer);
//Olnk.bugfixCreateLayerForWish();
});
}
function go_basket()
{
var oOpener = findMainFrame();
if (oOpener !== null && typeof (oOpener) != 'object') {
location.href = '/order/basket.html';
} else {
oOpener.location.href = '/order/basket.html';
if (opener !== null) {
self.close();
}
}
}
function move_basket_page()
{
var sLocation = location;
try {
if (mobileWeb == true && parent.$('#opt_layer_window').length > 0 && typeof(window.parent) == 'object') {
parent.$('html, body').css('overflowY', 'auto');
parent.$('#opt_layer_window').hide();
sLocation = parent.location;
}
} catch (e) {}
sLocation.href = '/order/basket.html';
}
/**
* 이미지 확대보기 (상품상세 버튼)
*/
function go_detail()
{
var sUrl = '/product/detail.html?product_no=' + iProductNo;
var oOpener = findMainFrame();
if (typeof(iCategoryNo) != 'undefined') {
sUrl += '&cate_no='+iCategoryNo;
}
if (typeof(iDisplayGroup) != 'undefined') {
sUrl += '&display_group='+iDisplayGroup;
}
if (oOpener !== null && typeof (oOpener) != 'object') {
location.href = sUrl;
} else {
oOpener.location.href = sUrl;
if (opener !== null) {
self.close();
}
}
}
/**
* 바로구매하기/장바구니담기 Action - 로그인하지 않았을 경우
*/
function check_action_nologin()
{
alert(__('회원만 구매 가능합니다. 비회원인 경우 회원가입 후 이용하여 주세요.'));
var bOpener = false;
var oOpener = findMainFrame();
var sLocation = location;
try {
if (oOpener != null && typeof (oOpener) != 'undefined' && oOpener.location.hostname == self.location.hostname) {
bOpener = true;
}
} catch (e) {}
try {
if (mobileWeb == true && parent.$('#opt_layer_window').length > 0 && typeof(window.parent) == 'object') {
parent.$('html, body').css('overflowY', 'auto');
parent.$('#opt_layer_window').hide();
sLocation = parent.location;
}
} catch (e) {}
sUrl = '/member/login.html?noMember=1&returnUrl=' + encodeURIComponent(location.href);
if (bOpener) {
oOpener.location.href = sUrl;
} else {
sLocation.href = sUrl;
}
}
/**
* 바로구매하기 Action - 불량회원 구매제한
*/
function check_action_block(sMsg)
{
if (sMsg == '' ) {
sMsg = __('쇼핑몰 관리자가 구매 제한을 설정하여 구매하실 수 없습니다.');
}
alert(sMsg);
}
/**
* 관심상품 등록 - 로그인하지 않았을 경우
*/
function add_wishlist_nologin(sUrl)
{
alert(__('로그인 후 관심상품 등록을 해주세요.'));
btn_action_move_url(sUrl);
}
/**
* 바로구매하기 / 장바구니 담기 / 관심상품 등록 시 url 이동에 사용하는 메소드
* @param sUrl 이동할 주소
*/
function btn_action_move_url(sUrl)
{
var bOpener = false;
var oOpener = findMainFrame();
var sLocation = location;
try {
if (oOpener != null && typeof (oOpener) != 'undefined' && oOpener.location.hostname == self.location.hostname) {
bOpener = true;
}
} catch (e) {}
try {
if (mobileWeb == true && parent.$('#opt_layer_window').length > 0 && typeof(window.parent) == 'object') {
parent.$('html, body').css('overflowY', 'auto');
parent.$('#opt_layer_window').hide();
sLocation = parent.location;
}
} catch (e) {}
sUrl += '?return_url=' + encodeURIComponent('http://' + location.hostname + location.pathname + location.search);
if (bOpener === false) {
sLocation.replace(sUrl);
} else {
oOpener.location.replace(sUrl);
}
}
/**
* return_url 없이 url 이동에 사용하는 메소드
* @param sUrl 이동할 주소
*/
function btn_action_move_no_return_url(sUrl)
{
var bOpener = false;
var oOpener = findMainFrame();
try {
if (oOpener != null && typeof (oOpener) != 'undefined' && oOpener.location.hostname == self.location.hostname) {
bOpener = true;
}
} catch (e) {}
if (bOpener === false) {
location.replace(sUrl);
} else {
oOpener.location.replace(sUrl);
}
}
/**
* 관심상품 등록 - 파라미터 생성
*/
function add_wishlist(sMode)
{
var sUrl = 'http://' + location.hostname;
sUrl += '/exec/front/Product/Wishlist/';
var param = location.search.substring(location.search.indexOf('?') + 1);
sParam = param + '&command=add';
sParam += '&referer=' + encodeURIComponent('http://' + location.hostname + location.pathname + location.search);
add_wishlist_action(sUrl, sParam, sMode);
}
var bWishlistSave = false;
function add_wishlist_action(sAction, sParam, sMode)
{
if (bWishlistSave === true) {
alert('관심상품 등록중입니다.');
return false;
}
var required_msg = __('품목을 선택해 주세요.');
var aItemCode = ITEM.getWishItemCode();
if (Olnk.isLinkageType(sOptionType) === true) {
aItemCode = Olnk.getSelectedItemForWish(sProductCode, $('[id^="product_option_id"]:visible'));
required_msg = __('필수 옵션을 선택해주세요.');
}
if (aItemCode === false) {
var sBuyBtnParent = $(sMode).parent().parent().attr('id');
try {
if (mobileWeb == true) {
if (sBuyBtnParent != '' && sBuyBtnParent == 'fixedActionButton') {
$('select[id^="' + product_option_id + '"]:visible').each(function() {
var sSelectOptionId = $(this).attr('id');
var sParentVal = $(this).val();
$("#productOptionIframe")[0].contentWindow.$('#product_detail_option_layer #'+sSelectOptionId+'').val(sParentVal).trigger('change');
});
var iTop = parseInt(( $(window).height() - $("#productOptionIframe").height() ) / 2);
$("#opt_layer_iframe_parent").css({"top": iTop, "left": 0});
$('html, body').css({'overflow-y': 'hidden', width: '100%', height: '100%'});
$('#opt_layer_window').show();
return;
}
}
} catch (e) {}
alert(required_msg);
return false;
}
if (aItemCode !== null) {
var sItemCode = '';
var aTemp = [];
for (var x in aItemCode) {
try {
var opt_id = aItemCode[x].substr(aItemCode[x].length-4, aItemCode[x].length);
aTemp.push('selected_item[]='+opt_id);
}catch(e) {}
}
if (Olnk.isLinkageType(sOptionType) === true) {
sParam = sParam + '&' + 'selected_item[]=000A&selected_item_by_etype[]=' + $.toJSON(aItemCode);
} else {
sParam = sParam + '&' + aTemp.join('&');
}
}
sParam = sParam + '&product_no='+iProductNo;
// 추가 옵션 체크 (품목기반 추가옵션일때는 폼제출때 검증 불필요)
if (NEWPRD_ADD_OPTION.isItemBasedAddOptionType() !== true && checkAddOption() === false) {
return false;
}
// 추가옵션
var aAddOptionStr = new Array();
var aAddOptionRow = new Array();
if (add_option_name) {
for (var i=0;i<add_option_name.length;i++) {
if (add_option_name[i] != '') {
aAddOptionRow.push(add_option_name[i] + '*' + $('#' + add_option_id + i).val());
}
}
}
aAddOptionStr.push(aAddOptionRow);
sParam += '&add_option=' + encodeURIComponent(aAddOptionStr.join('|'));
// 파일첨부 옵션 유효성 체크
if (FileOptionManager.checkValidation() === false) return;
bWishlistSave = true;
// 파일첨부 옵션의 파일업로드가 없을 경우 바로 관심상품 넣기
if (FileOptionManager.existsFileUpload() === false) {
add_wishlist_request(sParam, sMode);
// 파일첨부 옵션의 파일업로드가 있으면
} else{
FileOptionManager.upload(function(mResult){
// 파일업로드 실패
if (mResult===false) {
bWishlistSave = false;
return false;
}
// 파일업로드 성공
for (var sId in mResult) {
sParam += '&'+sId+'='+FileOptionManager.encode(mResult[sId]);
}
add_wishlist_request(sParam, sMode);
});
}
}
function add_wishlist_request(sParam, sMode)
{
var sUrl = '/exec/front/Product/Wishlist/';
$.post(
sUrl,
sParam,
function(data) {
if (sMode != 'back') {
add_wishlist_result(data);
}
bWishlistSave = false;
},
'json');
}
function add_wishlist_result(aData)
{
var bBuyLayer = false;
var bOpener = true;
var oOpener = findMainFrame();
var agent = navigator.userAgent.toLowerCase();
if (aData == null) return;
if (aData.result == 'SUCCESS') {
if (agent.indexOf('iphone') != -1 || agent.indexOf('android') != -1) {
try {
if (parent.$('#opt_layer_window').length > 0 && typeof(window.parent) == 'object') {
parent.$('html, body').css('overflowY', 'auto');
parent.$('#opt_layer_window').hide();
bBuyLayer = true;
}
} catch (e) {}
}
try {
if (oOpener != null && typeof (oOpener) != 'undefined' && oOpener.location.hostname == self.location.hostname) {
bOpener = false;
}
} catch (e) {}
if (aData.confirm == 'T' && bOpener === true) {
layer_wishlist(bBuyLayer);
return;
}
alert(__('관심상품으로 등록되었습니다.'))
} else if (aData.result == 'ERROR') {
alert(__('실패하였습니다.'));
} else if (aData.result == 'NOT_LOGIN') {
alert(__('회원 로그인 후 이용하실 수 있습니다.'));
} else if (aData.result == 'INVALID_REQUEST') {
alert(__('파라미터가 잘못되었습니다.'));
} else if (aData.result == 'NO_TARGET') {
alert(__('이미 등록되어 있습니다.'));
}
}
/**
* 추가된 함수
* 해당 value값을 받아 replace 처리
* @param string sValue value
* @return string replace된 sValue
*/
function replaceCheck(sName,sValue)
{
//ECHOSTING-9736
if (typeof(sValue) == "string" && (sName == "option_add[]" || sName.indexOf("item_option_add") === 0)) {
sValue = sValue.replace(/'/g, '\\&#039;');
}
// 타입이 string 일때 연산시 단일 따움표 " ' " 문자를 " ` " 액센트 문자로 치환하여 깨짐을 방지
return sValue;
}
/**
* name, value값을 받아 input hidden 태그 반환
*
* @param string sName name
* @param string sValue value
* @return string input hidden 태그
*/
function getInputHidden(sName, sValue)
{
sValue = replaceCheck(sName,sValue); // 추가된 부분 (replaceCheck 함수 호출)
return "<input type='hidden' name='" + sName + "' value='" + sValue + "' />";
}
/**
* 필수옵션이 선택되었는지 체크
*
* @return bool 필수옵션이 선택되었다면 true, 아니면 false 반환
*/
function checkOptionRequired(sReq)
{
var bResult = true;
// 옵션이 없다면 필수값 체크는 필요없음.
if (has_option === 'F') {
return bResult;
}
var sTargetOptionId = product_option_id
if (sReq != null) {
sTargetOptionId = sReq;
}
option_msg = __('필수 옵션을 선택해주세요.');
if (option_type === 'F') {
// 단독구성
var iOptionCount = $('select[id^="' + sTargetOptionId + '"][required="true"]:visible').length;
if (iOptionCount > 0) {
if (ITEM.getItemCode() === false) {
// alert(option_msg);
bResult = false;
return false;
}
var aRequiredOption = new Object();
var aItemCodeList = ITEM.getItemCode();
// 필수 옵션정보와 선택한 옵션 정보 비교
for (var i=0;i<aItemCodeList.length;i++) {
var sTargetItemCode = aItemCodeList[i];
$('select[id^="' + sTargetOptionId + '"][required="true"]:visible option').each(function() {
if ($(this).val() == sTargetItemCode) {
var sProductOptionId = $(this).parent().attr('id');
aRequiredOption[sProductOptionId] = true;
}
});
}
// 필수옵션별 개수보다 선택한 옵션개수가 적을경우 리턴
if (iOptionCount > Object.size(aRequiredOption)) {
//alert(option_msg);
bResult = false;
return bResult;
}
}
} else {
if (option_type == 'E') {
$('select[id^="' + product_option_id + '"][required="true"]:visible').each(function() {
var sel = parseInt($(this).val());
if (isNaN(sel) === true) {
bResult = false;
return false;
}
});
return bResult;
}
if (ITEM.getItemCode() === false) {
//alert(option_msg);
bResult = false;
return false;
}
// 조합구성
if (item_listing_type == 'S') {
// 분리선택형
var eTarget = $.parseJSON(option_value_mapper);
for (var x in eTarget) {
if (ITEM.getItemCode().indexOf(eTarget[x]) > -1) {
bResult = true;
break;
} else {
bResult = false;
}
}
if (bResult === false) {
//alert(option_msg);
bResult = false;
return false;
}
} else {
$('select[id^="' + product_option_id + '"][required="true"]:visible').each(function() {
var eTarget = $(this).children().children();
bResult = false;
eTarget.each(function() {
if (ITEM.getItemCode().indexOf($(this).val()) > -1) {
bResult = true;
return false;
}
});
if (bResult === false) {
//alert(option_msg);
return false;
}
});
}
}
return bResult;
}
/**
* 추가옵션 입력값 체크
*
* @return bool 모든 추가옵션에 값이 입력되었다면 true, 아니면 false
*/
function checkAddOption(sReq)
{
if (sReq != null) {
add_option_id = sReq;
}
var bResult = true;
$('[id^="' + add_option_id + '"]:visible').each(function()
{
if ($(this).attr('require') !== false && $(this).attr('require') == 'T') {
if ($(this).val().replace(/^[\s]+|[\s]+$/g, '').length == 0) {
alert(__('추가 옵션을 입력해주세요.'));
$(this).focus();
bResult = false;
return false;
}
}
});
return bResult;
}
/**
* 수량 가져오기
*
* @return mixed 정상적인 수량이면 수량(integer) 반환, 아니면 false 반환
*/
function getQuantity()
{
// 뉴상품인데 디자인이 수정안됐을 수 있다.
if (isNewProductSkin() === false) {
iQuantity = parseInt($(quantity_id).val(),10);
} else {
if (has_option == 'T') {
var iQuantity = 0;
if (Olnk.isLinkageType(sOptionType) === true) {
iQuantity = parseInt($(quantity_id).val(),10);
return iQuantity;
}
$('[name="quantity_opt[]"]').each(function() {
iQuantity = iQuantity + parseInt($(this).val(),10);
});
} else {
var iQuantity = parseInt($(quantity_id).val().replace(/^[\s]+|[\s]+$/g,'').match(/[\d\-]+/),10);
if (isNaN(iQuantity) === true || $(quantity_id).val() == '' || $(quantity_id).val().indexOf('.') > 0) {
return false;
}
}
}
return iQuantity;
}
/**
* 수량 체크
*
* @return mixed 올바른 수량이면 수량을, 아니면 false
*/
function checkQuantity()
{
// 수량 가져오기
var iQuantity = getQuantity();
if (isNewProductSkin() === false) {
if (iQuantity === false) return false;
if (iQuantity < product_min) {
alert(sprintf(__('최소 주문수량은 %s 입니다.'), product_min));
$(quantity_id).focus();
return false;
}
if (iQuantity > product_max && product_max > 0) {
alert(sprintf(__('최대 주문수량은 %s 입니다.'), product_max));
$(quantity_id).focus();
return false;
}
} else {
var bResult = true;
$('[name="quantity_opt[]"]').each(function() {
iQuantity = parseInt($(this).val());
if (iQuantity < product_min) {
alert(sprintf(__('상품별 최소 주문수량은 %s 입니다.'), product_min));
$(quantity_id).focus();
bResult = false;
return false;
}
if (iQuantity > product_max && product_max > 0) {
alert(sprintf(__('상품별 최대 주문수량은 %s 입니다.'), product_max));
$(quantity_id).focus();
bResult = false;
return false;
}
});
if (bResult == false) {
return bResult;
}
}
return iQuantity;
}
function commify(n)
{
var reg = /(^[+-]?\d+)(\d{3})/; // 정규식
n += ''; // 숫자를 문자열로 변환
while (reg.test(n)) {
n = n.replace(reg, '$1' + ',' + '$2');
}
return n;
}
var isClose = 'T';
function optionPreview(obj, sAction, sProductNo, closeType)
{
var sPreviewId = 'btn_preview_';
var sUrl = '/product/option_preview.html';
var layerId = $('#opt_preview_' + sAction + '_' + sProductNo);
// layerId = action명 + product_no 로 이루어짐 (한 페이지에 다른 종류의 상품리스트가 노출될때 구분 필요)
if ($(layerId).length > 0) {
$(layerId).show();
} else if (sProductNo != '') {
$.post(sUrl, 'product_no=' + sProductNo + '&action=' + sAction, function(result)
{
$(obj).after(result.replace(/[<]script( [^ ]+)? src=\"[^>]*>([\s\S]*?)[<]\/script>/g,""));
});
}
}
function closeOptionPreview(sAction, sProductNo)
{
isClose = 'T';
setTimeout("checkOptionPreview('" + sAction + "','" + sProductNo + "')", 150);
}
function checkOptionPreview(sAction, sProductNo)
{
var layerId = $('#opt_preview_' + sAction + '_' + sProductNo);
if (isClose == 'T') $(layerId).hide();
}
function openOptionPreview(sAction, sProductNo)
{
isClose = 'F';
var layerId = $('#opt_preview_' + sAction + '_' + sProductNo);
$(layerId).show();
$(layerId).mousemouseenter(function()
{
$(layerId).show();
}).mouseleave(function()
{
$(layerId).hide();
});
}
function changeOptionId()
{
if (typeof product_price == 'undefined') {
var product_price = 0;
}
var price = product_price;
$('select[id^="' + product_option_id + '"]').each(function()
{
aOptInfo = $(this).val().split('|');
if (typeof (aOptInfo[1]) != 'undefined') {
price += parseInt(aOptInfo[1]);
}
});
$('#product_price').val(price);
$('#span_product_price').html(commify(price) + '원');
}
/**
* 네이버체크아웃 주문하기
*/
function nv_add_basket_1_product()
{
bIsMobile = false;
if (_isProc == 'F') {
alert(__("체크아웃 입점상태를 확인하십시오."));
return;
}
if (typeof(set_option_data) != 'undefined') {
alert(__('세트상품은 체크아웃 구매가 불가하오니, 쇼핑몰 바로구매를 이용해주세요. 감사합니다.'));
return;
}
product_submit('naver_checkout', '/exec/front/order/basket/')
}
/**
* 네이버체크아웃 찜하기
*/
function nv_add_basket_2_product()
{
if (_isProc == 'F') {
alert(__("체크아웃 입점상태를 확인하십시오."));
return;
}
window.open("/exec/front/order/navercheckoutwish?product_no=" + iProductNo, "navercheckout_basket",
'scrollbars=yes,status=no,toolbar=no,width=450,height=300');
}
/**
* 네이버체크아웃 주문하기
*/
function nv_add_basket_1_m_product()
{
bIsMobile = true;
if (_isProc == 'F') {
alert(__("체크아웃 입점상태를 확인하십시오."));
return;
}
if (typeof(set_option_data) != 'undefined') {
alert(__('세트상품은 체크아웃 구매가 불가하오니, 쇼핑몰 바로구매를 이용해주세요. 감사합니다.'));
return;
}
product_submit('naver_checkout', '/exec/front/order/basket/')
}
/**
* 네이버체크아웃 찜하기
*/
function nv_add_basket_2_m_product()
{
if (_isProc == 'F') {
alert(__("체크아웃 입점상태를 확인하십시오."));
return;
}
window.location.href = "/exec/front/order/navercheckoutwish?product_no=" + iProductNo;
//window.open("/exec/front/order/navercheckoutwish?product_no=" + iProductNo, "navercheckout_basket", 'scrollbars=yes,status=no,toolbar=no,width=450,height=300');
}
/**
* 옵션 추가 구매시에 같은 옵션을 검사하는 함수
*
* @returns Boolean
*/
function duplicateOptionCheck()
{
var bOptionDuplicate = getOptionDuplicate();
var bAddOptionDuplicate = getAddOptionDuplicate();
if (bOptionDuplicate !== true && bAddOptionDuplicate !== true) {
alert(__('동일한 옵션의 상품이 있습니다.'));
return false;
}
return true;
}
/**
* 텍스트 인풋 옵션 중복 체크
*
* @returns {Boolean}
*/
function getAddOptionDuplicate()
{
var aOptionRow = new Array();
var iOptionLength = 0;
var aOptionValue = new Array();
var bReturn = true;
// 기본 옵션
$('[id^="' + add_option_id + '"]:visible').each(function()
{
aOptionRow.push($(this).val());
});
aOptionValue.push(aOptionRow.join(',@,'));
$('.EC_MultipleOption').each(function()
{
aOptionRow = new Array();
$($(this).find('.' + $.data(document, 'multiple_option_input_class'))).each(function()
{
aOptionRow.push($(this).val());
});
var sOptionRow = aOptionRow.join(',@,');
if ($.inArray(sOptionRow, aOptionValue) > -1) {
bReturn = false;
return false;
} else {
aOptionValue.push(sOptionRow);
}
});
return bReturn;
}
/**
* 일반 셀렉트박스형 옵션 체크 함수
*
* @returns {Boolean}
*/
function getOptionDuplicate()
{
// 선택여부는 이미 선택이 되어 있음
var aOptionId = new Array();
var aOptionValue = new Array();
var aOptionRow = new Array();
var iOptionLength = 0;
// 기본 옵션
$('select[id^="' + product_option_id + '"]:visible').each(function(i)
{
aOptionValue.push($(this).val());
iOptionLength++;
});
// 추가 구매
$('.' + $.data(document, 'multiple_option_select_class')).each(function(i)
{
aOptionValue.push($(this).val());
});
var aOptionRow = new Array();
for ( var x in aOptionValue) {
var sOptionValue = aOptionValue[x];
aOptionRow.push(sOptionValue);
if (x % iOptionLength == iOptionLength - 1) {
var sOptionId = aOptionRow.join('-');
if ($.inArray(sOptionId, aOptionId) > -1) { return false; }
aOptionId.push(sOptionId);
aOptionRow = new Array();
}
}
return true;
}
function getOptionValue(sReq)
{
var sReturn = sReq;
if (sReq.indexOf('|') > -1) {
var aReturn = sReq.split('|');
sReturn = aReturn[0];
}
return sReturn;
}
function action_sms_restock(sParam)
{
window.open('#none', 'sms_restock' ,'width=459, height=490');
$('#frm_image_zoom').attr('target', 'sms_restock');
$('#frm_image_zoom').attr('action', '/product/sms_restock.html');
$('#frm_image_zoom').submit();
}
// 최대 할인쿠폰 다운받기 팝업
function popupDcCoupon(product_no, coupon_no, cate_no, opener_url, location)
{
var Url = '/';
if ( location === 'Front' || typeof location === 'undefined') {
Url += 'product/'
}
Url += '/coupon_popup.html';
window.open(Url + "?product_no=" + product_no + "&coupon_no=" + coupon_no + "&cate_no=" + cate_no + "&opener_url=" + opener_url, "popupDcCoupon", "toolbar=no,scrollbars=no,resizable=yes,width=800,height=640,left=0,top=0");
}
/**
* 관련상품 열고 닫기
*/
function ShowAndHideRelation()
{
try {
var sRelation = $('ul.mSetPrd').parent();
var sRelationDisp = sRelation.css('display');
if (sRelationDisp === 'none') {
$('#setTitle').removeClass('show');
sRelation.show();
} else {
$('#setTitle').addClass('show');
sRelation.hide();
}
} catch(e) { }
}
var ITEM = {
getItemCode : function()
{
var chk_has_opt = '';
try {
chk_has_opt = has_option;
}catch(e) {chk_has_opt = 'T';}
if (chk_has_opt == 'F') {
return [item_code];
} else {
// 필수값 체크
var bRequire = false;
$('[id^="product_option_id"]').each(function() {
if (Boolean($(this).attr('required')) === true || $(this).attr('required') == 'required') {
bRequire = true;
return false;
}
});
var aItemCode = new Array();
if (bRequire === true) {
if ($('#totalProducts').size() === 0) {
sItemCode = this.getOldProductItemCode();
if (sItemCode !== false) {
if (typeof(sItemCode) === 'string') {
aItemCode.push(sItemCode);
} else {
aItemCode = sItemCode;
}
} else {
// 옵션이 선택되지 않음
return false;
}
} else {
if ($('.option_box_id').length == 0) {
// 옵션이 선택되지 않음
return false;
}
$('.option_box_id').each(function() {
aItemCode.push($(this).val());
});
}
}
return aItemCode;
}
},
getWishItemCode : function()
{
var chk_has_opt = '';
try {
chk_has_opt = has_option;
}catch(e) {chk_has_opt = 'T';}
if (chk_has_opt == 'F') {
return [item_code];
} else {
// 필수값 체크
var bRequire = false;
$('[id^="product_option_id"]').each(function() {
if (Boolean($(this).attr('required')) === true || $(this).attr('required') == 'required') {
bRequire = true;
return false;
}
});
var aItemCode = new Array();
if (bRequire === true) {
if ($('#totalProducts').size() === 0) {
sItemCode = this.getOldProductItemCode();
if (sItemCode !== false) {
if (typeof(sItemCode) === 'string') {
aItemCode.push(sItemCode);
} else {
aItemCode = sItemCode;
}
} else {
// 옵션이 선택되지 않음
return false;
}
} else {
if ($('.soldout_option_box_id,.option_box_id').length == 0) {
// 옵션이 선택되지 않음
return false;
}
$('.soldout_option_box_id,.option_box_id').each(function() {
aItemCode.push($(this).val());
});
}
}
return aItemCode;
}
},
getOldProductItemCode : function(sSelector)
{
if (sSelector === undefined) {
sSelector = '[id^="product_option_id"]';
}
var sItemCode = null;
// 뉴상품 옵션 선택 구매
if (has_option === 'F') {
// 화면에 있음
sItemCode = item_code;
} else {
if (item_listing_type == 'S') {
var aOptionValue = new Array();
$(sSelector).each(function() {
if (ITEM.isOptionSelected($(this).val()) === true) {
aOptionValue.push($(this).val());
}
});
if (option_type === 'T') {
var aCodeMap = $.parseJSON(option_value_mapper);
sItemCode = aCodeMap[aOptionValue.join('#$%')];
} else {
sItemCode = aOptionValue;
}
} else {
sItemCode = $(sSelector).val();
}
}
if (sItemCode === undefined) {
return false;
}
return sItemCode;
},
isOptionSelected : function(aOption)
{
var sOptionValue = null;
if (typeof aOption === 'string') {
sOptionValue = aOption;
} else {
if (aOption.length === 0) return false;
sOptionValue = aOption.join('-|');
}
sOptionValue = '-|'+sOptionValue+'-|';
return !(/-\|\*{1,2}-\|/g).test(sOptionValue);
}
};
/**
* ie8 일때 indxeOf 동작안함
*/
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(elt /*, from*/) {
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0) ? Math.ceil(from) : Math.floor(from);
if (from < 0) {
from += len;
}
for (from; from < len; from++) {
if (from in this && this[from] === elt) {
return from;
}
}
return -1;
};
}
if (!Object.size) {
Object.size = function(obj) {
var size = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)) size++;
}
return size;
};
}
/**
* 추가구성 상품 라이브러리
*/
var TotalAddSale = function() {
//추가할인액계산
var oProductList = new Object();
var oTotalAddSaleParam = new Object();
var iTotalAddSalePrice = 0;
/**
* 추가할인액 주문api조회
* @param fCallback 콜백함수
* @return TotalAddSale.iTotalAddSalePrice
*/
var getCalculatorSalePrice = function (fCallback, iPrice) {
$.ajax({
url : "/exec/front/shop/CalculatorProduct",
type : "post",
data : oTotalAddSaleParam,
dataType : "json",
timeout : 1100,
success : function(oResponse){
TotalAddSale.iTotalAddSalePrice = oResponse;
fCallback(iPrice);
},
error : function(){
alert('옵션 선택에 따른 할인판매가가 정상적으로 표시되지 않고 있습니다.\n상품 주문시에는 할인판매가로 정상 적용됩니다.');
fCallback(iPrice);
}
});
}
return {
// 총 추가할인액 반환
getTotalAddSalePrice : function() {
return TotalAddSale.iTotalAddSalePrice;
},
// 계산할 정보 셋팅
setParam : function(sKey, value) {
oTotalAddSaleParam[sKey] = value;
},
// 계산될 상품리스트
getProductList : function() {
return oProductList;
},
// 총 추가할인금액 리셋
setTotalAddSalePrice : function(iSalePrice) {
TotalAddSale.iTotalAddSalePrice = iSalePrice;
},
// 계산할 정보 수량 셋팅
setQuantity : function(sItemCode, sQuantity) {
oProductList[sItemCode] = sQuantity;
},
// api호출
getCalculatorSalePrice : function(fCallback, iPrice) {
getCalculatorSalePrice(fCallback, iPrice);
}
};
}();
$(document).ready(function(){
});
var isMobile = false;
var sInputMileBackground = '';
$(document).ready(function() {
// 모바일접속 여부
// mobileWeb 값이 있으면 참조하고 없으면 m. 도메인 체크
if (mobileWeb == undefined) {
if (window.location.hostname.substr(0, 2) == 'm.' || window.location.hostname.substr(0, 12) == 'mobile--shop' || window.location.hostname.substr(0, 11) == 'skin-mobile') {
isMobile = true;
}
} else {
isMobile = mobileWeb;
}
// 주문서 작성 페이지
try {
$('#np_use0').attr('checked', 'true');
$('#np_use0').click(function() {
if ($(this).attr('checked') == false) {
initNaverMileage();
if (isMobile == true && typeof(nbp) == 'object') {
nbp.mileage.inactive();
}
} else {
if (isMobile == true && typeof(nbp) == 'object') {
nbp.mileage.active();
}
}
if (isMobile == false) {
setNaverPoint();
}
});
} catch(e) {}
// 네이버마일리지 적립금과 동시사용 불가에 따른 처리
// 동시사용 불가인 경우 디자인 수정을 안했을때 기존꺼 노출
try {
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == false) {
$('div.boardView').find('#input_mile').parents('div:first').removeClass('displaynone');
$('div.boardView').find('#np_use0').parents('div:first').removeClass('displaynone');
}
} catch (e) {}
// 적립금동시사용불가 디자인적용에 따른 처리
try {
if (isApplyDesignNMCanUseWithMileage()) {
$('#either_mileage_navermileage_select0').attr('checked', true);
if (isMobile == true) {
$('input[name^="mileage_use_select"]').click(function() {
var oInputMile = getInputMileObject();
if ($(this).val() == 'mileage') {
initNaverMileage();
oInputMile.css('background', sInputMileBackground);
oInputMile.attr('readonly', false);
if (isApplyDesignNMCanUseWithMileage() == true) {
nbp.mileage.inactive();
}
} else {
sInputMileBackground = oInputMile.css('background');
oInputMile.val(0);
oInputMile.attr('readonly', true);
oInputMile.css('background', '#CCCCCC');
if (isApplyDesignNMCanUseWithMileage() == true) {
nbp.mileage.active();
}
if (bInflowParam != false){
} else {
$('#_either_mileage_acc').hide();
}
}
set_total_price();
});
} else {
$('#navermileage_use_container').css({"display":"none"});
$('input[id^="either_mileage_navermileage_select1"]').css("margin-left", "10px");
$('label[for^="either_mileage_navermileage_select"]').css("padding-left", "3px");
$('input[name^="mileage_use_select"]').click(function() {
var oMileageUseContainer = $('#mileage_use_container');
var oNavermileageUseContainer = $('#navermileage_use_container');
var oNavermileageGuideContainer = $('#navermileage_guide_cotainer');
var oInputMile = getInputMileObject();
oMileageUseContainer.css('display', 'none');
oNavermileageUseContainer.css('display', 'none');
oNavermileageGuideContainer.css('display', 'none');
if ($(this).val() == 'mileage') {
oMileageUseContainer.css('display', '');
initNaverMileage();
} else {
oNavermileageUseContainer.css('display', '');
oNavermileageGuideContainer.css('display', '');
oInputMile.val(0);
//네이버 ON 상태는 꼭 이렇게 비교하라고 해서 이렇게 함
if (bInflowParam != false) {
} else {
$('#either_divNvPointBtnAdd').hide();
$('#either_divNvDefaultGuide').html('네이버 통해 방문 시 적립/사용 가능');
}
}
if (bInflowParam != false) {
setNaverPoint();
}
set_total_price();
});
var oNavermileageGuideContainer = $('#navermileage_guide_cotainer');
oNavermileageGuideContainer.css('display', 'none');
}
}
} catch (e) {}
// PC 쇼핑몰 > 주문서 작성페이지
if (isMobile == false) {
try {
// 네이버마일리지 가이드 폭조정(동시사용 불가능 UI)
$('.navermileage_guide').css({'text-align':'center', 'padding-top':'5px', 'padding-bottom':'5px', 'background-color':'#f7f7ff'});
// 적립률 색상 변경 & bold처리
$('#txt_np_save').css({'color':'#1ec228', 'font-weight':'bold'});
$('#divNvPointOpr').css({'color':'#1ec228', 'font-weight':'bold'});
} catch (e) {}
}
// 네이버 추가 적립률 네이버공통스크립트로 부터 가져오기
try {
var oNaverMileage = {
'def' : 0,
'base' : 0,
'add' : 0
};
oNaverMileage.def = $('#np_save_rate_default').val();
// get save rate of naverMileage
if (typeof(wcs) == 'object') {
var bInflowParam = wcs.getMileageInfo();
if (bInflowParam != false) {
oNaverMileage.base = wcs.getBaseAccumRate();
oNaverMileage.add = wcs.getAddAccumRate();
if (isMobile == false) {
if ($('.xans-order-form').length > 0) {//주문서
var oNaverStateImg = '<img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin:3px">';
$('#either_mileage_navermileage_select0').parents('tbody').find('th > label').html('적립금&<br>네이버마일리지<br>' + oNaverStateImg + '(택1)');
$('#naverPointStatus').html(oNaverStateImg);
$('#naverPointStatus img').css({'margin':'-3px 3px 0'});
$('#either_imgNaverMileageHelp').attr('http://img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
$('#np_use0').parent().append(oNaverStateImg);
$('#imgNaverMileageHelp').attr('src', 'http://img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
} else {
$('#imgNaverMileageHelp').css({'margin-top' : '-2px'});
}
}
} else {
oNaverMileage.base = oNaverMileage.def;
if (isMobile == false) {
if ($('.xans-order-form').length > 0) {//주문서
var oNaverStateImg = '<img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png" style="margin:3px">';
//택1 일 경우 (어차피 display none 일 때는 안 보임)
$('#either_mileage_navermileage_select0').parents('tbody').find('th > label').html('적립금&<br>네이버마일리지<br>' + oNaverStateImg + '(택1)');
$('#naverPointStatus').html(oNaverStateImg);
$('#naverPointStatus img').css({'margin':'-3px 3px 0'});
$('#np_use0').hide();
$('#divNvPointBtnAdd').hide();
$('#divNvDefaultGuide').html('네이버 통해 방문 시 적립/사용 가능');
$('label[for="np_use0"]').parent().html('네이버 마일리지' + oNaverStateImg);
$('#imgNaverMileageHelp').attr('src', 'http://img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
$('.naverInfo').hide();
} else {//상품상세
var sNaverStateImg = 'http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_off2.png';
var sOnClick = "NaverMileage.openMileageIntroPopup('http://static.mileage.naver.net/static/20130708/ext/intro.html');";
$('#naver_mileage_save_rate_base').parent().html('네이버 마일리지 <a href="#none" onclick="' + sOnClick + '"><img src="' + sNaverStateImg + '" style="margin-top:-2px;"></a><br>(네이버 통해 방문 시 적립/사용 가능)');
}
}
}
} else {
oNaverMileage.base = $('#np_save_rate').val();
oNaverMileage.add = $('#np_save_rate_add').val();
}
if (oNaverMileage.base == 0 || oNaverMileage.base == '') {
oNaverMileage.base = oNaverMileage.def;
}
// casting data type
oNaverMileage.def = castDataType(oNaverMileage.def);
oNaverMileage.base = castDataType(oNaverMileage.base);
oNaverMileage.add = castDataType(oNaverMileage.add);
// true - 상품상세 페이지, false - 주문서 작성 페이지
if (document.getElementById('naver_mileage_save_rate_base') != undefined && document.getElementById('naver_mileage_save_rate_base') != null) {
//ECHOSTING-73678
$('#imgNaverMileageHelp').attr('src','http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_on2.png');
if (oNaverMileage.base > 0) {
var iTotalNaverMileageRate = oNaverMileage.base + oNaverMileage.add;
$('#naver_mileage_save_rate_base').html(iTotalNaverMileageRate + '%');
} else {
$('#naver_mileage_save_rate_base').html(oNaverMileage.def + '%');
}
} else {
var iSaveRateSum = oNaverMileage.base;
if (oNaverMileage.add > 0) {
iSaveRateSum += oNaverMileage.add;
}
$('#divNvDefaultGuide .naver_mileage_save_rate_sum').html(castDataType(iSaveRateSum));
$('#either_divNvDefaultGuide .naver_mileage_save_rate_sum').html(castDataType(iSaveRateSum));
}
// 모바일 > 주문서 작성 페이지인 경우에만 실행(마일리지 모바일버전은 ui노출부분이 다르다.)
if (isMobile) {
initNavermileageWithWcs();
if ($('#frm_order_act').length > 0) {//주문서
var bUseSelectMileage = isApplyDesignNMCanUseWithMileage();
}
if (bInflowParam != false) {
if ($('.xans-product-detail').length > 0) {//상품상세
var sOnImg = '<img src="http://img.echosting.cafe24.com/design/skin/mobile/txt_naver_on1.png" style="width:28px;margin-bottom:-1px;">';
$('#naver_mileage_save_rate_add').html('적립 ' + sOnImg);
$('#naverMileageSaveText').hide();
} else {//주문서
$('#naverMileageTitle').append(' <img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin-bottom:-1px">');
if (bUseSelectMileage) {//택1
$('#navermileage_use_container').find('label > span').append(' <img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin-bottom:-1px">');
}
}
} else {
if ($('#frm_order_act').length > 0) {//주문서
$('#np_use0').hide();
$('#naverMileageTitle').append(' <img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png">');
$('#_mileage_acc').html('네이버 통해 방문 시 적립/사용 가능 ');
if (bUseSelectMileage) {//택1
$('#navermileage_use_container').find('label > span').append(' <img src="http://img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png" style="margin-bottom:-1px">');
$('#_mile_acc_rate').parent().hide();
$('#navermileage_use_container').find('.either_navermileage_use_container').append('네이버 통해 방문 시 적립/사용 가능');
}
} else{//상품상세
$('#naver_mileage_save_rate_base').hide();
var sOffImg = '<img src="http://img.echosting.cafe24.com/design/skin/mobile/txt_naver_off1.png" style="width:28px;margin-bottom:-1px;">';
$('#naver_mileage_save_rate_add').html(sOffImg+ ' (네이버 통해 방문 시 적립/사용 가능) ');
$('#naverMileageSaveText').hide();
}
}
}
} catch (e) {}
});
var naver_reqTxId;
var bNvOn = false;
var NaverMileage = {
onNvPointLayer:function(dMode)
{
bNvOn = true;
var obj = document.getElementById('divNvPointInfo');
$('#divNvPointInfo').show();
var leftMargine = obj.offsetWidth;
if (dMode == 1) {
var XY = $('#imgNaverMileageHelp').position();
obj.style.top = XY.top+14+'px';
obj.style.left = XY.left-150+'px';
if (obj.attachEvent) {
obj.attachEvent('onmouseover', NaverMileage.setNvOn);
} else {
obj.addEventListener('mouseover', NaverMileage.setNvOn, false);
}
}
return true;
},
setNvOn:function() {
bNvOn = true;
},
offNvPointLayerTic:function(bIntval)
{
bNvOn = false;
if (bIntval == true) {
setTimeout("NaverMileage.offNvPointLayer()", 200);
} else {
NaverMileage.offNvPointLayer();
}
},
offNvPointLayer:function()
{
if (bNvOn == false) $('#divNvPointInfo').hide();
},
openMileageIntroPopup : function(sUrl)
{
var iWidth = 404;
var iHeight = 412;
var iLeft = (screen.width - iWidth) / 2;
var iTop = (screen.height - iHeight) / 2;
var sOpt = 'width='+iWidth+', height='+iHeight+', left='+iLeft+', top='+iTop+', status=no, resizable=no';
window.open(sUrl, 'mileageIntroPopup', sOpt);
}
};
function showNaverCashShowAccumPopup()
{
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == false) {
var oInputMile = getInputMileObject();
if (parseInt(oInputMile.val()) > 0) {
alert(__('네이버마일리지는 적립금과 동시사용할 수 없습니다.'));
return false;
}
}
if (document.getElementById('np_use0').checked == false) {
alert(__('네이버 마일리지 사용/적립 시에는 좌측의 체크박스를 선택하셔야 합니다.'));
return false;
}
var sUrl = "https://service.mileage.naver.com/service/accumulation/"+$('#np_api_id').val()+"?doneUrl="+$('#np_done_url').val();
var sUrl = "https://service.mileage.naver.com/service/v2/accumulation/"+$('#np_api_id').val()+"?doneUrl="+$('#np_done_url').val();
if (typeof(sIsNaverMileageSandbox) != 'undefined') {
if (sIsNaverMileageSandbox == 'T') {
var sUrl = "https://sandbox-service.mileage.naver.com/service/v2/accumulation/"+$('#np_api_id').val()+"?doneUrl="+$('#np_done_url').val();
}
}
if (naver_reqTxId) {
sUrl = sUrl + "&reqTxId=" + naver_reqTxId;
}
var sNcisy = new String();
if (typeof(wcs) == 'object') {
var inflowParam = wcs.getMileageInfo();
if (inflowParam != false) {
sNcisy = inflowParam;
}
} else {
sNcisy = $('#np_ncisy').val();
}
sUrl = sUrl + "&Ncisy=" + sNcisy;
sUrl = sUrl + "&sig=" + $('#np_req_sig').val();
sUrl = sUrl + "&timestamp=" + $('#np_timestamp').val();
try {
if (typeof($('#r_total_price').val()) != 'undefined') {
var iMaxUseAmount = SHOP_PRICE.toShopPrice($('#r_total_price').val());
sUrl = sUrl + "&maxUseAmount=" + iMaxUseAmount;
}
} catch (e) {}
var sWinName = document.getElementById('np_window_name').value;
window.open(sUrl , sWinName, "width=496,height=434,status=no,resizable=no");
}
function enableNaverCashPanel(baseAccumRate, addAccumRate, useAmount, balanceAmount, reqTxId, sig, resultCode, mileageUseAmount, cashUseAmount, totalUseAmount)
{
naver_reqTxId = reqTxId;
if (SHOP_PRICE.toShopPrice(stringReplace(',','',$('#total_price').val())) + parseInt($('#np_use_amt').val()) < parseInt(totalUseAmount)) {
alert(__('결제하셔야 할 금액보다 사용금액이 큽니다. 다시 사용금액을 입력해주세요'));
return false;
}
if ($('#np_req_tx_id').val() != null && reqTxId != '' && reqTxId != 0 && resultCode == 'E1000') {
$('#np_req_tx_id').val(reqTxId);
$('#np_save_rate').val(baseAccumRate);
$('#np_save_rate_add').val(addAccumRate);
$('#np_use_amt').val(useAmount);
$('#np_mileage_use_amount').val(mileageUseAmount);
$('#np_cash_use_amount').val(cashUseAmount);
$('#np_total_use_amount').val(totalUseAmount);
$('#np_use_amt').val(useAmount);
$('#np_balance_amt').val(balanceAmount);
$('#np_sig').val(sig);
if ($('#np_use0').attr('checked') == true) {
$('#np_use').val('T');
} else {
$('#np_use').val('');
}
} else {
initNaverMileage();
}
$('#imgNaverMileageHelp').show();
// PC쇼핑몰인경우만 ui에 사용 마일리지&캐쉬 정보 적용
if (isMobile == false) {
setNaverPoint();
}
}
function setNaverPoint()
{
try {
var bUseNaverMileage = false;
if (isApplyDesignNMCanUseWithMileage()) {
if ($('#either_mileage_navermileage_select1').attr('checked') == true) {
bUseNaverMileage = true;
}
} else {
if ($('#np_use0').attr('checked') == true) {
bUseNaverMileage = true;
}
}
if (bUseNaverMileage == false) {
initNaverMileage();
}
var sNpReqTxId = document.getElementById('np_req_tx_id').value;
var iNpUseAmt = SHOP_PRICE.toShopPrice(document.getElementById('np_use_amt').value);
var iNpMileageUseAmt = SHOP_PRICE.toShopPrice(document.getElementById('np_mileage_use_amount').value);
var iNpCashUseAmt = SHOP_PRICE.toShopPrice(document.getElementById('np_cash_use_amount').value);
var iNpTotalUseAmt = SHOP_PRICE.toShopPrice(document.getElementById('np_total_use_amount').value);
var iNpBalanceAmt = SHOP_PRICE.toShopPrice(document.getElementById('np_balance_amt').value);
var iNpSaveRate = parseFloat(document.getElementById('np_save_rate').value);
var iNpSaveRateAdd = parseFloat(document.getElementById('np_save_rate_add').value);
var iNpSaveRateTotal = iNpSaveRate + iNpSaveRateAdd;
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
var elmNvDefaultGuide = document.getElementById('either_divNvDefaultGuide');
var oDivNvPointUse = document.getElementById('either_divNvPointUse');
var oDivNvPointSave = document.getElementById('either_divNvPointSave');
var oDivNvPointOpr = document.getElementById('either_divNvPointOpr');
var oDivNvPointBtnAdd = document.getElementById('either_divNvPointBtnAdd');
var oDivNvPointBtnMod = document.getElementById('either_divNvPointBtnMod');
var oTxtNpUse = document.getElementById('either_txt_np_use');
var oTxtNpSave = document.getElementById('either_txt_np_save');
var oExTxNpSave = document.getElementById('either_ex_tx_np_save');
var oExTxNpUse = document.getElementById('either_ex_tx_np_use');
var bInflowParam = wcs.getMileageInfo();
} else {
var elmNvDefaultGuide = document.getElementById('divNvDefaultGuide');
var oDivNvPointUse = document.getElementById('divNvPointUse');
var oDivNvPointSave = document.getElementById('divNvPointSave');
var oDivNvPointOpr = document.getElementById('divNvPointOpr');
var oDivNvPointBtnAdd = document.getElementById('divNvPointBtnAdd');
var oDivNvPointBtnMod = document.getElementById('divNvPointBtnMod');
var oTxtNpUse = document.getElementById('txt_np_use');
var oTxtNpSave = document.getElementById('txt_np_save');
var oExTxNpSave = document.getElementById('ex_tx_np_save');
var oExTxNpUse = document.getElementById('ex_tx_np_use');
}
if (isUseNaverMileage() == false) {
elmNvDefaultGuide.style.display = '';
}
oDivNvPointUse.style.display = 'none';
oDivNvPointSave.style.display = 'none';
oDivNvPointOpr.style.display = 'none';
oDivNvPointBtnAdd.style.display = 'none';
oDivNvPointBtnMod.style.display = 'none';
if (iNpTotalUseAmt > 0 && iNpSaveRate > 0) {//& opr
oDivNvPointOpr.style.display = 'inline';
}
if (iNpTotalUseAmt > 0 || iNpSaveRateTotal > 0) {
oDivNvPointBtnMod.style.display = 'inline';
} else {
oDivNvPointBtnAdd.style.display = 'inline';
}
if (iNpSaveRateTotal > 0) {//적립
if (elmNvDefaultGuide) {
elmNvDefaultGuide.style.display = 'none';
}
oDivNvPointSave.style.display = 'inline';
oTxtNpSave.innerHTML = oExTxNpSave.innerHTML.replace("[np_rate]", iNpSaveRateTotal);
}
set_total_price();
if (iNpTotalUseAmt > 0) {
if (elmNvDefaultGuide) {
elmNvDefaultGuide.style.display = 'none';
}
oDivNvPointUse.style.display = 'inline';
var sTmp = oExTxNpUse.innerHTML;
var aUseNaverValue = new Array();
if (iNpMileageUseAmt > 0) {
aUseNaverValue.push('마일리지 ' + addCommas(iNpMileageUseAmt) + '원');
}
if (iNpCashUseAmt > 0) {
aUseNaverValue.push('캐쉬 ' + addCommas(iNpCashUseAmt) + '원');
}
oTxtNpUse.innerHTML = aUseNaverValue.join(' + ') + ' 사용';
}
paymethod_display($(':input:radio[name="addr_paymethod"]:checked').val());
} catch (e) {
initNaverMileage();
set_total_price();
}
}
/**
* 네이버 마일리지/캐쉬 reset
* @return void
*/
function resetNaverPoint()
{
try {
$('#np_use0').attr('checked',false);
setNaverPoint();
$('#np_use0').attr('checked',true);
paymethod_display($(':input:radio[name="addr_paymethod"]:checked').val());
} catch (e) {}
}
/**
* 네이버 마일리지/캐쉬 사용안함
* @return void
*/
function initNaverMileage()
{
// clear value
try {
document.getElementById('np_req_tx_id').value = "";
document.getElementById('np_use_amt').value = 0;
document.getElementById('np_mileage_use_amount').value = 0;
document.getElementById('np_cash_use_amount').value = 0;
document.getElementById('np_total_use_amount').value = 0;
document.getElementById('np_balance_amt').value = 0;
document.getElementById('np_save_rate').value = 0;
document.getElementById('np_save_rate_add').value = 0;
document.getElementById('np_sig').value = "";
} catch (e) {}
// init design
try {
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
var oDivNvPointUse = document.getElementById('either_divNvPointUse');
var oDivNvPointSave = document.getElementById('either_divNvPointSave');
var oDivNvPointOpr = document.getElementById('either_divNvPointOpr');
var oDivNvPointBtnAdd = document.getElementById('either_divNvPointBtnAdd');
var oDivNvPointBtnMod = document.getElementById('either_divNvPointBtnMod');
} else {
var oDivNvPointUse = document.getElementById('divNvPointUse');
var oDivNvPointSave = document.getElementById('divNvPointSave');
var oDivNvPointOpr = document.getElementById('divNvPointOpr');
var oDivNvPointBtnAdd = document.getElementById('divNvPointBtnAdd');
var oDivNvPointBtnMod = document.getElementById('divNvPointBtnMod');
}
oDivNvPointUse.style.display = 'none';
oDivNvPointSave.style.display = 'none';
oDivNvPointOpr.style.display = 'none';
oDivNvPointBtnAdd.style.display = 'inline';
oDivNvPointBtnMod.style.display = 'none';
} catch (e) {}
// clear trasaction id
try {
naver_reqTxId = '';
} catch (e) {}
}
/**
* 네이버 마일리지/캐쉬 사용 여부
* @return boolean
*/
function isUseNaverMileage()
{
var bIsUse = false;
try {
if ($('#np_req_tx_id').val() != '' || $('#np_save_rate').val() > 0) {
bIsUse = true;
}
} catch (e) {}
return bIsUse;
}
/**
* 자료형 cast
* @param float fData 숫자
* @return mixed
*/
function castDataType(fData)
{
if (isNaN(fData) == false) {
if ((fData % 1) == 0) {
return parseInt(fData);
} else {
return parseFloat(fData);
}
} else {
return 0;
}
}
/**
* 모바일 마일리지 Library 초기화
*/
function initNavermileageWithWcs()
{
try {
// 네이버마일리지 관련 변수가 controller에서 assign이 안되어 있으면 아래부분 실행시도를 안한다.
if (typeof(nbp) == 'object') {
var iMaxuseAmount = parseInt($('#total_price').val().replace(/,/g, ''));
var iBaseAccumRate = parseFloat($('#np_save_rate_default').val());
var iTimestamp = parseInt($('#np_timestamp').val());
var sId = '_mileage_acc';
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
sId = '_either_mileage_acc';
}
var bResult = nbp.mileage.initWithWcs({
'sId': sId,
'sApiId': $('#np_api_id').val(),
'sDoneUrl': decodeURIComponent($('#np_done_url').val()),
'nMaxUseAmount': iMaxuseAmount,
'sSig': $('#np_req_sig').val(),
'nTimestamp': iTimestamp,
'nBaseAccumRate': iBaseAccumRate,
'bActive' : true,
'event' : {
'beforeAccum' : function(oEvent) { //적립/사용페이지가 뜨기 직전 호출된다.
set_total_price();
nbp.mileage.setMaxUseAmount(getNavermileageMaxAmount());
if (oEvent.bActive === false) { //마일리지 모듈이 비활성화 상태에서 적립/사용 버튼 클릭 callback 구현
alert('네이버 마일리지를 사용/적립하려면, 먼저 \'네이버 마일리지\'를 선택해야합니다. ');
return false;
}
},
'accum' : function(aRetVal) {
aRetVal.resultCode = convertResultCode(aRetVal.resultCode);
enableNaverCashPanel(aRetVal.baseAccumRate, aRetVal.addAccumRate, aRetVal.mileageUseAmount, aRetVal.balanceAmount, aRetVal.reqTxId, aRetVal.sig, aRetVal.resultCode, aRetVal.mileageUseAmount, aRetVal.cashUseAmount, aRetVal.totalUseAmount);
set_total_price();
}
}
});
if (bResult) {
if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
nbp.mileage.inactive();
}
} else {
if ($('#np_is_use').val() == 'T' && document.getElementById('_mileage_acc') != null && document.getElementById('_mileage_acc') != undefined) {
alert('네이버마일리지 적립/사용 초기화가 정상적이지 않습니다. 지속발생시 운영자에게 문의 해주세요.');
}
}
}
} catch (e) {}
}
/**
* pg모듈에서 리턴해주는 형식으로 변환
* @param string sCode 코드
* @return string
*/
function convertResultCode(sCode)
{
if (sCode == 'OK') {
return 'E1000';
} else if (sCode == 'CANCEL') {
return 'E1001';
} else if (sCode == 'ERROR') {
return 'E1002';
} else {
return 'E1100';
}
}
/**
*모바일 마일리지 최대사용가능 금액(결제금액 + 마일리지 사용금액)
* @return int
*/
function getNavermileageMaxAmount()
{
var iMaxAmount = SHOP_PRICE.toShopPrice($('#total_price').val().replace(/,/g, ''));
iMaxAmount += check_parseInt(getUseNaverMileageCash());
return iMaxAmount;
}
var BigDataLog = {
'_elementId' : 'bigdata_log',
'_cookieName' : 'bigdata_log',
'getcookie' : function(name) {
if (!document.cookie) return null;
name = name || this._cookieName;
var val = null;
var arr = document.cookie.split((escape(name)+'='));
if (arr.length >= 2) {
var arrSub = arr[1].split(';');
val = unescape(arrSub[0]);
}
return val;
},
'delcookie' : function(name) {
name = name || this._cookieName;
var sCookie = escape(name) + '=; ';
sCookie += 'expires='+ (new Date(1)).toGMTString() +'; ';
sCookie += 'path=/; ';
sCookie += 'domain='+ document.domain.replace(/^(www|m)\./i, '') +'; ';
document.cookie = sCookie;
},
'_script' : function(src) {
var node = document.createElement('script');
node.setAttribute('type', 'text/javascript');
node.setAttribute('id', this._elementId);
node.setAttribute('src', src);
document.body.appendChild(node);
},
'_iframe' : function(src) {
var node = document.createElement('iframe');
node.setAttribute('id', this._elementId);
node.setAttribute('src', src);
node.style.display = 'none';
node.style.width = '0';
node.style.height = '0';
document.body.appendChild(node);
},
'save' : function() {
var src = '/exec/front/External/Save'; // 환경에 맞게 변경하여 사용
src += '?referer='+encodeURIComponent(document.referrer);
src += '&href='+encodeURIComponent(location.href);
this._script(src);
//this._iframe(src);
}
};
if (BigDataLog.getcookie()) {
BigDataLog.delcookie();
} else {
if (window.attachEvent) window.attachEvent('onload', function(){BigDataLog.save();});
else window.addEventListener('load', function(){BigDataLog.save();}, false);
}
var COLORCHIP_FRONT = {
setFrontInit : function()
{
$('.xans-product-colorchip').find('.chips').each(function() {
var sColor = COLORCHIP_FRONT.RGB2Color($(this).css('backgroundColor'));
$(this).mouseover(function() {
if (COLORCHIP_FRONT.checkValidation(sColor) === true && aOptionColorchip[sColor] != '') {
$(this).css('cursor', 'pointer');
$('.BigImage').attr('src', aOptionColorchip[sColor]);
} else {
$(this).css('cursor', '');
}
});
});
},
RGB2Color : function (sRgb)
{
try {
rgb = sRgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
if (rgb === null) {
return sRgb.toString().toUpperCase();
} else {
return '#' + COLORCHIP_FRONT.byte2Hex(rgb[1]) + COLORCHIP_FRONT.byte2Hex(rgb[2]) + COLORCHIP_FRONT.byte2Hex(rgb[3]);
}
} catch (e) {
return '';
}
},
byte2Hex : function (n)
{
var nybHexString = "0123456789ABCDEF";
return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
},
checkValidation : function(sColor)
{
var regex = /^#?[0-9A-F]{6}$/i;
return regex.test(sColor);
}
}
$(document).ready(function() {
COLORCHIP_FRONT.setFrontInit();
});
/**
* 상품 이미지 확대
*
* @package app/Shop
* @subpackage Resource
* @author 이장규
* @since 2012. 1. 19.
* @version 1.0
*
*/
var ProductImageZoom = function()
{
/**
* 확대 영역 size
* @var array 너비, 높이
*/
var aLargeRect = {'width' : 0, 'height' : 0};
/**
* 상품상세에 있는 이미지 정보
* @var array 너비, 높이
*/
var aOriImage = {'width' : 0, 'height' : 0, 'left' : 0, 'top' : 0};
/**
* 초기화 여부 mouse over 하면 true, mouse out 하면 false
* @var bool
*/
var bInit = false;
/**
* 이미지 확대 준비
*/
this.prepare = function()
{
init();
bindEvent();
out();
};
/**
* 초기화
* @returns 초기화 할 필요 없으면 return true
*/
var init = function()
{
//확대를 시작하면 초기화 필요 없음
if (bInit == true) return true;
createLargeRect();//확대영역
setZoomInfo();
createSmallRect();//작은 사각형 영역
setMouseGuide();//마우스를 올려보세요
bInit = true;
};
/**
* 확대 영역 사각형 만들기
*/
var createLargeRect = function()
{
var sImageSrc = $('.BigImage').attr('src');
var iLargeWidth = $('.BigImage').width() * 2;
var iLargeHeight = $('.BigImage').height() * 2;
if ($('#zoom_image').length < 1) {
var aOriImagePosition = $('.BigImage').offset();
var sLargeHtml = '<p class="image_zoom_large"><span class="image_zoom_large_relative"><img id="zoom_image" alt="확대 이미지" /></span></p>';
$('#zoom_wrap').append(sLargeHtml);
}
$('#zoom_image').attr('src', sImageSrc);
$('#zoom_image').css({
'width' : iLargeWidth,
'height' : iLargeHeight
});
};
/**
* member 변수 set
*/
var setZoomInfo = function()
{
//확대 사각형
aLargeRect = {'width' : $('.image_zoom_large').width(), 'height' : $('.image_zoom_large').height()};
//원본 이미지
var aOriImagePosition = $('.BigImage').offset();
if (aOriImagePosition != null) {
aOriImage = {'width' : $('.BigImage').width(), 'height' : $('.BigImage').height(), 'left' : aOriImagePosition.left, 'top' : aOriImagePosition.top};
}
};
/**
* 작은 사각형 만들기
*/
var createSmallRect = function()
{
if ($('#image_zoom_small').length < 1) {
$('body').append('<div id="image_zoom_small"></div>');
}
var iSmallWidth = (aOriImage.width * aLargeRect.width) / $('#zoom_image').width(); // 작은네모 너비 = (상품이미지 너비 * 큰이미지 너비) / 확대이미지 너비
var iSmallHeight = (aOriImage.height * aLargeRect.height) / $('#zoom_image').height();
$('#image_zoom_small').css({
'width' : iSmallWidth,
'height' : iSmallHeight
});
};
/**
* '마우스를 올려보세요' 보여주기
*/
var setMouseGuide = function()
{
var sLang = SHOP.getLanguage();
if (sLang == 'ja_JP') {
var iImgWidth = 215;
} else {
var iImgWidth = 170;
}
var sZoomImage = 'http://img.echosting.cafe24.com/design/skin/admin/'+sLang+'/txt_product_zoom.gif';
if ($('#zoomMouseGiude').length < 1) {
var sGuideHtml = '<span id="zoomMouseGiude" style="display:block; position:relative; width:170px; margin:0 auto;"><img src="'+sZoomImage+'" id="zoomGuideImage" alt="'+__('마우스를 올려보세요.')+'" /></span>';
$('.BigImage').parent().append(sGuideHtml);
}
var aGuideImageSize = {'width' : iImgWidth, 'height' : 27};
$('#zoomGuideImage').css({
'position' : 'absolute',
'top' : aGuideImageSize.height * -1,
'right' : 0
});
};
/**
* event binding
*/
var bindEvent = function()
{
//브라우저 resizing 되면 위치값이 바뀜
$(window).resize(function(){
init();
out();
});
$('.BigImage, #image_zoom_small, #zoomGuideImage').bind('mousemove mouseover', function(e){
move(e);
});
$('.BigImage, #image_zoom_small').bind('mouseout', function(){
out();
});
};
/**
* 상품 이미지 밖으로 마우스 이동
*/
var out = function()
{
$('#image_zoom_small, .image_zoom_large').hide();
$('#zoomMouseGiude').show();
bInit = false;
};
/**
* 상품 이미지 내에서 마우스 이동
* @param e event
*/
var move = function(e)
{
//썸네일 이미지에 마우스를 over 하면 이미지가 바뀌기 때문에 초기화 해야 함
init();
$('#zoomMouseGiude').hide();
var aMousePosition = getMousePosition(e);
//작은 사각형 이동
$('#image_zoom_small').css({
'left' : aMousePosition.left,
'top' : aMousePosition.top,
'display' : 'block'
});
$('.image_zoom_large').show();
//확대영역 이동
$('#zoom_image').css({
'left' : (aMousePosition.left - aOriImage.left) * -2,
'top' : (aMousePosition.top - aOriImage.top) * -2
});
};
/**
* 작은 네모의 좌표 구하기
* @param e 이벤트
* @returns array left, top
*/
var getMousePosition = function(e)
{
var iSmallLeftMax = aOriImage.left + aOriImage.width - $('#image_zoom_small').outerWidth();
var iSmallTopMax = aOriImage.top + aOriImage.height - $('#image_zoom_small').outerHeight();
//마우스 커서가 작은 네모의 가운데로 가게 하기 위해
var iSmallX = e.pageX - parseInt($('#image_zoom_small').outerWidth() / 2);//작은 사각형 위치 = 마우스 X좌표 - (작은 사각형 / 2)
var iSmallY = e.pageY - parseInt($('#image_zoom_small').outerHeight() / 2);
//max 작은 사각형 위치
if (iSmallX > iSmallLeftMax) iSmallX = iSmallLeftMax;
if (iSmallY > iSmallTopMax) iSmallY = iSmallTopMax;
//min 작은 사각형 위치
if (iSmallX < aOriImage.left) iSmallX = aOriImage.left;
if (iSmallY < aOriImage.top) iSmallY = aOriImage.top;
return {'left' : iSmallX, 'top' : iSmallY};
};
};
$(document).ready(function()
{
var imageZoom = new ProductImageZoom();
imageZoom.prepare();
});
$(document).ready(function()
{
var sBigSrc = $('.BigImage').attr('src');
$('.ThumbImage').mouseover(function(index)
{
$('#prdDetailImg').attr('rel', $(this).parent().index());
var sSrc = $(this).attr('src');
if (sSrc.indexOf('/product/tiny/') > 0) {
if (sSrc.substring(sSrc.lastIndexOf('/')) == sBigSrc.substring(sBigSrc.lastIndexOf('/'))) {
sSrc = sSrc.replace('/product/tiny/','/product/big/');
} else {
sSrc = ImagePreview.eBigImgSrc;
}
$('.BigImage').attr('src',sSrc);
// 일단 복잡한 과정은 제외하고 파일 교체만 처리
} else if (sSrc.indexOf('/product/small/') > 0) {
if (sSrc.substring(sSrc.lastIndexOf('/')) == sBigSrc.substring(sBigSrc.lastIndexOf('/'))) {
sSrc = sSrc.replace('/product/small/','/product/big/');
} else {
sSrc = ImagePreview.eBigImgSrc;
}
$('.BigImage').attr('src',sSrc);
} else if (sSrc.indexOf('/thumb/') > 0) {
$('.BigImage').attr('src',ImagePreview.eBigImgSrc);
} else {
// 추가 이미지
sSrc = sSrc.replace('/product/extra/small/','/product/extra/big/');
$('.BigImage').attr('src',sSrc);
}
});
ImagePreview.eBigImgSrc = $('.BigImage').attr('src');
var bPreview = ($.data(document,'Preview') == 'T') ? true : false;
// 제일 처음 로딩시 이미지값 저장해놓음..뉴상품에서는 small == big 이지만 구상품 스킨에서는
// tiny와 big의 이미지명 틀림!!
ImagePreview.eBigImgSrc = $('.BigImage').attr('src');
if (bPreview === true) {
ImagePreview.Init();
}
});
var ImagePreview =
{
eTarget : null,
eBigImgSrc : null,
Init : function()
{
this.eTarget = $('.xans-product-image img.BigImage');
this.eTarget.parent().addClass('cloud-zoom');
this.showNotice();
ImagePreview.setZoom();
},
showNotice : function()
{
var sLang = SHOP.getLanguage();
if (sLang == 'ja_JP') {
var iImgWidth = 107;
} else {
var iImgWidth = 85;
}
var sZoomImage = 'http://img.echosting.cafe24.com/design/skin/admin/'+sLang+'/txt_product_zoom.gif';
var sLeft = this.eTarget.width() / 2 - iImgWidth;
$('<div id="zoomNotice"><img src="'+sZoomImage+'"></div>').css(
{
'height' : '0px',
'position' : 'relative',
'opacity' : '0.75',
'KHTMLOpacity' : '0.75',
'MozOpacity' : '0.75',
'filter' : 'Alpha(opacity=75)',
'top' : '-27px',
'margin-left' : sLeft
}).appendTo(this.eTarget.parent());
},
setZoom : function()
{
$('.cloud-zoom').mouseover(function()
{
$('.cloud-zoom').CloudZoom();
});
}
}
// 이전, 다음 상품 보기
function viewProduct(iProductNo)
{
var sPath = document.location.pathname;
var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
var aMatchResult = sPath.match(sPattern);
if (aMatchResult) {
var sSearchString = '';
if (location.search) {
sSearchString = '&' + location.search.replace(/\?/,'');
}
location.href = '/front/php/product.php?product_no='+iProductNo+sSearchString;
} else {
location.href = location.pathname + location.search.replace(/product_no=[\d]+/,'product_no=' + iProductNo);
}
}
// 팝업
function product_popup(sLink, sName, sOption, ele)
{
var sPath = document.location.pathname;
var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
var aMatchResult = sPath.match(sPattern);
var sSearchQuery = location.search;
if (aMatchResult) {
if (sSearchQuery) {
sSearchQuery = sSearchQuery + '&product_no=' + aMatchResult[2];
} else {
sSearchQuery = '?product_no=' + aMatchResult[2];
}
}
try {
var sDetailUri = '';
if (ele) {
var iOrder = $(ele).attr('rel');
if (window.location.href.indexOf('/surl/P/') != -1) {
sDetailUri = '?product_no=' + parseInt(window.location.href.split('/surl/P/')[1]) + '&order=' + iOrder;
} else {
sDetailUri = sSearchQuery + '&order=' + iOrder;
}
}
window.open('/' + sLink + sDetailUri, sName, sOption);
} catch (e) {
window.open('/' + sLink + sSearchQuery, sName, sOption);
}
}
$(document).ready(function(){
/**
* url에서 파라미터 가져오기
* @param string name 파라미터명
* @return string 파라미터 값
*/
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null) {
return '';
} else {
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
}
/**
* 최근상품번호 리스트 가져오기
* @param int iProductNo product_no
* @param string sCookieVal 현재 쿠키값
* @return string 기존 쿠키값에 현재 상품리스트 추가한 쿠키값
*/
function getRecentUnique(iProductNo, sCookieVal)
{
var newList = [];
var aList = sCookieVal ? sCookieVal.split('|') : [];
var iMaximumLength = 50;
for (var i = 0; i < aList.length; i++) {
var sNo = $.trim(aList[i]);
if (sNo == '' || sNo == iProductNo) continue; // 이미 있으면 skip...
newList.push(sNo);
}
newList.push(iProductNo);
if (newList.length >= iMaximumLength) {
newList = newList.slice(newList.length - iMaximumLength);
}
return newList.join('|');
}
// 최근 본 상품 쿠키 세팅하기
var sPath = document.location.pathname;
var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
var aMatchResult = sPath.match(sPattern);
if (aMatchResult) {
var iProductNo = aMatchResult[2];
} else {
var iProductNo = getParameterByName('product_no');
}
var sCookieName = 'recent_plist' + (SHOP.isDefaultShop() ? '' : EC_SDE_SHOP_NUM);
var sCookieVal = $.cookie(sCookieName);
$.cookie(sCookieName, getRecentUnique(iProductNo, sCookieVal), {
'path' : '/',
'expires' : 365
});
});
var STOCKLAYER = (function() {
var sUrl = '/product/stocklayer.html';
//세트 상품 여부
function isSetProdct()
{
if (typeof(set_option_data) === 'undefined') {
return false;
}
return true;
}
//stockLayer Element Get
function getStockLayerElement(iProductNo)
{
var sStockLayerId = 'stockLayer_' + iProductNo;
return $('#' + sStockLayerId);
}
//모든 재고 레이어 Element Get
function getAllStockLayer()
{
return $('.EC-stockLayer');
}
return {
init : function() {
$('.EC-stockdesign').click(function (e) {
var iProductNo = $(this).attr('product_no');
var $oAllStockLayer = getAllStockLayer();
$oAllStockLayer.hide();
var $oStockLayer = getStockLayerElement(iProductNo);
if ($oStockLayer.length > 0) {
$oStockLayer.show();
return;
}
var oParam = {};
oParam['product_no'] = iProductNo;
if (isSetProdct() === true) {
oParam['stockData'] = $.parseJSON(set_option_data);
oParam['is_set_product'] = 'T';
} else {
oParam['stockData'] = $.parseJSON(option_stock_data);
oParam['is_set_product'] = 'F';
}
$.ajax ({
type : 'POST',
url : sUrl,
data : oParam,
success : function(sHtml) {
sHtml = sHtml.replace(/[<]script( [^ ]+)? src=\"[^>]*>([\s\S]*?)[<]\/script>/g, "");
$('body').append(sHtml);
},
error : function(e) {
__('오류발생');
}
});
e.preventDefault();
});
},
closeStockLayer : function() {
var $oAllStockLayer = getAllStockLayer();
$oAllStockLayer.hide();
}
}
})();
$(document).ready ( function() {
STOCKLAYER.init();
});
//상품 옵션 id
var product_option_id = 'product_option_id';
$(document).ready(function(){
/**
* JS 로딩후 셀렉트 박스 활성화
* Jira : ECHOSTING-69324
*/
$('select[class^="ProductOption"]').removeAttr('disabled');
// 옵션변경
$('select[id^="'+product_option_id+'"]').unbind().change(function(){
NewProductOptionBuilder.rebuild(this);
try {
var sOptionId = $(this).attr('id');
setPrice(false, true, sOptionId);
if (isNewProductSkin() === false) {
setOldTotalPrice();
}
} catch(e) {
this.value = '*';
return false;
}
});
// 옵션추가 변경 (구상품스킨)
$('select[id*="_'+product_option_id+'"]').live('change', function(){
if (isNewProductSkin() === false) {
setOldTotalPrice();
}
});
//ECHOSTING-77239 - 80113 : 배송준비중관리에서 특정된 두개의 기호가 포함된 옵션값만 깨져서 노출
// 추가입력 옵션 ; 제거
$('.input_addoption').blur(function(){
if ($(this).val().search(/;/) > -1){
alert('특수문자 ;는 입력할 수 없습니다.');
$(this).val($(this).val().replace(/;/g, ''));
}
});
});
// 뉴상품에 뉴상품 스킨인지 확인하는 메소드 (뉴상품인데 구상품인 경우에는 false)
function isNewProductSkin()
{
return $('#totalProducts').length > 0;
}
// 구스킨을 사용할경우 총 금액 계산
function setOldTotalPrice()
{
if (product_price_content == true) {
return ;
}
// 판매가 회원 공개인 경우 옵션 값 계산 필요없음!
if (sIsDisplayNonmemberPrice === 'T') {
$('#span_product_price_text').html(sNonmemberPrice);
return ;
}
var iQuantity = 1;
if (typeof($(quantity_id).val()) != 'undefined' ) {
iQuantity = parseInt($(quantity_id).val(),10);
}
var iOptionPrice = 0;
if (option_type === 'T') {
iOptionPrice = parseInt(product_price, 10);
}
var aStockData = new Array();
if (typeof(option_stock_data) != 'undefined') {
aStockData = $.parseJSON(option_stock_data);
}
// 복합형
if (option_type == 'T') {
// 일체선택형
if (item_listing_type == 'S') {
sOptionId = ITEM.getOldProductItemCode();
if (sOptionId !== false) {
iOptionPrice += (aStockData[sOptionId].option_price - product_price);
}
} else {
$('select[id^="product_option_id"][value!="*"] option:selected').each(function() {
var sOptionId = $(this).val();
if (typeof(aStockData[sOptionId]) != 'undefined' && aStockData[sOptionId].stock_price != 0) {
iOptionPrice += (aStockData[sOptionId].option_price - product_price);
}
});
}
} else if ( option_type == 'E'){ // 저장형
var iPrdPrice = SHOP_PRICE.toShopPrice(product_price);
var iOptPrice = 0;
var iTotalPrice = 0;
var sPrice = '';
$('select[id^="product_option_id"]').each(function() {
var iValNo = parseInt($(this).val());
if (isNaN(iValNo) === true) {
return;
}
iOptPrice += SHOP_PRICE.toShopPrice(aStockData[iValNo].stock_price);
});
iTotalPrice = iPrdPrice + iOptPrice;
} else {
// 단독형일때는 구상품과 다르게 품목단위로 계산이 필요함.
$('select[id^="product_option_id"][value!="*"] option:selected').each(function() {
var sOptionId = $(this).val();
if (typeof(aStockData[sOptionId]) != 'undefined' && aStockData[sOptionId].stock_price != 0) {
iOptionPrice += aStockData[sOptionId].option_price;
} else {
iOptionPrice += aStockData[sOptionId].option_price;
}
});
}
if (option_type === 'F' && iOptionPrice === 0) {
iOptionPrice = product_price;
}
if (Olnk.isLinkageType(option_type) === true) {
$('#span_product_price_text').html(SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice));
} else {
iPrice = getProductPrice(iQuantity, iOptionPrice, null, null, function(iPrice){
$('#span_product_price_text').html(SHOP_PRICE_FORMAT.toShopPrice(iPrice));
});
}
}
/**
* 뉴상품 프론트 옵션을 관리하는 객체
* 앞으로 전역으로 함수를 선언하지 말고 여기에 선언
*/
var NEWPRD_OPTION = {
DELIMITER_SEMICOLON:';',
DELIMITER_SLASH:'/',
/**
* 셀렉트 엘리먼트의 첫번째 옵션으로 변경
* @param oSelect object 셀렉트 엘리먼트 객체
*/
resetSelectElement: function(oSelect) {
if (typeof(oSelect) !== 'object' || typeof(oSelect.is) !== 'function' || oSelect.is('select') !== true) {
return false;
}
oSelect.val(oSelect.find('option:first').val());
},
/**
* 옵션 셀렉트박스의 첫번째/두번째 값인지
* @param sOptionValue 선택값
*/
isOptionSelectTitleOrDivider: function(sOptionValue) {
return ($.inArray(sOptionValue, ['*', '**']) !== -1) ? true : false;
}
};
/**
* 뉴상품 프론트 추가옵션을 관리하는 객체
* 앞으로 전역으로 함수를 선언하지 말고 여기에 선언
*/
var NEWPRD_ADD_OPTION = {
/**
* 추가옵션 리스트 리턴 (필수, 선택모두)
* @returns array 추가옵션 리스트
*/
getCurrentAddOption: function() {
var aAddOption = [];
$(".input_addoption").each(function(){
aAddOption.push($(this).val());
});
return aAddOption;
},
/**
* 현재 작성되어있는 추가옵션으로 품목에 표시할 타이틀 리턴
* @param aAddOption array 추가옵션 리스트
* @returns string 현재 작성된 추가옵션 타이틀
*/
getCurrentAddOptionTitle: function(aAddOption) {
var aAddOptionTitle = [];
$.each(aAddOption, function(iIdx, sValue){
if (!sValue) {
return true;
}
var sOptionName = add_option_name[iIdx];
var sAddOptionTitle = sOptionName+NEWPRD_OPTION.DELIMITER_SLASH+sValue;
aAddOptionTitle.push(sAddOptionTitle);
});
var delimeter = ', ';
return (aAddOptionTitle.length > 0) ? aAddOptionTitle.join(delimeter)+delimeter : '';
},
/**
* 셀렉트 엘리먼트의 첫번째 옵션으로 변경
* @param oSelect object 셀렉트 엘리먼트 객체
*/
resetSelectElement: function(oSelect) {
return NEWPRD_OPTION.resetSelectElement(oSelect);
},
/**
* 품목별 추가옵션 처리를위한 모든 추가옵션항목을 폼에 셋팅
*/
setItemAddOptionName: function(frm) {
if (!add_option_name) {
return;
}
frm.append(getInputHidden('item_add_option_name', add_option_name.join(NEWPRD_OPTION.DELIMITER_SEMICOLON)));
},
/**
* 품목별 추가옵션을 셋팅
* @param sItemCode string 품목코드
* @param sItemAddOption string 품목별 추가옵션 입력값
*/
setItemAddOption: function(sItemCode, sItemAddOption, frm) {
if (!add_option_name || !sItemAddOption) {
return;
}
var aAddOption = sItemAddOption.split(NEWPRD_OPTION.DELIMITER_SEMICOLON);
var iLength = aAddOption.length;
if (iLength < 1) {
return;
}
for (var iIdx=0; iIdx<iLength; iIdx++) {
frm.prepend(getInputHidden('item_option_add['+sItemCode+']['+iIdx+']', aAddOption[iIdx]));
}
},
/**
* 품목기반의 추가옵션타입을 사용해야하는지
* @returns bool 품목기반의 추가옵션이면 true 아니면 false
*/
isItemBasedAddOptionType: function() {
// 옵션이 없을때
if (has_option !== 'T') {
return false;
}
// 뉴스킨이 아닐때
if (isNewProductSkin() !== true) {
return false;
}
// 연동형 옵션일때 (전역:sOptionType)
if (Olnk.isLinkageType(sOptionType) === true) {
return false;
}
return true;
}
};
;(function(window){
var $ = window.$;
window.NewProductOptionBuilder = {
/*상품맵*/
$items: {},
/*옵션마크시퀀스*/
$seq: 0,
/*로컬라이징*/
STRING: {
SOLDOUT: __("품절")
},
/*품절옵션 노출여부*/
$bIsDisplaySoldoutOption: null,
/*옵션 데이터 및 노드 초기화*/
addItem: function ($piNo, $phItem) {
this.$items[$piNo] = $phItem;
if ($phItem.option_type == 'T' && $phItem.item_listing_type == 'S') {
$phItem.map = {};
this._mining($phItem);
}
},
/*세트추가상품데이터구조 구 데이터 호환처리*/
_addItemLegacy: function () {
var $aDataList = [];
if (window.set_option_data) {
$aDataList.push(set_option_data);
}
if (window.add_option_data) {
$aDataList.push(add_option_data);
}
for (var $i = 0; $i < $aDataList.length; $i++) {
var $hItemList = jQuery.parseJSON($aDataList[$i]);
for (var $k in $hItemList) {
if ($k in this.$items) continue;
var $hItem = $hItemList[$k];
if ($hItem.option_stock_data) $hItem.option_stock_data = jQuery.parseJSON($hItem.option_stock_data);
this.addItem($k, $hItem);
}
}
},
/*상품노드에 상품번호 세팅*/
_bindItemNo: function () {
$(".xans-element-.xans-record-").each(function(){
var $jitem = $(this).find('.xans-record- a[href^="/product/detail.html"], .xans-record- a[href^="/product/"]');
$jitem.each(function($i,$item){
var $iNo = (/product_no=(\d+)/.test(this.href), RegExp.$1) || (/\/(\d+)\/(\?|$)/.test(this.href), RegExp.$1);
if ($iNo) {
$(this).closest(".xans-record-").addClass("-item -item-"+$iNo).attr("data-no",$iNo);
}
});
});
$(".xans-element-.xans-product-setproduct>.xans-record-,.xans-element-.xans-product-setproduct .product>.xans-record-").each(function(){
var $jitem = $(this).find('select[id^="setproduct_option_id"]');
$jitem.each(function($i,$item){
var $iNo = (/setproduct_option_id_(\d+)_\d+/.test(this.id), RegExp.$1);
$(this).closest(".product.xans-record-,.product>.xans-record-").addClass("-item -item-"+$iNo).attr("data-no",$iNo);
});
});
$(".xans-element-.xans-product-addproduct>.xans-record-,.xans-element-.xans-product-addproduct .product>.xans-record-").each(function(){
var $jitem = $(this).find('select[id^="addproduct_option_id"]');
$jitem.each(function($i,$item){
var $iNo = (/addproduct_option_id_(\d+)_\d+/.test(this.id), RegExp.$1);
$(this).closest(".product.xans-record-,.product>.xans-record-").addClass("-item -item-"+$iNo).attr("data-no",$iNo);
});
});
$(".xans-element-.xans-myshop-optionall>.xans-record-").each(function(){
if (0 === $(this).find('a[onclick^="NewWishSetOption"]').length) {
return;
}
var $c = /modify\('(\d+)', '(\d+)'\)/.exec($(this).find('a[onclick^="NewWishSetOption"]').get(0).onclick.toString());
var $iNo = aWishProductSetData[aWishlistProductData[$c[1]].wish_list_idx][$c[2]].product_no;
var $jitem = $(this).find('select[id="set_wishlist_product_option_id1"]');
$jitem.each(function($i,$item){
$(this).closest(".xans-myshop-optionall>.xans-record-").addClass("-item -item-"+$iNo).attr("data-no",$iNo);
});
});
//장바구니
$(".xans-element-.xans-order-optionall>.xans-record-").each(function(){
if (0 === $(this).find('a[onclick^="NewBasketSetOption"]').length) {
return;
}
var $c = /modify\('(\d+)', '(\d+)'\)/.exec($(this).find('a[onclick^="NewBasketSetOption"]').get(0).onclick.toString());
var $iNo = aBasketProductSetData[aBasketProductData[$c[1]].basket_prd_no][$c[2]].product_no;
var $jitem = $(this).find('select[id="set_product_option_id1"]');
$jitem.each(function($i,$item){
$(this).closest(".xans-order-optionall>.xans-record-").addClass("-item -item-"+$iNo).attr("data-no",$iNo);
});
});
var $iNo = (/product_no=(\d+)/.test(location.href), RegExp.$1);
if (!$iNo && window.iProductNo) {
$iNo = iProductNo;
}
if ($iNo) {
$(".xans-element-.xans-product-detail,.xans-element-.xans-product-zoom").each(function(){
$(this).addClass("-item -item-"+$iNo).attr("data-no",$iNo);
});
}
},
/*상품별옵션초기화*/
_initItem: function ($peNode) {
var $jItem = $($peNode);
var $piNo = $jItem.attr("data-no");
var $hItem = this.$items[$piNo];
var $aSections = [];
$jItem.find([
'select[id="product_option_id1"]:last',
'select[id="set_wishlist_product_option_id1"]:last',
'select[id="wishlist_product_option_id1"]:last',
'select[id="set_product_option_id1"]:last',
'select[id="setproduct_option_id_'+$piNo+'_1"]:last',
'select[id="addproduct_option_id_'+$piNo+'_1"]:last',
'select[id="option_'+$piNo+'_0"]:last',
'select[id$="product_option_id1"]:last'
].join(",")).each(function($i,$item){
$aSections.push($item.id.slice(0,-1));
});
for (var $j = 0, $jval, $jlen = $aSections.length; $jval = $aSections[$j], $j < $jlen; $j++) {
var $jItemSelList = $jItem.find('select[id^="'+$jval+'"]').addClass("product-item-"+(++this.$seq)).attr("data-no",$piNo).attr("data-eid",this.$seq);
var $jItemSel1 = $jItemSelList.eq(0);
$jItemSel1.children().each(function(){
if (!/^\*+$/.test(this.value)) {
$(this).remove();
}
});
var $aLMapSorted = this._sort($hItem.map);
for (var $i = 0; $i < $aLMapSorted.length; $i++) {
//품절 옵션 노출하지 않음 && 품절 상태이면 select 품목 만들지 않음
if (this._getDisplaySoldoutOption() === false && $aLMapSorted[$i].val._isSoldout === true) {
continue;
}
if (false === $aLMapSorted[$i].val._isHide || "T" === $aLMapSorted[$i].val.is_display) {
$jItemSel1.append('<option value="' + $aLMapSorted[$i].key + '">' + $aLMapSorted[$i].key + ($aLMapSorted[$i].val._isSoldout? " ["+this.STRING.SOLDOUT+"]": "") + '</option>');
}
}
$jItemSelList.change(this._onRebuild);
$jItemSel1.change();
}
},
/*초기화!(조합형 && 품절기능)을 사용하는 경우에만 작동*/
init: function () {
this._addItemLegacy();
this._bindItemNo();
this._setDisplaySoldoutOption();
var instance = this;
$(".xans-record-.-item, .xans-product-detail.-item").each(function(){
var $iNo = $(this).attr("data-no");
if ($iNo in instance.$items && instance.$items[$iNo].map) {
instance._initItem(this);
}
});
},
/*선택옵션에 따른 하위 재설정*/
rebuild: function ($peSelNode) {
var $iNo = $($peSelNode).attr("data-no");
var $iEId = $($peSelNode).attr("data-eid");
var $item = this.$items[$iNo];
if (!$item || !$item.map) {
return;
}
/product_option_id(\d+)$/.test($peSelNode.id) ||
/^setproduct_option_id_\d+_(\d+)/.test($peSelNode.id) ||
/^addproduct_option_id_\d+_(\d+)/.test($peSelNode.id) ||
/^option_\d+_(\d+)/.test($peSelNode.id);
var $iDepth = +RegExp.$1;
if (/^option_\d+_(\d+)/.test($peSelNode.id)) {
$iDepth+= 1;
}
var $hLMap = $item.map;
var $jOptions = $("select.product-item-"+$iEId);
var $bIsSoldout = true;
$jOptions.each(function($i,$item){
if ($bIsSoldout && $i < $iDepth) {
if ($(this).val() in $hLMap) {
$hLMap = $hLMap[$(this).val()];
} else {
$bIsSoldout = false;
$(this).val("*");
}
} else {
$(this).val("*");
$(this).children().each(function(){
if (!/^\*+$/.test(this.value)) {
$(this).remove();
}
});
}
});
if ($bIsSoldout && $iDepth < $jOptions.length) {
var $col = $jOptions.eq($iDepth);
var $aLMapSorted = this._sort($hLMap);
for (var $i = 0; $i < $aLMapSorted.length; $i++) {
//품절 옵션 노출하지 않음 && 품절 상태이면 select 품목 만들지 않음
if (this._getDisplaySoldoutOption() === false && $aLMapSorted[$i].val._isSoldout === true) {
continue;
}
if (false === $aLMapSorted[$i].val._isHide || "T" === $aLMapSorted[$i].val.is_display) {
$col.append('<option value="' + $aLMapSorted[$i].key + '">' + $aLMapSorted[$i].key + ($aLMapSorted[$i].val._isSoldout? " ["+this.STRING.SOLDOUT+"]": "") + '</option>');
}
}
}
},
/*이벤트핸들러*/
_onRebuild: function (event) {
NewProductOptionBuilder.rebuild(this);
},
/*품절체크*/
_mapSoldout: function ($phMap) {
if ("O" == {}.toString.apply($phMap).slice(8,9)) {
if ("stock_number" in $phMap) {
$phMap._isSoldout = (1 > $phMap.stock_number && $phMap.use_stock) || $phMap.is_selling === "F";
} else {
for (var $k in $phMap) {
this._mapSoldout($phMap[$k]);
}
var $bSoldout = true;
var $bHide = true;
for (var $k in $phMap) {
if (("T" === $phMap[$k].is_display || false === $phMap[$k]._isHide) && false === $phMap[$k]._isSoldout) {
$bSoldout = false;
}
if ("T" === $phMap[$k].is_display || false === $phMap[$k]._isHide) {
$bHide = false;
}
}
$phMap._isSoldout = $bSoldout;
$phMap._isHide = $bHide;
}
}
},
/*데이터 조합 및 정리*/
_mining: function ($phItem) {
var $hLink = $phItem.option_value_mapper_array;
var $hInfo = $phItem.option_stock_data;
var $iOrder = 0;
for (var $k = 0; $k < $hLink.length; $k++) {
var $aPath = (""+$hLink[$k][0]).split("#$%");
var $hLMap = $phItem.map;
for (var $i = 0, $item, $ilen = $aPath.length; $item = $aPath[$i], $i < $ilen; $i++) {
if (!($item in $hLMap)) {
$hLMap[$item] = $ilen-1 == $i? $hInfo[$hLink[$k][1]]: {};
$hLMap[$item].__order = ++$iOrder;
}
$hLMap = $hLMap[$item];
}
}
this._mapSoldout($phItem.map);
},
/*소트*/
_sort: function ($ph) {
var $a = [];
for (var $k in $ph) {
if ($ph.hasOwnProperty($k)) {
if (/^(_is|__)/.test($k)) {
continue;
}
$a.push({key: $k, val: $ph[$k]});
}
}
var $hNewHash = [];
var $icol = $a.sort(function($a, $b){return $a.val.__order > $b.val.__order? 1: $a.val.__order < $b.val.__order? -1: 0;});
for (var $item, $i=0, $ilen=$icol.length; $item=$icol[$i], $i < $ilen; $i++) {
$hNewHash.push($item);
}
return $hNewHash;
},
/*품절옵션 노출여부*/
_getDisplaySoldoutOption : function() {
return this.$bIsDisplaySoldoutOption;
},
/*품절옵션 노출 설정 데이터 할당*/
_setDisplaySoldoutOption : function() {
this.$bIsDisplaySoldoutOption = typeof(bIsDisplaySoldoutOption) !== 'undefined' ? bIsDisplaySoldoutOption : true;
}
};
})(window);
$(function(){
NewProductOptionBuilder.init();
});
$(document).ready(function(){
// 파일첨부옵션 초기화
FileOptionManager.init();
});
/**
* JSON.stringify
* @param object aData JSON.stringify 할 데이터
* @return string JSON.stringify 된 데이터 반환
*/
function JSON_stringify(aData)
{
if (!$.stringify) {
// https://gist.github.com/chicagoworks/754454
jQuery.extend({
stringify: function stringify(obj) {
if ("JSON" in window) {
return JSON.stringify(obj);
}
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"' + obj + '"';
return String(obj);
} else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n];
t = typeof(v);
if (obj.hasOwnProperty(n)) {
if (t == "string") {
v = '"' + v + '"';
} else if (t == "object" && v !== null){
v = jQuery.stringify(v);
}
json.push((arr ? "" : '"' + n + '":') + String(v));
}
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
}
});
}
return $.stringify(aData);
}
/**
* FileOption
* 파일옵션 class - 파일첨부 옵션 하나당 하나씩
* @author 백충덕 <cdbaek@simplexi.com>
*/
var FileOption = function(sInputId, aParam)
{
this.aOpt = {
inputId: sInputId,
name: null,
maxLen: null,
maxSize: null,
btnDel: '<a href="#none"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/common/btn_attach_close.gif" /></a>',
btnDelSelector: 'a',
eInputFile: null
};
$.extend(this.aOpt, aParam);
var self = this;
/**
* 초기화
*/
this.init = function()
{
self.aOpt.eInputFile = $('#'+self.aOpt.inputId+':visible');
// 지정된 id를 가진 input file이 없을 경우
if (!self.aOpt.eInputFile) return false;
// 파일리스트 목록 초기화
var aFileListContainer = self._getFileListContainer(self.aOpt.inputId);
if (aFileListContainer.size() < 1) {
self.aOpt.eInputFile.parent().append('<ul id="'+self._getFileListContainerId(self.aOpt.inputId)+'"></ul>');
}
// 모바일의 경우 삭제버튼 변경
if (self._isMobileBrowser()===true) {
self.aOpt.btnDel = '<button type="button" class="btnDelete">삭제</button></li>';
self.aOpt.btnDelSelector = 'button.btnDelete';
}
};
/**
* input:file change 이벤트 핸들러
* @param object eFileInput change이벤트가 발생한 input:file
*/
this.onChange = function(eFileInput)
{
var eFile = $(eFileInput);
// 업로드 파일명
var sFileName = this._getFileName(eFile.val());
if (sFileName.length<1) return false;
var eFileList = this._getFileListContainer(eFile.attr('id'));
// 첨부파일 최대 갯수 제한
var iCntFile = eFileList.find('li').length;
if (iCntFile >= this.aOpt.maxLen) {
if (eFile.val().length>0) alert(sprintf(__('첨부파일은 최대 %s개까지만 업로드 가능합니다.'), self.aOpt.maxLen));
// MSIE
if (navigator.appVersion.indexOf('MSIE') > -1) {
eFile.replaceWith(eFile = eFile.clone(true));
} else {
eFile.val('');
}
return false;
}
// 업로드 파일리스트 추가
var eFileItem = $('<li>'+sFileName+' '+this.aOpt.btnDel+'</li>');
var sId = eFile.attr('id');
var sRequire = eFile.attr('require');
// IE8 이하에서는 display가 바뀌어도 onChange가 trigger되므로 onChange 제거
eFile.get(0).onchange = null;
eFile.css('display', 'none');
eFile.attr({
id: '',
name: this.aOpt.inputId+'[]'
});
eFileItem.append(eFile);
eFileList.append(eFileItem);
// 새 파일업로드 input 배치
var eFileNew = $('<input type="file" onchange="FileOptionManager.onChange(this)"/>');
eFileNew.attr({
id: sId,
name: sId,
require: sRequire
});
eFileList.parent().prepend(eFileNew);
// 삭제버튼 이벤트 핸들러 세팅
eFileList.find(this.aOpt.btnDelSelector).click(function(){
$(this).parent().remove();
});
};
/**
* 유효성 체크
* @return bool 유효하면 true, 아니면 false
*/
this.checkValidation = function()
{
// 파일첨부 옵션이 '필수'가 아닐 경우 OK
if (self.aOpt.eInputFile.attr('require') !== 'T') return true;
// 파일첨부 옵션이 '필수'인데 업로드 선택 파일이 없을 경우
if (self.existsFileUpload()===false) {
alert(self.aOpt.name+' '+__('파일을 업로드 해주세요.'));
self.aOpt.eInputFile.focus();
return false;
}
return true;
};
/**
* 업로드 해야할 input:file 리스트 반환
* @return array 업로드 해야할 input:file 리스트
*/
this.getInputFileUpload = function()
{
return self._getFileListContainer(self.aOpt.inputId).find('input:file:hidden');
};
/**
* 업로드 해야할 input:file이 있는지 여부 체크
* @return bool 업로드 해야할 input:file이 있으면 true, 없으면 false
*/
this.existsFileUpload = function()
{
return self.getInputFileUpload().size() > 0;
};
/*
* 파일업로드 리스트를 담을 노드 반환
* @param string sSuffix
* @return element
*/
this._getFileListContainer = function(sSuffix)
{
var sFileListId = self._getFileListContainerId(sSuffix);
return $('ul[id="'+sFileListId+'"]');
};
/**
* 파일업로드 리스트를 담을 노드의 ID 반환
* @param string sSuffix id로 사용할 suffix
* @return string 노드의 ID
*/
this._getFileListContainerId = function(sSuffix)
{
return 'ul_'+sSuffix;
};
/**
* 파일 경로에서 파일명만 추출
* @param string sFilePath 파일 경로
* @return mixed 추출된 파일명 반환, 실패시 false 반환
*/
this._getFileName = function(sFilePath)
{
sFilePath = $.trim(sFilePath);
if (sFilePath.length<1) return false;
return $.trim(sFilePath.split('/').pop().split('\\').pop());
};
/**
* 모바일 브라우저인지 체크
* @return bool 모바일 브라우저이면 true, 아니면 false 반환
*/
this._isMobileBrowser = function()
{
// 전역 isMobile 변수가 세팅되어있을 경우 isMobile 변수값 반환
if (typeof isMobile != 'undefined') {
return isMobile;
// 전역 isMobile 변수가 없을 경우 location.hostname으로 판별
} else {
return location.hostname.indexOf('m.')===0;
}
};
}
/**
* FileOptionManager
* 파일옵션 객체를 관리하는 class - 페이지 내의 파일첨부 옵션 전체를 관장
* @author 백충덕 <cdbaek@simplexi.com>
*/
var FileOptionManager = {
bIsInputFileSupport: null,
/**
* FileOption 객체 리스트
* @var object
*/
aList: {},
/**
* 초기화
* - FileOptionManager.add()를 통해 추가된 FileOption 객체 초기화 처리
*/
init: function()
{
for (var sId in this.aList) {
if (this.aList.hasOwnProperty(sId)===false) continue;
// 초기화 과정에 문제가 생긴 객체는 리스트에서 제거
if (this.aList[sId].init() === false) delete this.aList[sId];
}
},
/**
* 파일업로드용 input:file의 change 이벤트 핸들러
* @param object eFileInput change 이벤트가 발생한 input:file
*/
onChange: function(eFileInput)
{
var sId = eFileInput.id;
this.aList[sId].onChange(eFileInput);
},
/**
* 리스트에 sInputId, aOpt 파라메터로 생성한 FileOption 객체 추가
* @param string sId 고유 ID (input:file의 id로도 쓰임)
* @param object aOpt 생성 파라메터
*/
add: function(sId, aOpt)
{
this.aList[sId] = new FileOption(sId, aOpt);
},
/**
* 업로드해야 할 input:file이 있는지 체크
* @param mixed mId 업로드 해야할 파일이 있는지 체크할 FileOption id. 없거나 하나 혹은 여러개.
* @return bool 파일업로드가 있으면 true, 아니면 false
*/
existsFileUpload: function(mId)
{
var aId = this._getList(mId);
for (var i=0; i<aId.length; i++) {
var sId = aId[i];
// 업로드해야 할 파일 있음
if (this.aList[sId].existsFileUpload() === true) return true;
}
return false;
},
/**
* 유효성 체크
* @param mixed mId 유효성 체크할 FileOption id. 없거나 하나 혹은 여러개.
* @return bool 유효하면 true, 아니면 false
*/
checkValidation: function(mId)
{
var aId = this._getList(mId);
// 유효성 체크
for (var i=0; i<aId.length; i++) {
var sId = aId[i];
if (this.aList[sId].checkValidation() === false) return false;
}
return true;
},
/**
* 파일첨부 옵션 업로드 실행
* @param mixed mId 파일업로드를 실행할 FileOption id. 없거나 하나 혹은 여러개.
* @param function callback 파일업로드 완료 후 실행할 callback
*/
upload: function(mId, callback)
{
var self = this;
// mId 지정하지 않음
if (typeof mId === 'function') {
callback = mId;
mId = null;
}
var aId = this._getList(mId);
// 업로드 해야할 input:file 추출
var aFile = [];
var aMaxSize = {};
for (var i=0; i<aId.length; i++) {
var sId = aId[i];
aMaxSize[sId] = this.aList[sId].aOpt.maxSize;
this.aList[sId].getInputFileUpload().each(function(idx){
var sVal = $.trim($(this).val());
if (sVal.length < 1) return;
aFile.push({
eFile: $(this),
eParent: $(this).parent()
});
});
}
// 업로드 할 파일이 없을 경우 중지 (업로드는 성공했다고 반환)
if (aFile.length < 1) {
callback(true);
return true;
}
var sTargetName = 'iframe_add_option_file_upload';
var sAction = '/api/product/fileupload/';
// form
var form = $('<form action="'+sAction+'" method="post" enctype="multipart/form-data" style="display:none;" target="'+sTargetName+'"></form>');
$('body').append(form);
// 업로드할 input:file append
for (var i=0; i<aFile.length; i++) {
aFile[i].eFile.appendTo(form);
}
// 커맨드 지정
$('<input type="hidden" name="cmd" value="upload" />').prependTo(form);
// 파일 업로드 사이즈 한계
$('<input type="hidden" name="max_size" value="'+encodeURIComponent(JSON_stringify(aMaxSize))+'" />').prependTo(form);
// iframe
var iframe = $('<iframe src="javascript:false;" name="'+sTargetName+'" style="display:none;"></iframe>');
$('body').append(iframe);
// iframe onload(form.submit response) 이벤트 핸들러
iframe.load(function(){
var doc = this.contentWindow ? this.contentWindow.document : (this.contentDocument ? this.contentDocument : this.document);
var root = doc.documentElement ? doc.documentElement : doc.body;
var sResult = root.textContent ? root.textContent : root.innerText;
var aResult = $.parseJSON(sResult);
var mReturn = false;
if (typeof aResult==='object') {
// 업로드 성공
if (aResult.err=='') {
// 업로드 성공한 파일정보를 가져와 input:hidden의 value로 저장
for (var sId in aResult.files) {
var eInputHidden = $('#'+sId+'_hidden');
var aVal = {
title: self.aList[sId].aOpt.name,
files: []
};
for (var i=0; i<aResult.files[sId].length; i++) {
aVal.files.push({
path: aResult.files[sId][i].path,
name: aResult.files[sId][i].name
});
}
eInputHidden.val(encodeURIComponent(JSON_stringify(aVal)));
// 반환값 세팅
if (mReturn===false) mReturn = {};
mReturn[sId] = aVal;
}
// 업로드 실패
} else {
alert(aResult.err);
}
}
// file element 원래 위치로 이동
for (var i=0; i<aFile.length; i++) {
aFile[i].eFile.appendTo(aFile[i].eParent);
}
// 임시 element 삭제
form.remove();
iframe.remove();
callback(mReturn);
});
// 파일전송
form.submit();
},
/**
* 브라우저가 input file 지원여부 반환
* @return bool input file 지원시 true, 아니면 false
*/
isInputFileSupport: function()
{
if (this.bIsInputFileSupport===null) {
this.bIsInputFileSupport = true;
try {
var eInputFile = document.createElement('input');
eInputFile.type = 'file';
eInputFile.style.display = 'none';
document.getElementsByTagName('body')[0].appendChild(eInputFile);
if (eInputFile.disabled) this.bIsInputFileSupport = false;
} catch (e) {
this.bIsInputFileSupport = false;
} finally {
if (eInputFile) eInputFile.parentNode.removeChild(eInputFile);
}
}
return this.bIsInputFileSupport;
},
// 파라메터로 넘기기 위해 인코딩
encode: function(sVal)
{
return encodeURIComponent(JSON_stringify(sVal)).replace(/'/g, "%27");
},
/**
* 넘겨받은 id에 해당하는 유효한 FileOption id 리스트 반환
* @param mixed mId 리스트로 추출할 FileOption id. 없거나 하나 혹은 여러개.
* @return array 유효한 FileOption id 리스트
*/
_getList: function(mId)
{
var aId = [];
// 지정한 id가 없다면 전체대상
if (!mId) {
for (var sId in this.aList) {
if (this.aList.hasOwnProperty(sId)===false) continue;
aId.push(sId);
}
// 지정한 id가 문자열 하나
} else if (typeof mId === 'string') {
aId.push(mId);
// 지정한 id가 Array(object)
} else {
aId = mId;
}
// 뭔가 문제가 있을 경우 빈 배열 반환
if ($.isArray(aId)===false || aId.length<1) return [];
// 유효한 id만 추출
var sId = '';
var aResult = [];
for (var i=0; i<aId.length; i++) {
sId = aId[i];
if (!(sId in this.aList)) continue;
aResult.push(sId);
}
return aResult;
}
};
/**
*
*/
var iPopupCateNo = '';
var iPopupProductNo = '';
var sPopupRefdoc = '';
var sPopupsSkinCode = '';
var aPopupPageName = '';
/**
* popup open
* 팝업의 형태는 layer popup 과 window popup 두형태가 존재한다.
*/
$(document).ready(function() {
// 팝업에서 ajax 로 세션을 동시접근 방지
setTimeout(function () {
POPUP.setPopupList();
}, 1000);
});
// ECHOSTING-91093 EP 캐시문제로 기존에 PHP 에서 처리하던 부분을 ajax를 호출하여 처리하도록 합니다.
var POPUP = {
init : function ()
{
},
setPopupList : function ()
{
// r 은 메인 ep캐시 회피용 더미 파라미터
$.ajax({
url: '/exec/front/popup/AjaxMain',
type: "get",
data: {'cate_no' : iPopupCateNo, 'refdoc' : sPopupRefdoc, 'skin_code' : sPopupsSkinCode, 'page_name' : aPopupPageName, 'product_no' : iPopupProductNo, 'random_dummy' : Math.random()},
dataType: "json",
success : function (oResult) {
if (oResult.result == '0000') {
aPopupList = oResult.data;
POPUP.setPopup();
}
},
error : function () {
}
});
},
setPopup : function ()
{
if (!aPopupList) {
return ;
}
if ($.cookie('SDE_POPUP')) {
var aPopupCookie = $.cookie('SDE_POPUP').split('&');
}
// 팝업리스트를 호출하며
// 시간이 만료시간 전이며, SDE_POPUP에 쿠키값이 없는지 검사
for (var i=0; i<aPopupList.length; i++) {
if (aPopupList[i].open) {
if (this.bOpenPopup(aPopupList[i].idx, aPopupCookie)) {
open_popup(aPopupList[i]);
}
}
}
},
//회원이 그만본다고 정의한 idx를 비교
bOpenPopup: function(iIdx, aPopupCookie)
{
if (!aPopupCookie) return true;
var aCookie = [];
for (var i=0; i<aPopupCookie.length; i++) {
aCookie = aPopupCookie[i].split('=');
if (aCookie[0] == iIdx) {
// [솔업2] - 2013.11.28
// SUB-6539 오늘 하루 열지 않음 만료시간과 현재시간을 체크 하는 로직 추가
var oCookieTime = new Date(parseInt(aCookie[1]) * 1000);
var sCookieTime = new String(oCookieTime.getFullYear());
sCookieTime += (oCookieTime.getMonth() < 10) ? '0' + new String(oCookieTime.getMonth()) : new String(oCookieTime.getMonth());
sCookieTime += (oCookieTime.getDate() < 10) ? '0' + new String(oCookieTime.getDate()) : new String(oCookieTime.getDate());
sCookieTime += (oCookieTime.getHours() < 10) ? '0' + new String(oCookieTime.getHours()) : new String(oCookieTime.getHours());
sCookieTime += (oCookieTime.getMinutes() < 10) ? '0' + new String(oCookieTime.getMinutes()) : new String(oCookieTime.getMinutes());
sCookieTime += (oCookieTime.getSeconds() < 10) ? '0' + new String(oCookieTime.getSeconds()) : new String(oCookieTime.getSeconds());
var oCurrentTime = new Date();
var sCurrentTime = new String(oCurrentTime.getFullYear());
sCurrentTime += (oCurrentTime.getMonth() < 10) ? '0' + new String(oCurrentTime.getMonth()) : new String(oCurrentTime.getMonth());
sCurrentTime += (oCurrentTime.getDate() < 10) ? '0' + new String(oCurrentTime.getDate()) : new String(oCurrentTime.getDate());
sCurrentTime += (oCurrentTime.getHours() < 10) ? '0' + new String(oCurrentTime.getHours()) : new String(oCurrentTime.getHours());
sCurrentTime += (oCurrentTime.getMinutes() < 10) ? '0' + new String(oCurrentTime.getMinutes()) : new String(oCurrentTime.getMinutes());
sCurrentTime += (oCurrentTime.getSeconds() < 10) ? '0' + new String(oCurrentTime.getSeconds()) : new String(oCurrentTime.getSeconds());
if (parseInt(sCookieTime) < parseInt(sCurrentTime)) {
return true;
}
return false;
}
}
return true;
}
};
var open_popup = function(aData) {
var aSize = aData.size.split('*');
var aPos = aData.position.split('*');
var ds = aData.file.indexOf('?') == -1 ? '?' : '&';
var sUri = aData.file+ds+'idx='+aData.idx+'&type='+aData.type;
var sChildType = aData.child_type;
/**
* layer popup open
*/
this.layer_popup = function() {
var oElement = document.createElement('div');
oElement.id = 'popup_'+aData.idx;
oElement.style.position = 'absolute';
oElement.style.top = aPos[0]+'px';
oElement.style.left = aPos[1]+'px';
oElement.style.zIndex = '99';
//ECHOSTING-39168 [긴급][스타일맨]IE8 개별팝업 이슈확인요청
oElement.style.width = aSize[0]+'px';
oElement.innerHTML = '<iframe src="'+sUri+'" scrolling="no" width="'+aSize[0]+'" height="'+aSize[1]+'" frameborder="0" allowTransparency="true"></iframe>';
document.body.appendChild(oElement);
// 레이어 팝업 드래그
$('#'+oElement.id+' iframe').load(function(){
var iframeBody = $(this).contents().find('body');
iframeBody.css({'margin': 0});
if (navigator.userAgent.indexOf('MSIE') > 0) {
iframeBody.bind('contextmenu', function(){ return false; });
iframeBody.bind('selectstart', function(){ return false; });
iframeBody.bind('dragstart', function(){ return false; });
}
// ECHOSTING-91562 샘플 팝업인 경우에만 레이어팝업 리사이징
if (sChildType == 'W') {
// ECHOSTING-114699 팝업 리사이징 오류 관련 수정 로직 추가 - 2014.11.04
var bIsExistsGoogleAd = (iframeBody.find('iframe[name="google_conversion_frame"]').size() > 0) ? true : false;
if (bIsExistsGoogleAd == true) {
iframeBody.find('iframe[name="google_conversion_frame"]').attr('width', '13px');
}
var iAdjustSizeX = this.contentWindow.document.body.scrollWidth + 'px';
var iAdjustSizeY = this.contentWindow.document.body.scrollHeight + 'px';
this.style.width = iAdjustSizeX;
this.style.height = iAdjustSizeY;
iframeBody.find('.xans-popup-footer > div').css('width', (parseInt(iAdjustSizeX) - 10) + 'px');
}
iframeBody.mousedown(function(e){
var orgX = e.clientX;
var orgY = e.clientY;
iframeBody.mousemove(function(e){
oElement.style.left = (parseInt(oElement.style.left) + e.clientX - orgX) + "px";
oElement.style.top = (parseInt(oElement.style.top) + e.clientY - orgY) + "px";
});
iframeBody.mouseup(function(e){
iframeBody.unbind('mousemove');
});
iframeBody.mouseleave(function(e){
iframeBody.unbind('mousemove');
});
});
}); // end of 레이어 팝업 드래그
};
/**
* window popup open
*/
this.win_popup = function() {
try {
var popup = window.open(sUri, 'popup_'+aData.idx, 'width='+aSize[0]+', height='+aSize[1]+', top='+aPos[0]+', left='+aPos[1]+', toolbar=0, menubar=0');
popup.focus();
} catch (e) {
}
};
var aFunction = {
'W' : 'win_popup',
'L' : 'layer_popup'
};
this[aFunction[aData.type]]();
}
/**
* 어드민 기능 링커 (ADMIN TOOL LINKER)
*
* 어드민의 주요기능들을 프론트의 기능과 연동하여 사용자가 원하는 기능을 직관적으로 바로 추적할 수 있도록 한 기능.
* @ author : ulariul jung
*/
var ATL = {};
/**
* ATL 활성화
* 1 : 사용함
* 0 : 사용안함
*/
ATL.ACTIVE = 1;
/**
* 헤더 출력여부
*/
ATL.HEADER_DISPLAY = 1;
// Top Level Domain
ATL.TLD = '.cafe24.com';
//윈도우 계정일때 임시로 갈 어드민 주소
ATL.TA = '';
//어드민 오픈시
ATL.OPEN_ADMIN = 0;
//구동중인 모듈명
ATL.EXEC = '';
/**
* 헤더 처리부
*/
ATL.Header = {
//옵션
aOption : [
{key:1, name:'yes', desc:'사용함', title:'사용함으로 설정하면, 원하는 부분을 바로 수정할 수 있도록 관리자 페이지를 링크하여 줍니다. 원하는 부분의 관리자 설정과 디자인 편집을 할 수 있습니다.'},
{key:0, name:'no', desc:'사용안함', title:'사용안함으로 설정하면, 기존 쇼핑몰 화면의 각 페이지로 이동 할 수 있습니다.'}
],
//display
aDisplay : [{open_btn:'fadeIn', top:-50, margin_top:0},
{open_btn:'fadeOut', top:0, margin_top:61}],
iBodyMargin: 0,
init: function() {
var sStyle = ATL.HEADER_DISPLAY == 0 ? 'style="top:-50px"' : '';
$('<div id="front-linker" '+sStyle+'></div>').appendTo('body').html(this.html());
this.iBodyMargin = Number($('body').css('margin-top').replace('px', ''));
this.activeIntroduce();
this.activeAtl();
this.activeAdmin();
this.display();
},
//관리자기능소개
activeIntroduce: function() {
$('#front-linker .use').click(function() {
$('#front-linker #introduce').toggle();
return false;
});
$('#front-linker #introduce .hide').click(function() {
$('#front-linker #introduce ').hide();
return false;
});
},
//사용함 버튼
activeAtl: function() {
$('#front-linker .choice li').click(function() {
var iVal = $(this).find('input').val();
ATL.ACTIVE = iVal;
$('#front-linker .choice li').removeClass('selected');
$(this).addClass('selected');
ATL.Util.setOption();
});
},
//관리자바로가기 버튼
activeAdmin: function() {
$('#front-linker .admin a').click(function() {
if ( ATL.AdminPop && typeof ATL.AdminPop.document == "object") {
ATL.AdminPop.close();
}
ATL.AdminPop = window.open("/admin/php","pop","");
return false;
});
},
//iDisplay 1은 열기 0은 닫기
display: function() {
function displayNode(aDisplay) {
$('#front-linker').animate({top:aDisplay.top}, 500);
$('#front-linker .open')[aDisplay.open_btn](500);
$('body').css('margin-top', ATL.Header.iBodyMargin+aDisplay.margin_top);
}
displayNode(this.aDisplay[ATL.HEADER_DISPLAY]);
$('#front-linker .open, #front-linker .close').click(function() {
ATL.HEADER_DISPLAY = $(this).attr('class') == 'close' ? 0 : 1;
ATL.Util.setOption();
displayNode(ATL.Header.aDisplay[ATL.HEADER_DISPLAY]);
});
},
html: function() {
var aHtml = [];
aHtml.push('<div class="show-ctrl">');
aHtml.push(' <h2>Front Remocon</h2>');
aHtml.push(' <p class="admin"><a href="/admin/php" target="_blank">쇼핑몰 관리자 바로가기</a></p>');
aHtml.push(' <p class="use">');
aHtml.push(' <a href="#introduce">쇼핑몰 관리자 기능을 사용하시겠습니까?</a>');
aHtml.push(' </p>');
aHtml.push(' <p class="manual">');
aHtml.push(' <a href="http://img.echosting.cafe24.com/guide/customerManual.pdf" target="_blank">쇼핑몰 관리자 매뉴얼</a>');
aHtml.push(' </p>');
aHtml.push(' <ul class="choice">');
$(this.aOption).each(function(iNo, oItem) {
sChecked = (oItem.key == ATL.ACTIVE) ? oItem.name+' selected' : oItem.name;
aHtml.push('<li class="'+sChecked+'" title="'+oItem.title+'"><label><input type="radio" name="active" value="'+oItem.key+'" /> '+oItem.desc+'</label></li>');
});
aHtml.push(' </ul>');
aHtml.push(' <div id="introduce" style="display:none;">');
aHtml.push(' <strong class="title">쇼핑몰 관리자 기능</strong>');
aHtml.push(' <p>');
aHtml.push(' 쇼핑몰 관리자 기능이란? 관리자 페이지에 접속하지 않고도 쇼핑몰 화면에<br>');
aHtml.push(' <strong>대표운영자로 로그인 시, 원하는 부분을 바로 수정할 수 있도록 관리자 설정 페이지를<br>');
aHtml.push(' 링크 또는 디자인 편집창을 링크 해주는 기능</strong>을 말합니다. ');
aHtml.push(' </p>');
aHtml.push(' <ul>');
aHtml.push(' <li><strong>* 사용함</strong> : 관리자 설정 페이지 및 디자인 편집창 링크하여 바로 수정할 수 있습니다.</li>');
aHtml.push(' <li><strong>* 사용안함</strong> : 기존 쇼핑몰 화면의 페이지를 이동할 수 있습니다. </li>');
aHtml.push(' </ul>');
aHtml.push(' <button type="button" class="hide">레이어 닫기</button>');
aHtml.push(' <span class="edge"></span>');
aHtml.push(' </div>');
aHtml.push(' <button class="close" type="button" value="0">쇼핑몰 관리자 기능 접기</button>');
aHtml.push('</div>');
aHtml.push('<div class="hide-ctrl">');
aHtml.push(' <button class="open" type="button" value="1">열기</button>');
aHtml.push('</div>');
return aHtml.join('');
}
};
/**
* 고스트 모듈 관리 Class
*/
ATL.Ghost = {
init: function() {
$('<div id="atl-bg"></div><div id="atl-ghost"></div>').hide().appendTo('body');
$('#atl-bg').mouseenter(ATL.Ghost.close);
},
run: function(sMethod, oAttr) {
$(oAttr.node).mouseenter(function(e) {
if (ATL.ACTIVE == 0) {
return;
}
var oNode = $(this);
var iPaddingTop = Number(oNode.css('padding-top').replace('px', ''));
oCloneNode = oNode.clone().css({'margin': 0});
oPosition = oNode.offset();
$('#atl-bg, #atl-ghost').fadeIn(100);
$('#atl-ghost').html('').css({display:'block', top: (oPosition.top-6), left: oPosition.left-6, width: oNode.outerWidth(), height:(oNode.height()+iPaddingTop)}) .append(oCloneNode)
.append('<div class="disable"></div>');
if (ATL[sMethod]) {
ATL[sMethod].init(oCloneNode, sMethod, oAttr);
}
$('#atl-ghost .disable').css('opacity', 0);
});
},
close: function() {
if (ATL.OPEN_ADMIN === 0) {
$('#atl-bg, #atl-ghost').hide();
}
}
};
//메뉴
ATL.Menu = {
add: function(aMenu)
{
var aHtml = [];
$(aMenu).each(function() {
aHtml.push('<li><a href="'+this.url+'" title="'+this.title+'"><span class="bullet"></span>'+this.name+'</a></li>');
});
aHtml.push('<li class="base-menu"><a href="/disp/admin/editor/main" title="꾸미기 창을 띄워서 디자인을 상세 편집합니다"><span class="bullet"></span>디자인 편집</a></li>');
$('<div id="atl-menu"></div>').appendTo('#atl-ghost').html('<ul>'+aHtml.join('')+'</ul>').find('a').click(this.click);
// ECHOSTING-94258 프론트 링커에서 ATL 메뉴가 스크롤 따라다니도록 수정
ATL.Menu.set($(window));
$(window).scroll(function () {
ATL.Menu.set(this);
});
},
click: function(e) {
e.preventDefault();
var sHref = $(this).attr('href');
if (sHref.indexOf('/disp/admin/editor/main') > -1) {
ATL.Menu.editor();
} else {
ATL.Admin.adminOpen({name:$(this).text(), url: sHref});
}
},
/**
* @todo 모듈 인덱스 계산후 index 정의
* @doc http://wiki.simplexi.com:8080/pages/viewpage.action?pageId=61450083
*/
editor: function() {
var sUrl = document.location.pathname === '/' ? '/index.html' : document.location.pathname;
sUrl += encodeURIComponent(document.location.search);
var sModule = function() {
var sModule = $.trim(ATL[ATL.EXEC].oNode.attr('class')).split(' ');
return sModule[2].replace('xans-','').replace(/-/g, '_');
}();
var sSrc = '/disp/admin/editor/main?editorFile='+sUrl+'&type=module&key='+sModule+'&action=edit';
var pop = window.open(sSrc, 'smartDesignEditor','width=' + (screen.availWidth - 20) + 'px,height=' + (screen.availHeight - 70) + 'px, resizable=yes');
pop.focus();
},
// ECHOSTING-94258 프론트 링커에서 ATL 메뉴가 스크롤 따라다니도록 수정
set: function (obj)
{
var oGhostOffset = $('#atl-ghost').offset();
var iGhostPosY = oGhostOffset.top;
var iGhostSizeY = parseInt($('#atl-ghost').height());
var iMenuSizeY = parseInt($('#atl-menu').height());
var iScrollPosY = $(obj).scrollTop();
var iCurrentScrollPosY = iScrollPosY + 150;
var iMaxScrollPosY = iGhostPosY + iGhostSizeY - iMenuSizeY;
if (iCurrentScrollPosY < iGhostPosY) {
var iPosY = 0;
} else if (iCurrentScrollPosY > iMaxScrollPosY) {
var iPosY = iMaxScrollPosY - iGhostPosY;
} else {
var iPosY = iCurrentScrollPosY - iGhostPosY;
}
$('#atl-menu').css('top', iPosY + 'px');
}
};
/**
* 기본 UTIL 정의
*/
ATL.Util = {
setOption: function() {
$.cookie('atl_option', ATL.ACTIVE+','+ATL.HEADER_DISPLAY, {path:'/'});
},
getOption: function() {
var aOption = $.cookie('atl_option').split(',');
return {active:aOption[0], display_header:aOption[1]};
},
queryString: function(sUrl, sKey) {
var aTmpUrl = sUrl.split('?');
var aUrl = [], _aUrl = [];
aTmpUrl = aTmpUrl[1].split('&');
for (var i =0; i<aTmpUrl.length; i++) {
_aUrl = aTmpUrl[i].split('=');
aUrl[_aUrl[0]] =_aUrl[1];
}
return sKey ? aUrl[sKey] : aUrl;
}
};
/**
* 어드민 관련 기능
*/
ATL.Admin = {
init: function() {
$(this.html()).appendTo('body').find('.close').click(this.close);
},
adminOpen: function(oAttr) {
ATL.OPEN_ADMIN = 1;
$('#atl-ghost').hide().html('');
$('#atl-bg').show();
$('#atl-admin').show()
.css({top: $(window).scrollTop()+100, left: ($('body').width() / 2) - (936 / 2) })
.find('h2').html(oAttr.name);
$('#atl-admin .iframe')
.html('<iframe src="'+oAttr.url+'" frameborder="0"></iframe>')
.find('iframe').load(function() {
try { ATL[ATL.EXEC].ui($(this).contents(), $(this)); } catch (e) { }
});
},
close: function() {
ATL.OPEN_ADMIN = 0;
$('#atl-bg, #atl-admin, #atl-ghost').hide();
},
html: function() {
return '<div id="atl-admin"><h2>디자인 추가</h2><div class="iframe"></div><button type="button" class="close">닫기</button></div>';
}
};
// 1.9 UI를 제어
ATL.Ui = {
tableResize: function(oContent, aSize, iChangeSize) {
iChangeSize = iChangeSize ? iChangeSize : '100%'
var aWidthAttr = [];
for (var i =0; i<aSize.length; i++) {
aWidthAttr.push('[width="'+aSize[i]+'"]');
}
$(oContent).find('table='+aWidthAttr.join(',')).attr('width', iChangeSize);
},
//사용자가 어드민을 클릭한 후 로딩된 페이지 제어
load: function(oContent, oIframe, sSearch) {
$(oContent).find(sSearch).click(function() {
oIframe.load(function() {
ATL.Admin.close();
window.location.reload();
});
});
}
};
ATL.Module = {
//layout 모듈
layout_logotop : {name: '로고', node: '.xans-layout-logotop'},
layout_logobottom : {name:'푸터로고', node: '.xans-layout-logobottom'},
layout_bookmark : {name:'즐겨찾기', node: '.xans-layout-bookmark'},
layout_shortcut : {name:'바로가기', node: '.xans-layout-shortcut'},
//layout_shortcut : {node:'.xans-layout-shortcut', url:'/admin/php/m/set_shortcut_f.php'},
layout_search : {name:'검색 키워드', node: '.xans-layout-searchheader, .xans-layout-searchside'},
layout_productrecent : {name: '오늘 본 상품', node: '.xans-layout-productrecent'},
layout_category : {name: '분류 설정', node:'.xans-layout-category'},
layout_myshop : {name:'마이쇼핑', node:'.xans-layout-myshop'},
layout_project : {name:'기획전', node: '.xans-layout-project'},
layout_info : {name: '고객상담 안내', node:'.xans-layout-info, .xans-layout-footer'},
layout_boardinfo : {name: '전체게시판', node: '.xans-layout-boardinfo'},
layout_jointbuy : {name:'공동구매', node:'.xans-layout-jointbuy'},
//board
board_listpackage : {name:'게시판 목록', node:'.xans-board-listpackage'},
board_paging : {name:'게시판 페이징 처리', node:'.xans-board-paging'},
board_search : {name:'게시판 검색', node:'.xans-board-search'},
// mall 모듈
mall_faq : {node: '.xans-mall-faq'},
// product
product_listmain : {name:'메인페이지 상품리스트', node: '.xans-product-listmain'},
product_menupackage : {name:'상품 카테고리 헤더', node: '.xans-product-menupackage'},
product_list : {name:'카테고리 상품진열', node: '.xans-product-listrecommend, .xans-product-listnew, .xans-product-normalpackage'},
product_detail : {name:'상품상세', node: '.xans-product-detail'},
product_additional : {name:'상품상세 정보', node:'.xans-product-additional'},
product_normalpaging : {name:'일반상품 페이징', node:'.xans-product-normalpaging'},
search_form : {name:'상품검색', node:'.xans-search-form'},
jointbuy_package : {name:'공동구매', node:'.xans-jointbuy-package'},
project_package : {name:'기획전 리스트', node:'.xans-project-package'},
mall_faq :{name:'이용안내', node:'.xans-mall-faq'},
mall_company : {name:'회사소개', node:'.xans-mall-company'},
mall_term : {name:'이용약관 등록', node:'.xans-mall-term'},
mall_privacy : {name:'개인정보취급방칩', node:'.xans-mall-privacy'},
order_basketpackage :{name:'장바구니', node:'.xans-order-basketpackage'},
order_basketguide :{name:'장바구니 이용안내', node:'.xans-order-basketguide'},
order_form :{name:'주문서 작성', node:'.xans-order-form'},
order_result :{name:'주문 완료', node:'.xans-order-result'},
myshop_orderhistorylist :{name:'주문 내역 조회', node:'.xans-myshop-orderhistorylist'},
myshop_bankbook :{name:'마이 쇼핑', node:'.xans-myshop-bankbook'},
myshop_wishlist :{name:'관심상품', node:'.xans-myshop-wishlist'},
myshop_mileagehistory :{name:'적립금', node:'.xans-myshop-mileagehistorypackage'},
myshop_couponserial : {name:'쿠폰', node:'.xans-myshop-couponserial'},
myshop_couponlist : {name:'쿠폰리스트', node:'.xans-myshop-couponlist'},
myshop_boardlistsearch : {name:'1:1게시판 검색', node:'.xans-myshop-boardlistsearch'},
myshop_orderhistorydetail : {name: '주문상세내역', node:'.xans-myshop-orderhistorydetail'},
myshop_addrlist : {name:'배송주소록 관리', node:'.xans-myshop-addrlist'},
myshop_mileagecouponpackage : {name:'적립금', node:'.xans-myshop-mileagecouponpackage'},
myshop_mileageunavailpackage : {name:'미가용 적립내역보기', node:'.xans-myshop-mileageunavailpackage'},
myshop_paging : {name:'모듈 페이징', node:'.xans-myshop-orderhistorypaging, .xans-myshop-historypaging, .xans-myshop-boardpackage, .xans-myshop-unavailpaging, .xans-myshop-couponmemberpaging, .xans-myshop-couponlistpaging, .xans-myshop-wishlistpaging'},
//member
//member_join : {node: '.xans-member-join'},
footer : {name:'Temp', node: '.xans-layer-footer1211'}
};
/**
* 모듈 동작시 기본 상속 모듈
* 모듈이 구동시에 상속하는 최상위 클래스입니다.
*/
ATL.Base = {
sUrl : '',
oNode : '',
oAttr: {},
/**
* 모듈 기능 구동 초기화
* @param oNode 고스트모듈내에 clone된 모듈의 node
* @param sMethod 구동된 모델 코드
* @param oAttr 모델의 모듈 속성
*/
init: function(oNode, sMethod, oAttr) {
ATL.EXEC = sMethod;
this.oNode = $(oNode);
this.oAttr = oAttr;
this.run();
this.menu();
},
run: function() {
},
menu: function() {
ATL.Menu.add([]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
},
reload: function () {
parent.location.reload();
}
};
//로고 대응
ATL.layout_logotop = $.extend({}, ATL.Base, {});
//하단 푸터
ATL.layout_logobottom = $.extend({}, ATL.Base, {});
// 즐겨찾기
ATL.layout_bookmark = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{ url: '/disp/admin/link/bookmark', title: '즐겨찾기 정보를 입력합니다.', name:'즐겨찾기 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
$(oContent).find('div.typeNav').hide();
ATL.Ui.tableResize(oContent, [908, 800]);
ATL.Ui.load(oContent, oIframe, 'a[class="btnSubmit"]');
}
});
// 바로가기
ATL.layout_shortcut = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{ url: '/disp/admin/link/shortcut', title: '바로가기 정보를 입력합니다.', name:'바로가기 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
$(oContent).find('div.typeNav').hide();
ATL.Ui.tableResize(oContent, [908, 800]);
ATL.Ui.load(oContent, oIframe, 'a[class="btnSubmit"]');
}
});
//마이샵
ATL.layout_myshop = $.extend({}, ATL.Base, {
// [솔업2차] - 2013.12.13
// SUB-8676 메뉴 제거 요청으로 주석처리
/*
menu: function() {
var aMenu = [
{ url: '/disp/admin/manage/icon', title: '상품 아이콘을 설정합니다.', name: '상품 아이콘 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [908, 800]);
}
*/
});
//기획전
if (sProductMode == 'O') { // 구상품
ATL.layout_project = $.extend({}, ATL.Base, {});
} else {
ATL.layout_project = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{ url: '/disp/admin/product/categorymanage?exhibition=T', title: '기획전 분류를 관리합니다.', name:'기획전 분류 관리'},
{ url: '/disp/admin/product/ShowInfoExhibition', title: '기획전 상품 진열을 관리합니다.', name:'기획전 상품 진열관리'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
$(oContent).find('.typeNav').hide();
ATL.Ui.load(oContent, oIframe, '.btnSubmit');
}
});
}
//고객상담 안내
ATL.layout_info = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{ url: '/admin/php/m/company_info_f.php', title: '고객센터정보안내를 설정합니다.', name:'고객센터정보안내 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
$(oContent).find('table:eq(1)').hide();
ATL.Ui.tableResize(oContent, [908, 800]);
ATL.Ui.load(oContent, oIframe, 'a[class="btnSubmit"]');
}
});
// 검색
ATL.layout_search = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [ { url: '/admin/php/m/product_search_setting_f.php', title: '상품검색 키워드 설정 설정.', name:'상품검색 키워드 설정'} ];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.load(oContent, oIframe, 'input[alt="확인"]');
}
});
//최근본 상품
ATL.layout_productrecent = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [ { url: '/disp/admin/manage/recent', title: '최근본 상품의 개수를 설정합니다.', name:'최근본상품 개수 설정'} ];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
$(oContent).find('.typeNav').hide();
ATL.Ui.load(oContent, oIframe, '.btnSubmit');
}
});
// 카테고리 관리(전체 상품 목록)
if (sProductMode == 'O') { // 구상품
ATL.layout_category = $.extend({}, ATL.Base, {
run : function() {
$('#atl-ghost .disable').remove();
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iCateNo = ATL.Util.queryString($(this).attr('href'), 'cate_no');
ATL.Admin.adminOpen({name:'카테고리 설정', url:'/admin/php/g/category_properties.php?category_no='+iCateNo});
});
},
menu: function() {
var aMenu = [
{ url: '/admin/php/g/big_category_create.php', title: '상품 목록에 새로운 분류를 등록합니다.', name:'대분류 등록'},
{ url: '/admin/php/g/category_main_display.php', title: '메인메뉴에 노출될 분류를 설정합니다.', name:'메인메뉴 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [770]);
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_modify_02.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_entry.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_delete.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
} else { // 뉴상품
ATL.layout_category = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{ url: '/disp/admin/product/categorymanage?is_linker=1', title: '메인분류 표시상태를 변경합니다.', name:'메인분류 표시상태'},
{ url: '/disp/admin/product/ConvenienceSetting?is_linker=1', title: '메뉴보기 설정을 변경합니다.', name:'메뉴보기 설정(팝업메뉴)'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [908]);
var aBtn = [
'a[class="btnSubmit"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
}
// 전체게시판
ATL.layout_boardinfo = $.extend({}, ATL.Base, {
run : function() {
$('#atl-ghost .disable').remove();
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iBoardNo = ATL.Util.queryString($(this).attr('href'), 'board_no');
ATL.Admin.adminOpen({name:'게시판 표시순서 변경', url:'/admin/php/b/board_admin_c.php?mode=modify&board_no='+iBoardNo});
});
},
menu: function() {
var aMenu = [ { url: '/admin/php/b/board_admin_o.php', title: '메인메뉴에 노출될 분류를 설정합니다.', name:'게시판 순서변경'} ];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [670, 650, 750, 770], '98%');
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/memcon/pop_b_bg.gif"],table[background="http://img0001.echosting.cafe24.com/admin/center/newadmin/b/pop_b_bg.gif"]').hide();
$(oContent).find('.table_title_blue').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/button/but_modify_02.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/button/but_chg_order02.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//공동구매
ATL.layout_jointbuy = $.extend({}, ATL.Base, {});
// 메인상품 관리
if (sProductMode == 'O') { // 구상품
ATL.product_listmain = $.extend({}, ATL.Base, {
iDisplayNo : 0,
run : function() {
$('#atl-ghost .disable').remove();
this.iDisplayNo = Number(this.oNode.attr('class').split(' ')[2].split('-')[3]) + 1;
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
ATL.Admin.adminOpen({name:'상품 수정', url:'/admin/php/g/modify_product_f.php?product_no='+iNo});
});
},
/**
* @todo 메인상품 진열관리 메뉴는 1.9의 UI 스크립트 변경이 필요함
* @todo 메인상품 진열관리 메뉴는 1.9의 UI 스크립트 변경이 필요함
*/
menu: function() {
var aMenu = [
{ url: '/admin/php/g/new_main_product_display_f.php?display_group='+this.iDisplayNo, title: '상품을 진열하실 수 있습니다.', name:'메인상품 진열관리'},
{ url: '/admin/php/g/product_list_setting_f.php', title: '상품 목록에 표시되는 항목을 설정합니다.', name:'표시항목 관리'},
{ url: '/disp/admin/manage/icon', title: '상품목록에 나오는 아이콘을 설정합니다.', name:'상품 아이콘 설정'},
{ url: '/admin/php/g/register_product_f.php?cate_no=-1', title: '상품을 등록합니다.', name:'상품 등록'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.ec_container').width('100%');
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/memcon/pop_b_bg.gif"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_entry.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_modify_02.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
} else {
ATL.product_listmain = $.extend({}, ATL.Base, {
// ECHOSTING-94258 프론트 링커에서 뉴상품 클릭시 상품정보 수정 가능하도록 개선
iDisplayNo : 0,
run : function() {
$('#atl-ghost .disable').remove();
this.iDisplayNo = Number(this.oNode.attr('class').split(' ')[2].split('-')[3]) + 1;
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
ATL.Admin.adminOpen({name:'상품 수정', url:'/disp/admin/product/ProductRegister?product_no='+iNo});
$('#atl-admin iframe').load(function () {
$('#atl-admin').css('height', '807px')
});
});
},
menu: function() {
var aMenu = [
{ url: '/disp/admin/product/ShowInfoMain?is_linker=1', title: '상품을 진열하실 수 있습니다.', name:'상품진열 관리'},
{ url: '/disp/admin/product/ShowDisplayDefault?is_linker=1', title: '상품정보 표시를 설정합니다.', name:'상품정보표시 설정'},
{ url: '/disp/admin/manage/icon', title: '상품목록에 나오는 아이콘을 설정합니다.', name:'상품 아이콘 설정'},
{ url: '/disp/admin/product/ConvenienceSetting?is_linker=1', title: '옵션 미리보기 기능을 설정합니다.', name:'옵션 미리보기 기능'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
var aBtn = [
'a[class="btnSubmit"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
// ECHOSTING-68135 상품진열관리 레이어의 크기 조정 - 2014.05.09
var oLayerAdjustSize = {'width': '1100px', 'height': '780px'};
$('#atl-admin').css(oLayerAdjustSize);
$('#atl-admin').css('left', document.body.clientWidth / 2 - 550 + 'px');
oIframe.css(oLayerAdjustSize);
}
});
}
//category.html 페이지 카테고리 헤더
if (sProductMode == 'O') { // 구상품
ATL.product_menupackage = $.extend({}, ATL.Base, {
menu: function() {
iCateNo = ATL.Util.queryString(document.location.href, 'cate_no');
var aMenu = [
{ url: '/admin/php/g/category_design.php?category_no='+iCateNo, title: '상품 카테고리 기본설정을 수정합니다.', name:'카테고리 기본설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.table_title_blue').hide();
$(oContent).find('td[width="95"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
} else {
ATL.product_menupackage = $.extend({}, ATL.Base, {
menu: function() {
iCateNo = ATL.Util.queryString(document.location.href, 'cate_no');
var aMenu = [
{ url: '/disp/admin/product/categorymanage?category_no=' + iCateNo +'&is_linker=1', title: '분류 꾸미기를 설정합니다.', name:'분류 꾸미기'},
{ url: '/disp/admin/product/ConvenienceSetting?is_linker=1', title: '분류를 설정합니다.', name:'분류 설정'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
}
// 카테고리 상품리스트
if (sProductMode == 'O') { // 구상품
ATL.product_list = $.extend({}, ATL.Base, {
sClass : '',
run : function() {
this.sClass = this.oNode.attr('class').split(' ')[2];
$('#atl-ghost .disable').remove();
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
if (iNo) {
ATL.Admin.adminOpen({name:'상품 수정', url:'/admin/php/g/modify_product_f.php?product_no='+iNo});
}
});
},
menu: function() {
if (document.location.href.indexOf('cate_no') > -1) {
iCateNo = ATL.Util.queryString(document.location.href, 'cate_no');
} else {
var aMatch = ($(this.oNode).html()).match(/\$([a-z0-9_]+)[ ]*=[ ]*(.+)/im);
iCateNo = aMatch[2];
}
var aMenu = [];
if (this.sClass == 'xans-product-normalpackage') {
aMenu.push({url:'/admin/php/g/register_product_f.php?cate_no='+iCateNo, title:'일반상품에 상품을 등록합니다.', name:'상품 등록'});
aMenu.push({url:'/admin/php/g/normal_product_list.php?category_no='+iCateNo, title:'일반 상품을 진열관리합니다.', name:'진열관리'});
aMenu.push({url:'/admin/php/g/product_display_order_f.php?display_group=1&category_no='+iCateNo, title:'진열순서를 변경합니다.', name:'진열순서 변경'});
} else if (this.sClass == 'xans-product-listnew') {
aMenu.push({url:'/admin/php/g/new_product_list.php?category_no='+iCateNo, title:'신상품을 진열관리합니다.', name:'신상품 진열관리'});
aMenu.push({url:'/admin/php/g/product_display_order_f.php?display_group=3&category_no='+iCateNo, title:'진열순서를 변경합니다.', name:'진열순서 변경'});
} else if (this.sClass == 'xans-product-listrecommend') {
aMenu.push({url:'/admin/php/g/reco_product_list.php?category_no='+iCateNo, title:'추천상품을 진열관리합니다.', name:'진열관리'});
aMenu.push({url:'/admin/php/g/product_display_order_f.php?display_group=2&category_no='+iCateNo, title:'진열순서를 변경합니다.', name:'진열순서 변경'});
}
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.table_title_blue').hide();
$(oContent).find('td[width="95"]').hide();
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/pop_b_bg.gif"],table[background="http://img0001.echosting.cafe24.com/admin/memcon/pop_b_bg.gif"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_chg_p02.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_entry.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
} else {
ATL.product_list = $.extend({}, ATL.Base, {
sClass : '',
run : function() {
this.sClass = this.oNode.attr('class').split(' ')[2];
$('#atl-ghost .disable').remove();
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
if (iNo) {
ATL.Admin.adminOpen({name:'상품 수정', url:'/disp/admin/product/ProductRegister?product_no='+iNo});
$('#atl-admin iframe').load(function () {
$('#atl-admin').css('height', '807px')
});
}
});
},
menu: function() {
if (document.location.href.indexOf('cate_no') > -1) {
iCateNo = ATL.Util.queryString(document.location.href, 'cate_no');
} else {
var aMatch = ($(this.oNode).html()).match(/\$([a-z0-9_]+)[ ]*=[ ]*(.+)/im);
iCateNo = aMatch[2];
}
var aMenu = [];
if (this.sClass == 'xans-product-normalpackage') {
aMenu.push({url:'/disp/admin/shop1/product/ShowInfoCategory?category_no=' + iCateNo + '&display_group=1&is_linker=1', title:'추천상품을 진열관리합니다.', name:'상품진열 관리'});
aMenu.push({url:'/disp/admin/shop1/product/ShowDisplayDefault?tab_mode=list&display_mode=normal&is_linker=1', title:'상정정보표시를 설정합니다.', name:'상품정보표시 설정'});
aMenu.push({url:'/disp/admin/product/ConvenienceSetting?is_linker=1', title:'기타 편의기능을 설정합니다.', name:'기타 편의기능 설정'});
aMenu.push({url:'/disp/admin/manage/icon', title:'상품 아이콘을 설정합니다.', name:'상품 아이콘 설정'});
aMenu.push({url:'/disp/admin/product/productregister?is_linker=1', title:'상품을 등록합니다.', name:'상품 등록'});
} else if (this.sClass == 'xans-product-listnew') {
aMenu.push({url:'/disp/admin/shop1/product/ShowInfoCategory?category_no=' + iCateNo + '&display_group=3&is_linker=1', title:'추천상품을 진열관리합니다.', name:'상품진열 관리'});
aMenu.push({url:'/disp/admin/shop1/product/ShowDisplayDefault?tab_mode=list&display_mode=new&is_linker=1', title:'상정정보표시를 설정합니다.', name:'상품정보표시 설정'});
aMenu.push({url:'/disp/admin/product/ConvenienceSetting?is_linker=1', title:'기타 편의기능을 설정합니다.', name:'기타 편의기능 설정'});
aMenu.push({url:'/disp/admin/manage/icon', title:'상품 아이콘을 설정합니다.', name:'상품 아이콘 설정'});
aMenu.push({url:'/disp/admin/product/productregister?is_linker=1', title:'상품을 등록합니다.', name:'상품 등록'});
} else if (this.sClass == 'xans-product-listrecommend') {
aMenu.push({url:'/disp/admin/shop1/product/ShowInfoCategory?category_no=' + iCateNo + '&display_group=2&is_linker=1', title:'추천상품을 진열관리합니다.', name:'상품진열 관리'});
aMenu.push({url:'/disp/admin/product/ShowDisplayDefault?tab_mode=list&display_mode=reco&is_linker=1', title:'상정정보표시를 설정합니다.', name:'상품정보표시 설정'});
aMenu.push({url:'/disp/admin/product/ConvenienceSetting?is_linker=1', title:'기타 편의기능을 설정합니다.', name:'기타 편의기능 설정'});
aMenu.push({url:'/disp/admin/manage/icon', title:'상품 아이콘을 설정합니다.', name:'상품 아이콘 설정'});
aMenu.push({url:'/disp/admin/product/productregister?is_linker=1', title:'상품을 등록합니다.', name:'상품 등록'});
}
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.table_title_blue').hide();
$(oContent).find('td[width="95"]').hide();
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/pop_b_bg.gif"],table[background="http://img0001.echosting.cafe24.com/admin/memcon/pop_b_bg.gif"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_chg_p02.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_entry.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
// ECHOSTING-68135 상품진열관리 레이어의 크기 조정 - 2014.05.09
var oLayerAdjustSize = {'width': '1100px', 'height': '780px'};
$('#atl-admin').css(oLayerAdjustSize);
$('#atl-admin').css('left', document.body.clientWidth / 2 - 550 + 'px');
oIframe.css(oLayerAdjustSize);
}
});
}
ATL.product_detail = $.extend({}, ATL.Base, {
menu: function() {
var iNo = ATL.Util.queryString(document.location.href, 'product_no');
if (sProductMode == "O") { // 구상품
var aMenu = [
{url: '/admin/php/g/modify_product_f.php?product_no='+iNo, title: '해당상품의 정보를 수정합니다.', name:'상품정보 수정'},
{url : '/admin/php/g/product_detail_setting_f.php', title:'상세정보 기본표시 설정을 정의합니다.', name:'상품 표시항목 관리'},
{url : '/admin/php/m/mileage_info_f.php', title:'적립금 설정을 정의합니다.', name:'적립금 설정'},
{url : '/admin/php/m/sns_promote_f.php', title:'SNS를 통한 상품홍보를 위한 설정 페이지입니다.', name:'SNS 상품홍보 관리'},
{url : '/admin/php/m/qrcode_prd_cfg.php', title:'상품의 QR코드를 만듭니다.', name:'상품 QR코드 만들기'},
{url : '/admin/php/m/mall_manage_info_f.php', title:'상점운영 방식을 설정합니다.', name:' 상품운영 관리 설정'},
{url : '/admin/php/m/product_common_event_f.php', title:'공통이벤트 관리를 합니다.', name:'공통이벤트 관리'},
{url : '/disp/admin/newcoupon/setting', title:'쿠폰 기본설정', name:'쿠폰 기본설정'},
{url : '/admin/php/m/mall_manage_info_f.php', title:'장바구니 담기 확인창을 설정', name:'장바구니 담기 확인창 설정'}
];
} else {
var aMenu = [
{url: '/disp/admin/product/ProductRegister?product_no='+iNo + '&is_linker=1', title: '상품의 정보를 수정합니다.', name:'상품 수정'},
{url : '/disp/admin/product/ShowDisplayDetail?is_linker=1', title:'상품 정보 표시를 설정합니다.', name:'상품정보표시 설정'},
{url : '/admin/php/m/mileage_info_f.php', title:'적립금 설정을 정의합니다.', name:'적립금 설정'},
{url : '/admin/php/m/sns_promote_f.php', title:'SNS를 통한 상품홍보를 위한 설정 페이지입니다.', name:'SNS 상품홍보 관리'},
{url : '/admin/php/m/qrcode_prd_cfg.php', title:'상품의 QR코드를 만듭니다.', name:'상품 QR코드 만들기'},
{url : '/admin/php/m/mall_manage_info_f.php', title:'상점운영 방식을 설정합니다.', name:' 상품운영 관리 설정'},
{url : '/admin/php/m/product_common_event_f.php', title:'공통이벤트 관리를 합니다.', name:'공통이벤트 관리'},
{url : '/disp/admin/newcoupon/setting?is_linker=1', title:'쿠폰 기본설정', name:'쿠폰 기본설정'},
{url : '/admin/php/m/mall_manage_info_f.php', title:'장바구니 담기 확인창을 설정', name:'장바구니 담기 확인창 설정'}
];
}
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.table_title_blue').hide();
$(oContent).find('td[width="95"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_modify_02.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'input[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_s_save.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_apply.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//상품상세 기본정보
ATL.product_additional = $.extend({}, ATL.Base, {
menu: function() {
if (sProductMode == "O") { // 구상품
ATL.Menu.add([
{url : '/admin/php/m/payment_info_f.php', title:'결제 안내정보를 변경합니다.', name:'결제안내 변경'},
{url : '/admin/php/m/shipping_agreement_info_f.php', title:'배송안내를 변경합니다.', name:'배송안내 변경'},
{url : '/admin/php/m/prod_change_agreement_f.php', title:'교환안내를 변경합니다.', name:'교환안내 변경'},
{url : '/admin/php/m/shipping_info_f.php', title:'배송/반송 설정', name:'배송/반송 설정'},
]);
} else {
var iNo = ATL.Util.queryString(document.location.href, 'product_no');
ATL.Menu.add([
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1', title:'상품 상세정보를 변경합니다.', name:'상품상세정보 수정'},
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1' + '#detail', title:'상품 결제정보를 변경합니다.', name:'상품결제정보 수정'},
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1' + '#delivery', title:'배송정보를 변경합니다.', name:'배송정보 수정'},
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1' + '#detail', title:'교환 및 반품정보를 변경합니다.', name:'교환 및 반품정보 수정'},
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1' + '#detail', title:'서비스 문의 내용을 변경합니다.', name:'서비스 문의 수정'},
{url : '/admin/php/b/board_admin_c.php?mode=modify&board_no=4', title:'상품 사용 후기 설정을 변경합니다.', name:'상품 사용 후기 설정'},
{url : '/admin/php/b/board_admin_c.php?mode=modify&board_no=6', title:'상품 Q&A 설정을 변경합니다.', name:'상품 Q&A 설정'},
{url : '/disp/admin/product/ProductRegister?product_no=' + iNo + '&is_linker=1' + '#relative', title:'관련상품을 변경합니다.', name:'관련상품 수정'}
]);
}
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('table[style="border-collapse:collapse;margin-top:11"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_reset.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//상품검색
ATL.search_form = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([{url : '/admin/php/m/product_set_search_key_f.php', title:'상품검색조건을 설정합니다.', name:'상품검색조건 설정'}]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('div:first').css('width', '100%');
var aBtn = [
'input[src="http://img.cafe24.com/images/ec_admin/btn/btn_confirm_005.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//일반상품 페이징 처리
ATL.product_normalpaging = $.extend({}, ATL.Base, {});
//공동구매
ATL.jointbuy_package = $.extend({}, ATL.Base, {});
//기획전 상품리스트
if (sProductMode == 'O') { // 구상품
ATL.project_package = $.extend({}, ATL.Base, {
iDisplayNo : 0,
run : function() {
$('#atl-ghost .disable').remove();
this.iDisplayNo = Number(this.oNode.attr('class').split(' ')[2].split('-')[3]) + 1;
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
ATL.Admin.adminOpen({name:'상품 수정', url:'/admin/php/g/modify_product_f.php?product_no='+iNo});
});
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.ec_container').width('100%');
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/memcon/pop_b_bg.gif"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_setok.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_entry.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/g/but_modify_02.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
} else {
ATL.project_package = $.extend({}, ATL.Base, {
iDisplayNo : 0,
run : function() {
$('#atl-ghost .disable').remove();
this.iDisplayNo = Number(this.oNode.attr('class').split(' ')[2].split('-')[3]) + 1;
this.oNode.find('a').unbind('click').click(function(e) {
e.preventDefault();
var iNo = ATL.Util.queryString($(this).attr('href'), 'product_no');
ATL.Admin.adminOpen({name:'상품 수정', url:'/disp/admin/product/ProductRegister?product_no='+iNo});
$('#atl-admin iframe').load(function () {
$('#atl-admin').css('height', '807px')
});
});
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
var aBtn = [
'a[class="btnSubmit"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
// ECHOSTING-68135 상품진열관리 레이어의 크기 조정 - 2014.05.09
var oLayerAdjustSize = {'width': '1100px', 'height': '780px'};
$('#atl-admin').css(oLayerAdjustSize);
$('#atl-admin').css('left', document.body.clientWidth / 2 - 550 + 'px');
oIframe.css(oLayerAdjustSize);
}
});
}
// 메인상품 관리
ATL.board_listpackage = $.extend({}, ATL.Base, {
iBoardNo : 0,
run : function() {
if (document.location.href.indexOf('board_no') > -1) {
this.iBoardNo = ATL.Util.queryString(document.location.href, 'board_no');
} else {
this.iBoardNo = Number($.trim(this.oNode.attr('class')).split(' ')[2].split('-')[3]);
}
},
/**
* @todo 메인상품 진열관리 메뉴는 1.9의 UI 스크립트 변경이 필요함
*/
menu: function() {
var aMenu = [
{ url: '/admin/php/b/board_admin_c.php?mode=modify&board_no='+this.iBoardNo, title: '게시판 정보를 설정합니다.', name:'게시판 정보'},
{ url: '/disp/admin/manage/icon', title: '게시판 아이콘을 설정합니다.', name:'게시판 아이콘 설정'},
{ url: '/admin/php/shop1/b/board_admin_c_d.php?mode=modify&board_no='+this.iBoardNo, title: '디자인 구성을 설정합니다.', name:'디자인 구성'}
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.ec_container').width('100%');
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/center/newadmin/b/pop_b_bg.gif"], .table_title_blue').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/button/but_modify_02.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
ATL.board_paging = $.extend({}, ATL.Base, {});
ATL.board_search = $.extend({}, ATL.Base, {});
//상품상세 기본정보
ATL.mall_faq = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/member_info_f.php', title:'회원가입 안내정보를 변경합니다.', name:'회원가입안내 변경'},
{url : '/admin/php/m/order_info_f.php', title:'주문 안내정보를 변경합니다.', name:'주문안내 변경'},
{url : '/admin/php/m/payment_info_f.php', title:'결제 안내정보를 변경합니다.', name:'결제안내 변경'},
{url : '/admin/php/m/shipping_agreement_info_f.php', title:'배송안내를 변경합니다.', name:'배송안내 변경'},
{url : '/admin/php/m/prod_change_agreement_f.php', title:'교환안내를 변경합니다.', name:'교환안내 변경'},
{url : '/admin/php/m/shipping_info_f.php', title:'배송/반송 설정', name:'배송/반송 설정'},
{url : '/admin/php/m/change_agreement_f.php', title:'환불안내를 변경합니다.', name:'환불안내 변경'},
{url : '/admin/php/m/mileage_f.php', title:'기타안내를 변경합니다.', name:'기타안내 변경'},
{url : '/admin/php/m/member_info_f.php', title:'쇼핑몰이용안내를 변경합니다.', name:'쇼핑몰이용안내 등록'},
{url : '/admin/php/m/shipping_info_f.php', title:'배송설정을 변경합니다.', name:'배송설정'}
]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, ['73%', 770, 775, 570]);
if (oIframe.attr("src").indexOf("shipping_info_f.php") < 0) {
$(oContent).find('table:eq(1)').hide();
}
$(oContent).find('#iView').width('100%');
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_reset.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//회사소개
ATL.mall_company = $.extend({}, ATL.mall_faq, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/company_info_f.php', title:'회사소개를 등록/변경합니다.', name:'회사소개 등록'},
{url : '/admin/php/m/company_info_f.php', title:'회사약도를 등록/변경합니다.', name:'회사약도 등록'}
]);
}
});
//이용약관
ATL.mall_term = $.extend({}, ATL.mall_faq, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/mall_agree_f.php', title:'이용약관을 등록합니다.', name:'이용약관 등록'}
]);
}
});
//개인정보 취급방침
ATL.mall_privacy = $.extend({}, ATL.mall_faq, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/private_agree_f.php', title:'개인정보 취급방침 등록.', name:'개인정보취급방침 등록'}
]);
}
});
//장바구니
ATL.order_basketpackage = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/mall_manage_info_f.php', title:'장바구니 저장 기간설정을 하실 수 있습니다.', name:'장바구니 저장 기간설정'}
]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('table[style="border-collapse:collapse;margin-top:11"]').hide().end()
.find("#basket_term > tbody > tr").hide().parent().find(".basket_term").show();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_reset.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//장바구니 이용안내
ATL.order_basketguide = $.extend({}, ATL.Base, {});
//주문서 페이지
ATL.order_form = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/pay_info_f.php', title:'결제방식을 설정합니다.', name:'결제방식 설정'},
{url : '/admin/php/m/bank_info_f.php', title:'무통장입금 계좌를 설정합니다.', name:'무통장입금 계좌설정'},
{url : '/admin/php/AutoLogin/request.php?uri=http%3A%2F%2Fbm-svc.cafe24.com%2Fframe%2Fpg%2F', title:'카드/계좌이체 신청하기 페이지입니다.', name:'카드/계좌이체 신청관리'},
{url : '/admin/php/AutoLogin/request.php?uri=http%3A%2F%2Fbm-svc.cafe24.com%2Fframe%2Fpg%2Fmobilians%2F%3Furl%3Dindex', title:'휴대폰결제 신청/관리합니다.', name:'휴대폰결제 신청/관리'},
//{url : 'http://bm-svc.cafe24.com/frame/pg/escrow/', title:'에스크로 신청/관리', name:'에스크로 신청/관리'},
{url : '/admin/php/AutoLogin/request.php?uri=http%3A%2F%2Fbm-svc.cafe24.com%2Fframe%2Fpg%2Fusafe%2F', title:'전자보증 신청/관리', name:'전자보증 신청/관리'},
{url : '/admin/php/m/ord_add_f.php', title:'주문추가항목 설정', name:'주문추가항목 설정'}
]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('table[style="border-collapse:collapse;margin-top:11"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_reset.gif"]',
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_setok.gif"]',
'img[src="http://img.cafe24.com/images/ec_admin/btn/btn_019.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//주문완료
ATL.order_result = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([
{url : '/admin/php/m/shipping_info_f.php', title:'배송기간을 설정합니다.', name:'배송기간 설정'}
]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/center/newadmin/m/but_setok.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//장바구니
ATL.myshop_orderhistorylist = $.extend({}, ATL.Base, {});
//마이쇼핑 첫페이지
ATL.myshop_bankbook = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([{url : '/admin/php/m/mileage_info_f.php', title:'적립금 정보를 설정합니다.', name:'적립금 설정'},
{url:'/admin/php/c/member_admin_c_f.php', title:'회원등급을 설정합니다.', name:'회원등급 설정'}]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [770]);
var aBtn = ['img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]'];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//위시 리스트
ATL.myshop_wishlist = $.extend({}, ATL.Base, {});
// 적립금
ATL.myshop_mileagehistory = $.extend({}, ATL.Base, {
menu: function() {
ATL.Menu.add([{url : '/admin/php/m/mileage_info_f.php', title:'적립금 정보를 설정합니다.', name:'적립금 설정'}]);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [770]);
var aBtn = ['img[src="http://img0001.echosting.cafe24.com/admin/center/m/but_blue_confirm.gif"]'];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//쿠폰
ATL.myshop_couponserial = $.extend({}, ATL.Base, {
menu: function() {
var aMenu = [
{url: '/disp/admin/newcoupon/setting', title: '쿠폰의 기본설정을 합니다.', name:'쿠폰 기본설정'},
{url: '/disp/admin/Newcoupon/serialCreate', title:'시리얼쿠폰을 생성합니다.', name:'시리얼쿠폰 만들기' },
{url: '/disp/admin/newcoupon/serialIssueInquiry', title:'시리얼쿠폰을 발급 및 조회합니다.', name:'시리얼쿠폰 발급/조회' }
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
var aBtn = [
'a[class="btnSubmit"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//쿠폰리스트
ATL.myshop_couponlist = $.extend({}, ATL.Base, {});
ATL.myshop_boardpackage = $.extend({}, ATL.Base, {
///admin/php/b/board_admin_c.php?mode=modify&board_no=9&board_group_name=1:1 상담
/**
* @todo 메인상품 진열관리 메뉴는 1.9의 UI 스크립트 변경이 필요함
* @todo 메인상품 진열관리 메뉴는 1.9의 UI 스크립트 변경이 필요함
*/
menu: function() {
var aMenu = [
{ url: '/admin/php/b/board_admin_c.php?mode=modify&board_no=9', title: '게시판을 설정합니다.', name:'게시판 설정'},
{url: '/admin/php/b/board_admin_c_d.php?mode=modify&board_no=9', title:'게시판 디자인을 구성합니다.', name:'디자인 구성' }
];
ATL.Menu.add(aMenu);
},
ui: function(oContent, oIframe) {
ATL.Ui.tableResize(oContent, [750, 770]);
$(oContent).find('.ec_container').width('100%');
$(oContent).find('.table_title_blue').hide();
$(oContent).find('table[background="http://img0001.echosting.cafe24.com/admin/center/newadmin/b/pop_b_bg.gif"]').hide();
var aBtn = [
'img[src="http://img0001.echosting.cafe24.com/admin/button/but_modify_02.gif"]'
];
ATL.Ui.load(oContent, oIframe, aBtn.join(','));
}
});
//1:1게시판 검색
ATL.myshop_boardlistsearch = $.extend({}, ATL.Base, {});
//배송 주소록 관리
ATL.myshop_addrlist = $.extend({}, ATL.Base, {});
//주문 상세내역
ATL.myshop_orderhistorydetail = $.extend({}, ATL.Base, {});
//미가용 쿠폰 / 회원적립내역
ATL.myshop_mileagecouponpackage = $.extend({}, ATL.Base, {});
//미가용 적립내역보기
ATL.myshop_mileageunavailpackage = $.extend({}, ATL.Base, {});
ATL.myshop_paging = $.extend({}, ATL.Base, {});
/**
* 어드민 툴 링커 기능 구동
*/
$(document).ready(function() {
//브라우저 ie6,7은 구동되지 않음.
if ($.browser.msie === true && Number($.browser.version) <= 6) {
return;
}
// 쿠키는 서버사이드에서 구워 놓으며, 있다면 EP등의 영향이 아니라고 판단함.
if (!$.cookie('atl_epcheck')) {
return;
}
// .cafe24.com 도메인에서만 구동된다.
if (document.domain.indexOf(ATL.TLD) === -1) {
return;
}
// Admin '쇼핑몰관리자기능사용'을 사용안함으로 선택한 경우 구동되지 않음.
if (DB_ACTIVE == 'F') {
return;
}
try {
// 상위 페이지가 존재하는 경우 (즉, 현재 페이지가 iframe인 경우에는 어드민 툴 링커 기능 구동 안함)
if (window.parent != window) {
return ;
}
} catch (e) {
}
//ECHOSTING-19219 /link/bookmark.html 추가함.
//ECHOSTING-28795 /estimate/print.html 추가함.
//ECHOSTING-29514 /myshop/coupon/coupon_product_list.html 추가함.
function isAllowPage() {
// 정규 표현식 or 문자열로 수정 허용하지 않을 폴더 or 파일 설정
var aProtectedPages = [/\/protected\/.*/, /\/myshop\/order\/print\/.*/,
'/front/php/myshop/myshop_orders_detail_print2.php',
/\/popup\/.*/, '/estimate/userform.html','/estimate/print.html', /\/product\/recommend_mail\.html.*/,
'/link/shortcut.html','/link/bookmark.html','/myshop/coupon/coupon_product_list.html', /\/myshop\/addr_popup\/.*/,
/\/product\/image_zoom.html.*/, '/poll/poll_result.html', '/order/pg_success.html',
/\/coupon\/coupon_select.html.*/, /\/myshop\/order\/issue\/tax.html.*/,
'/shopinfo/urgency.html','/urgency/urgency.html','/product/search_board_list.html', /\/myshop\/order\/issue\/cash.html.*/,
/\/calendar\/calendar_write.html.*/];
var sPath = location.pathname;
for (var i =0; i < aProtectedPages.length; i++) {
if (sPath.match(aProtectedPages[i]) != null) return false;
}
return true;
}
//허용하지 않는 페이지는 구동하지 않는다.
if (isAllowPage() === false) {
return;
}
// 기본 환경 설정 쿠키 저장
if (!$.cookie('atl_option')) {
ATL.Util.setOption();
}
var oOption = ATL.Util.getOption();
ATL.ACTIVE = oOption.active;
ATL.HEADER_DISPLAY = oOption.display_header;
// 상위 레이어 초기화
ATL.Header.init();
// 고스트 초기화
ATL.Ghost.init();
// 어드민 바로가기 초기화
ATL.Admin.init();
/**
* Front 모듈을 기준으로 어드민 툴 링커를 구동합니다.
*/
for (k in ATL.Module) {
ATL.Ghost.run(k, ATL.Module[k]);
}
});
/**
* 접속통계 & 실시간접속통계
*/
$(document).ready(function(){
// 이미 weblog.js 실행 되었을 경우 종료
if ($('#log_realtime').length > 0) {
return;
}
/*
* QueryString에서 디버그 표시 제거
*/
function stripDebug(sLocation)
{
if (typeof sLocation != 'string') return '';
sLocation = sLocation.replace(/^d[=]*[\d]*[&]*$/, '');
sLocation = sLocation.replace(/^d[=]*[\d]*[&]/, '');
sLocation = sLocation.replace(/(&d&|&d[=]*[\d]*[&]*)/, '&');
return sLocation;
}
// realconn & Ad aggregation
var _aPrs = new Array();
_sUserQs = window.location.search.substring(1);
_sUserQs = stripDebug(_sUserQs);
_aPrs[0] = 'rloc='+escape(document.location);
_aPrs[1] = 'rref='+escape(document.referrer);
_aPrs[2] = 'udim='+window.screen.width+'*'+window.screen.height;
_aPrs[3] = 'rserv='+aLogData.log_server2;
if (aLogData.log_debug == 'T') _aPrs[4] = 'd';
// 모바일웹일 경우 추가 파라미터 생성
var _sMobilePrs = '';
if (mobileWeb === true) _sMobilePrs = '&mobile=T&mobile_ver=new';
_sUrlQs = _sUserQs + '&' + _aPrs.join('&') + _sMobilePrs;
var _sUrlFull = '/exec/front/realconn/main/?'+_sUrlQs;
var node = document.createElement('iframe');
node.setAttribute('src', _sUrlFull);
node.setAttribute('id', 'log_realtime');
document.body.appendChild(node);
if (aLogData.log_debug == 'T') {
$('#log_realtime').css({'display':'block','width':'100%','height':'450px'});
} else {
$('#log_realtime').css({'display':'none','width':'0','height':'0'});
}
// eclog2.0, eclog1.9
var sTime = new Date().getTime();//ECHOSTING-54575
var sScriptSrc = 'http://'+aLogData.log_server1+'/weblog.js?uid='+aLogData.mid+'&uname='+aLogData.mid+'&r_ref='+document.referrer;
if (mobileWeb === true) sScriptSrc += '&cafe_ec=mobile';
sScriptSrc+= '&t='+sTime;//ECHOSTING-54575
var node = document.createElement('script');
node.setAttribute('type', 'text/javascript');
node.setAttribute('src', sScriptSrc);
node.setAttribute('id', 'log_script');
document.body.appendChild(node);
});
/**
* 비동기식 데이터 정의 회원로그인 정보 / 최근 본 상품
*/
var methods =
{
Basketcnt : function(aData)
{
$('.xans-layout-orderbasketcount span a').html(aData);
},
Couponcnt : function(aData)
{
$('.xans-layout-myshopcouponcount').html(aData);
},
member : function(output)
{
try {
var output = decodeURIComponent(output);
if ( AuthSSLManager.isError(output) == true ) {
alert(output);
return;
}
var aData = AuthSSLManager.unserialize(output);
var fk = '';
for ( var k in aData) {
$('.xans-member-var-' + k).html(aData[k]);
}
} catch(e) {}
},
recent : function(aData)
{
aNodes = $('.xans-layout-productrecent .xans-record-');
var iRecordCnt = aNodes.length;
var iCheckCnt = 0;
for ( var i = 0 ; i < aData.length ; i++) {
if (!aNodes[i]) {
$(aNodes[iRecordCnt - 1]).clone().appendTo($(aNodes[iRecordCnt - 1]).parent());
iCheckCnt++;
}
}
if (iCheckCnt>0){
aNodes = $('.xans-layout-productrecent .xans-record-');
}
if (aData.length > 0) {
$('.xans-layout-productrecent').show();
}
for ( var i = 0 ; i < aData.length ; i++) {
replaceHtml(aNodes[i], aData[i]);
}
// 종료 카운트 지정
if (aData.length < aNodes.length) {
iLength = aData.length;
deleteNode();
}
recentBntInit();
/**
* 패치되지 않은 노드를 제거
*/
function deleteNode()
{
for ( var i = iLength ; i < aNodes.length ; i++) {
$(aNodes[i]).remove();
}
}
function replaceHtml(oNode, aData)
{
var sHtml = $(oNode).html().replace('about:blank', aData.recent_img).replace('##param##', aData.param).replace('##name##',aData.name);
$(oNode).html(sHtml);
if (aData.disp_recent === true) {
$(oNode).removeClass('displaynone');
}
}
function recentBntInit()
{
// 화면에 뿌려진 갯수
var iDisplayCount = 0;
// 보여지는 style
var sDisplay = '';
var iIdx = 0;
//
var iDisplayNoneIdx = 0;
var nodes = $('.xans-layout-productrecent .xans-record-').each(function()
{
sDisplay = $(this).css('display');
if (sDisplay != 'none') {
iDisplayCount++;
} else {
if (iDisplayNoneIdx == 0) {
iDisplayNoneIdx = iIdx;
}
}
iIdx++;
});
var iRecentCount = nodes.length;
var bBtnActive = iDisplayCount > 0;
$('.xans-layout-productrecent .prev').unbind('click').click(function()
{
if (bBtnActive !== true) return;
var iFirstNode = iDisplayNoneIdx - iDisplayCount;
if (iFirstNode == 0 || iDisplayCount == iRecentCount) {
alert(__('최근 본 첫번째 상품입니다.'));
return;
} else {
iDisplayNoneIdx--;
$(nodes[iDisplayNoneIdx]).hide();
$(nodes[iFirstNode - 1]).removeClass('displaynone');
$(nodes[iFirstNode - 1]).fadeIn('fast');
}
}).css(
{
cursor : 'pointer'
});
$('.xans-layout-productrecent .next').unbind('click').click(function()
{
if (bBtnActive !== true) return;
if ( (iRecentCount ) == iDisplayNoneIdx || iDisplayCount == iRecentCount) {
alert(__('최근 본 마지막 상품입니다.'));
} else {
$(nodes[iDisplayNoneIdx]).fadeIn('fast');
$(nodes[iDisplayNoneIdx]).removeClass('displaynone');
$(nodes[ (iDisplayNoneIdx - iDisplayCount)]).hide();
iDisplayNoneIdx++;
}
}).css(
{
cursor : 'pointer'
});
}
}
}
$(document).ready(
function()
{
$('.xans-layout-productrecent').hide();
var aNodes = $('.xans-layout-statelogon, .xans-layout-logon');
var aModule = [];
if (aNodes.length > 0) {
aModule.push('member');
}
aNodes = $('.xans-layout-productrecent .xans-record-');
var iRecordCnt = aNodes.length;
if (iRecordCnt > 0) {
aModule.push('recent');
}
// 장바구니 수량
aNodesBasket = $('.xans-layout-orderbasketcount');
if (aNodesBasket.length > 0) {
aModule.push('Basketcnt');
}
// 쿠폰 갯수(Myshop: 마이페이지)
aNodesCoupon = $('.xans-myshop-bankbook, .xans-layout-myshopcouponcount');
if (aNodesCoupon.length > 0) {
aModule.push('Couponcnt');
}
if (aModule.length == 0) { return; }
// 에디터에서 접근했을 경우 임의의 상품 지정
var sEditor = '';
try {
if (bEditor === true) {
sEditor = '&PREVIEW_SDE=1';
}
} catch(e) { }
$.ajax(
{
url : '/exec/front/manage/async?module=' + aModule.join(',')+sEditor,
dataType : 'json',
success : function(aData)
{
for ( var k in aData) {
if (k == "member"){
AuthSSLManager.weave({
'auth_mode' : 'decryptClient',
'auth_string' : aData[k],
'auth_callbackName' : 'methods.member'
});
}else{
methods[k](aData[k]);
}
}
}
});
});
/**
* 상품상세 섬네일 롤링
*/
$(document).ready(function(){
$.fn.prdImg = function(parm){
var index = 0;
var target = parm.target;
var view = parm.view;
var listWrap = target.find('.xans-product-addimage');
var limit = listWrap.find('> ul > li').length;
var ul = target.find('.xans-product-addimage > ul');
var liFirst = target.find('.xans-product-addimage > ul > li:first-child');
var liWidth = parseInt(liFirst.width());
var liHeight = parseInt(liFirst.height());
var blockWidth = liWidth + parseInt(liFirst.css('marginRight')) + parseInt(liFirst.css('marginLeft'));
var columWidth = blockWidth * view;
var colum = Math.ceil(limit / view);
var roll = {
init : function(){
function struct(){
var ulWidth = limit * parseInt(blockWidth);
listWrap.append('<button type="button" class="prev">이전</button>');
listWrap.append('<button type="button" class="next">다음</button>');
ul.css({'position':'absolute', 'left':0, 'top':0, 'width':ulWidth});
listWrap.find('> ul > li').each(function(){
$(this).css({'float':'left'});
});
listWrap.css({'position':'relative', 'height':liHeight});
var prev = listWrap.find('.prev');
var next = listWrap.find('.next');
prev.click(function(){
if(index > 0){
index --;
}
roll.slide(index);
});
next.click(function(){
if(index < (colum-1) ){
index ++;
}
roll.slide(index);
});
if(index == 0){
prev.hide();
} else {
prev.show();
}
if(index >= (colum-1)){
next.hide();
} else {
next.show();
}
}
if(limit > view){
struct();
}
},
slide : function(index){
var left = '-' + (index * columWidth) +'px';
var prev = listWrap.find('.prev');
var next = listWrap.find('.next');
if(index == 0){
prev.hide();
} else {
prev.show();
}
if(index >= (colum-1)){
next.hide();
} else {
next.show();
}
ul.stop().animate({'left':left},500);
}
}
roll.init();
};
// 함수호출 : 상품상세 페이지
$.fn.prdImg({
target : $('.xans-product-image'),
view : 5
});
// 함수호출 : 상품확대보기팝업
$.fn.prdImg({
target : $('.xans-product-zoom'),
view : 5
});
});
/**
* 상품상세 사용후기
*/
$(document).ready(function(){
$('.xans-product-review a').click(function(e) {
e.preventDefault();
var no = $(this).attr('href').replace(/(\S*)no=(\d+)(\S*)/g, '$2');
var $obj = $('#product-review-read_'+no);
//로드된 엘리먼트 존재 체크
if ($obj.length > 0) {
if ($obj.css('display') =='none') {
$obj.show();
} else {
$obj.hide();
}
return;
}
REVIEW.getReadData($(this));
});
});
var PARENT = '';
var OPEN_REVIEW = '';
var REVIEW = {
getReadData : function(obj, eType)
{
if (obj != undefined) {
PARENT = obj;
var sHref = obj.attr('href');
var pNode = obj.parents('tr');
var pass_check = '&pass_check=F';
} else {
var sHref = PARENT.attr('href');
var pNode = PARENT.parents('tr');
var pass_check = '&pass_check=T';
}
var sQuery = sHref.split('?');
var sQueryNo = sQuery[1].split('=');
if (OPEN_REVIEW == sQueryNo[1]) {
$('#product-review-read').remove();
OPEN_REVIEW = '';
return false;
} else {
OPEN_REVIEW = sQueryNo[1];
}
$.ajax({
url : '/exec/front/board/product/4?'+sQuery[1]+pass_check,
dataType: 'json',
success: function(data) {
$('#product-review-read').remove();
var sPath = document.location.pathname;
var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
var aMatchResult = sPath.match(sPattern);
if (aMatchResult) {
var iProductNo = aMatchResult[2];
} else {
var iProductNo = getQueryString('product_no');
}
var aHtml = [];
//읽기 권한 체크
if (false === data.read_auth && eType == undefined) {
alert(decodeURIComponent(data.alertMSG));
//로그인페이지 이동
if (data.returnUrl != undefined) {
location.replace("/member/login.html?returnUrl=" + data.returnUrl);
}
return false;
}
if (data.is_secret == true) {
// 비밀글 비밀번호 입력 폼
aHtml.push('<form name="SecretForm_4" id="SecretForm_4">');
aHtml.push('<input type="text" name="a" style="display:none;">');
aHtml.push('<div class="view"><p>비밀번호 <input type="password" id="secure_password" name="secure_password" onkeydown="if (event.keyCode == 13) '+data.action_pass_submit+'"> <input type="button" value="확인" onclick="'+data.action_pass_submit+'"></p></div>');
aHtml.push('</form>');
} else {
// 글 내용
if (data.read['content_image'] != null) {
var sImg = data.read['content_image'];
} else {
var sImg = '';
}
aHtml.push('<div class="view">');
aHtml.push('<p>'+data.read['content']+'</p>');
aHtml.push('<p>'+sImg+'</p>');
aHtml.push('<p class="btnArea">');
if (data.write_auth == true) {
aHtml.push('<a href="/board/product/modify.html?board_act=edit&no='+data.no+'&board_no=4&link_product_no='+iProductNo+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/btn_board_modify.gif" alt="게시글 수정하기" /></a>');
}
aHtml.push('</p>');
aHtml.push('</div>');
// 댓글리스트
if (data.comment != undefined && data.comment.length != undefined) {
aHtml.push('<ul class="boardComment">');
for (var i=0; data.comment.length > i; i++) {
//댓글리스트
if (data.comment[i]['comment_reply_css'] == undefined) {
aHtml.push('<li>');
aHtml.push('<strong class="name">'+data.comment[i]['member_icon']+' '+data.comment[i]['comment_name']+'</strong>');
aHtml.push('<span class="date">'+data.comment[i]['comment_write_date']+'</span>');
aHtml.push('<span class="grade '+data.use_point+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/ico_point'+data.comment[i]['comment_point_count']+'.gif" alt="'+data.comment[i]['comment_point_count']+'점" /></span>');
if (data.comment[i]['comment_reply_display'] == true) {
aHtml.push('<span class="button">'+'<a href="#none" onclick="'+data.comment[i]['action_comment_reply']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_reply.gif" alt="댓글" /></a>'+'</span>');
}
aHtml.push('<p class="comment">'+data.comment[i]['comment_icon_lock']+' '+data.comment[i]['comment_content']+'</p>');
aHtml.push('</li>');
} else {
//댓글의 댓글리스트
aHtml.push('<li class="replyArea">');
aHtml.push('<strong class="name">'+data.comment[i]['member_icon']+' '+data.comment[i]['comment_name']+'</strong>');
aHtml.push('<span class="date">'+data.comment[i]['comment_write_date']+'</span>');
aHtml.push('<p class="comment">'+data.comment[i]['comment_icon_lock']+' '+data.comment[i]['comment_content']+'</p>');
aHtml.push('</li>');
}
}
aHtml.push('</ul>');
}
// 댓글쓰기
if (data.comment_write != undefined) {
aHtml.push('<form name="commentWriteForm_4'+data.key+'" id="commentWriteForm_4'+data.key+'">');
aHtml.push('<div class="memoCont">');
aHtml.push('<div class="writer">');
aHtml.push('<p class="user"><span class="nameArea">이름 '+data.comment_write['comment_name']+' 비밀번호 '+data.comment_write['comment_password']);
if (data.comment_write['comment_secret_display'] == true) {
aHtml.push('<label class="secret">'+data.comment_write['secure']+' 비밀댓글</label>');
}
aHtml.push('</span>');
aHtml.push(''+data.comment_write['comment']+'<a href="#none" onclick="'+data.comment_write['action_comment_insert']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_comment_submit.gif" alt="확인" /></a></p>');
aHtml.push('<p class="rating '+data.comment_write['use_point']+'">'+data.comment_write['comment_point']+'</p>');
aHtml.push('<p class="text '+data.comment_write['use_comment_size']+'">'+data.comment_write['comment_byte']+' / '+data.comment_write['comment_size']+' byte</p>');
aHtml.push('<p class="captcha '+data.comment_write['use_captcha']+'">'+data.comment_write['captcha_image']+data.comment_write['captcha']+'<img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/ico_information.gif" alt="" /> 왼쪽의 문자를 공백없이 입력하세요.(대소문자구분)</p>');
aHtml.push('</div>');
aHtml.push('</div>');
aHtml.push('</form>');
}
// 댓글의 댓글쓰기
if (data.comment_reply != undefined) {
aHtml.push('<form name="commentReplyWriteForm_4'+data.key+'" id="commentReplyWriteForm_4'+data.key+'" style="display:none">');
aHtml.push('<div class="memoCont reply">');
aHtml.push('<div class="writer">');
aHtml.push('<p class="user"><span class="nameArea">이름 '+data.comment_reply['comment_name']+' 비밀번호 '+data.comment_reply['comment_password']);
if (data.comment_reply['comment_secret_display'] == true) {
aHtml.push('<label class="secret">'+data.comment_reply['secure']+' 비밀댓글</label>');
}
aHtml.push('</span>');
aHtml.push(''+data.comment_reply['comment']+'<a href="#none" onclick="'+data.comment_reply['action_comment_insert']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_comment_submit.gif" alt="확인" /></a></p>');
aHtml.push('<p class="text '+data.comment_reply['use_comment_size']+'">'+data.comment_reply['comment_byte']+' / '+data.comment_reply['comment_size']+' byte</p>');
aHtml.push('<p class="captcha '+data.comment_reply['use_captcha']+'">'+data.comment_reply['captcha_image']+data.comment_reply['captcha']+'<img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/ico_information.gif" alt="" /> 왼쪽의 문자를 공백없이 입력하세요.(대소문자구분)</p>');
aHtml.push('</div>');
aHtml.push('</div>');
aHtml.push('</form>');
}
// 비밀댓글 확인
if (data.comment_secret != undefined) {
aHtml.push('<form name="commentSecretForm_4'+data.key+'" id="commentSecretForm_4'+data.key+'" style="display:none">');
aHtml.push('<div class="commentSecret">');
aHtml.push('<p>비밀번호 : '+data.comment_secret['secure_password']);
aHtml.push(' <a href="#none" onclick="'+data.comment_secret['action_secret_submit']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_submit.gif" alt="확인" /></a>');
aHtml.push(' <a href="#none" onclick="'+data.comment_secret['action_secret_cancel']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_cancel.gif" alt="취소" /></a></p>');
aHtml.push('</div>');
aHtml.push('</form>');
}
}
$(pNode).after('<tr id="product-review-read'+data.key+'"><td colspan="6">'+aHtml.join('')+'</td></tr>');
// 평점기능 사용안함일 경우 보여지는 td를 조절하기 위한 함수
PRODUCT_COMMENT.comment_colspan(pNode);
if (data.comment_write != undefined && data.comment_write['use_comment_size'] == '') PRODUCT_COMMENT.comment_byte(4, data.key);
if (data.comment_reply != undefined && data.comment_write['use_comment_size'] == '') PRODUCT_COMMENT.comment_byte(4, data.key, 'commentReplyWriteForm');
}
});
},
END : function() {}
};
/**
* 상품상세 Q&A
*/
$(document).ready(function(){
$('.xans-product-qna a').click(function(e) {
e.preventDefault();
var no = $(this).attr('href').replace(/(\S*)no=(\d+)(\S*)/g, '$2');
var $obj = $('#product-qna-read_'+no);
//로드된 엘리먼트 존재 체크
if ($obj.length > 0) {
if ($obj.css('display') =='none') {
$obj.show();
} else {
$obj.hide();
}
return;
}
QNA.getReadData($(this));
});
});
var PARENT = '';
var OPEN_QNA = '';
var QNA = {
getReadData : function(obj, eType)
{
if (obj != undefined) {
PARENT = obj;
var sHref = obj.attr('href');
var pNode = obj.parents('tr');
var pass_check = '&pass_check=F';
} else {
var sHref = PARENT.attr('href');
var pNode = PARENT.parents('tr');
var pass_check = '&pass_check=T';
}
var sQuery = sHref.split('?');
var sQueryNo = sQuery[1].split('=');
if (OPEN_QNA == sQueryNo[1]) {
$('#product-qna-read').remove();
OPEN_QNA = '';
return false;
} else {
OPEN_QNA = sQueryNo[1];
}
$.ajax({
url : '/exec/front/board/product/6?'+sQuery[1]+pass_check,
dataType: 'json',
success: function(data) {
$('#product-qna-read').remove();
var sPath = document.location.pathname;
var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
var aMatchResult = sPath.match(sPattern);
if (aMatchResult) {
var iProductNo = aMatchResult[2];
} else {
var iProductNo = getQueryString('product_no');
}
var aHtml = [];
//읽기 권한 체크
if (false === data.read_auth && eType == undefined) {
alert(decodeURIComponent(data.alertMSG));
//로그인페이지 이동
if (data.returnUrl != undefined) {
location.replace("/member/login.html?returnUrl=" + data.returnUrl);
}
return false;
}
if (data.is_secret == true) {
// 비밀글 비밀번호 입력 폼
aHtml.push('<form name="SecretForm_6" id="SecretForm_6">');
aHtml.push('<input type="text" name="a" style="display:none;">');
aHtml.push('<div class="view"><p>비밀번호 <input type="password" id="secure_password" name="secure_password" onkeydown="if (event.keyCode == 13) '+data.action_pass_submit+'"> <input type="button" value="확인" onclick="'+data.action_pass_submit+'"></p></div>');
aHtml.push('</form>');
} else {
// 글 내용
if (data.read['content_image'] != null) {
var sImg = data.read['content_image'];
} else {
var sImg = '';
}
aHtml.push('<div class="view">');
aHtml.push('<p>'+data.read['content']+'</p>');
aHtml.push('<p>'+sImg+'</p>');
aHtml.push('<p class="btnArea">');
if (data.write_auth == true) {
aHtml.push('<a href="/board/product/modify.html?board_act=edit&no='+data.no+'&board_no=6&link_product_no='+iProductNo+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/btn_board_modify.gif" alt="게시글 수정하기" /></a>');
}
aHtml.push('</p>');
aHtml.push('</div>');
// 댓글리스트
if (data.comment != undefined && data.comment.length != undefined) {
aHtml.push('<ul class="boardComment">');
for (var i=0; data.comment.length > i; i++) {
//댓글리스트
if (data.comment[i]['comment_reply_css'] == undefined) {
aHtml.push('<li>');
aHtml.push('<strong class="name">'+data.comment[i]['member_icon']+' '+data.comment[i]['comment_name']+'</strong>');
aHtml.push('<span class="date">'+data.comment[i]['comment_write_date']+'</span>');
aHtml.push('<span class="grade '+data.use_point+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/ico_point'+data.comment[i]['comment_point_count']+'.gif" alt="'+data.comment[i]['comment_point_count']+'점" /></span>');
if (data.comment[i]['comment_reply_display'] == true) {
aHtml.push('<span class="button">'+'<a href="#none" onclick="'+data.comment[i]['action_comment_reply']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_reply.gif" alt="댓글" /></a>'+'</span>');
}
aHtml.push('<p class="comment">'+data.comment[i]['comment_icon_lock']+' '+data.comment[i]['comment_content']+'</p>');
aHtml.push('</li>');
} else {
//댓글의 댓글리스트
aHtml.push('<li class="replyArea">');
aHtml.push('<strong class="name">'+data.comment[i]['member_icon']+' '+data.comment[i]['comment_name']+'</strong>');
aHtml.push('<span class="date">'+data.comment[i]['comment_write_date']+'</span>');
aHtml.push('<p class="comment">'+data.comment[i]['comment_icon_lock']+' '+data.comment[i]['comment_content']+'</p>');
aHtml.push('</li>');
}
}
aHtml.push('</ul>');
}
// 댓글쓰기
if (data.comment_write != undefined) {
aHtml.push('<form name="commentWriteForm_6'+data.key+'" id="commentWriteForm_6'+data.key+'">');
aHtml.push('<div class="memoCont">');
aHtml.push('<div class="writer">');
aHtml.push('<p class="user"><span class="nameArea">이름 '+data.comment_write['comment_name']+' 비밀번호 '+data.comment_write['comment_password']);
if (data.comment_write['comment_secret_display'] == true) {
aHtml.push('<label class="secret">'+data.comment_write['secure']+' 비밀댓글</label>');
}
aHtml.push('</span>');
aHtml.push(''+data.comment_write['comment']+'<a href="#none" onclick="'+data.comment_write['action_comment_insert']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_comment_submit.gif" alt="확인" /></a></p>');
aHtml.push('<p class="rating '+data.comment_write['use_point']+'">'+data.comment_write['comment_point']+'</p>');
aHtml.push('<p class="text '+data.comment_write['use_comment_size']+'">'+data.comment_write['comment_byte']+' / '+data.comment_write['comment_size']+' byte</p>');
aHtml.push('<p class="captcha '+data.comment_write['use_captcha']+'">'+data.comment_write['captcha_image']+data.comment_write['captcha']+'<img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/ico_information.gif" alt="" /> 왼쪽의 문자를 공백없이 입력하세요.(대소문자구분)</p>');
aHtml.push('</div>');
aHtml.push('</div>');
aHtml.push('</form>');
}
// 댓글의 댓글쓰기
if (data.comment_reply != undefined) {
aHtml.push('<form name="commentReplyWriteForm_6'+data.key+'" id="commentReplyWriteForm_6'+data.key+'" style="display:none">');
aHtml.push('<div class="memoCont reply">');
aHtml.push('<div class="writer">');
aHtml.push('<p class="user"><span class="nameArea">이름 '+data.comment_reply['comment_name']+' 비밀번호 '+data.comment_reply['comment_password']);
if (data.comment_reply['comment_secret_display'] == true) {
aHtml.push('<label class="secret">'+data.comment_reply['secure']+' 비밀댓글</label>');
}
aHtml.push('</span>');
aHtml.push(''+data.comment_reply['comment']+'<a href="#none" onclick="'+data.comment_reply['action_comment_insert']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_comment_submit.gif" alt="확인" /></a></p>');
aHtml.push('<p class="text '+data.comment_reply['use_comment_size']+'">'+data.comment_reply['comment_byte']+' / '+data.comment_reply['comment_size']+' byte</p>');
aHtml.push('<p class="captcha '+data.comment_reply['use_captcha']+'">'+data.comment_reply['captcha_image']+data.comment_reply['captcha']+'<img src="http://img.echosting.cafe24.com/skin/base_ko_KR/product/ico_information.gif" alt="" /> 왼쪽의 문자를 공백없이 입력하세요.(대소문자구분)</p>');
aHtml.push('</div>');
aHtml.push('</div>');
aHtml.push('</form>');
}
// 비밀댓글 확인
if (data.comment_secret != undefined) {
aHtml.push('<form name="commentSecretForm_6'+data.key+'" id="commentSecretForm_6'+data.key+'" style="display:none">');
aHtml.push('<div class="commentSecret">');
aHtml.push('<p>비밀번호 : '+data.comment_secret['secure_password']);
aHtml.push(' <a href="#none" onclick="'+data.comment_secret['action_secret_submit']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_submit.gif" alt="확인" /></a>');
aHtml.push(' <a href="#none" onclick="'+data.comment_secret['action_secret_cancel']+'"><img src="http://img.echosting.cafe24.com/skin/base_ko_KR/board/btn_ico_cancel.gif" alt="취소" /></a></p>');
aHtml.push('</div>');
aHtml.push('</form>');
}
}
$(pNode).after('<tr id="product-qna-read'+data.key+'"><td colspan="6">'+aHtml.join('')+'</td></tr>');
// 평점기능 사용안함일 경우 보여지는 td를 조절하기 위한 함수
PRODUCT_COMMENT.comment_colspan(pNode);
if (data.comment_write != undefined && data.comment_write['use_comment_size'] == '') PRODUCT_COMMENT.comment_byte(6, data.key);
if (data.comment_reply != undefined && data.comment_write['use_comment_size'] == '') PRODUCT_COMMENT.comment_byte(6, data.key, 'commentReplyWriteForm');
}
});
},
END : function() {}
};
/**
* 움직이는 배너 Jquery Plug-in
* @author cafe24
*/
;(function($){
$.fn.floatBanner = function(options) {
options = $.extend({}, $.fn.floatBanner.defaults , options);
return this.each(function() {
var aPosition = $(this).position();
var node = this;
$(window).scroll(function() {
var _top = $(document).scrollTop();
_top = (aPosition.top < _top) ? _top : aPosition.top;
setTimeout(function () {
$(node).stop().animate({top: _top}, options.animate);
}, options.delay);
});
});
};
$.fn.floatBanner.defaults = {
'animate' : 500,
'delay' : 500
};
})(jQuery);
/**
* 문서 구동후 시작
*/
$(document).ready(function(){
$('#banner, #quick').floatBanner();
});
/**
* 썸네일 이미지 엑박일경우 기본값 설정
*/
$(window).load(function() {
$("img.thumb,img.ThumbImage,img.BigImage").each(function($i,$item){
var $img = new Image();
$img.onerror = function () {
$item.src="//img.echosting.cafe24.com/thumb/img_product_big.gif";
}
$img.src = this.src;
});
});
//window popup script
function winPop(url) {
window.open(url, "popup", "width=300,height=300,left=10,top=10,resizable=no,scrollbars=no");
}
/**
* document.location.href split
* return array Param
*/
function getQueryString(sKey)
{
var sQueryString = document.location.search.substring(1);
var aParam = {};
if (sQueryString) {
var aFields = sQueryString.split("&");
var aField = [];
for (var i=0; i<aFields.length; i++) {
aField = aFields[i].split('=');
aParam[aField[0]] = aField[1];
}
}
aParam.page = aParam.page ? aParam.page : 1;
return sKey ? aParam[sKey] : aParam;
};
/**
* paging HTML strong tag로 변형
*/
function convertPaging(){
$('.paging ol a').each(function() {
var sPage = $(this).text() ? $(this).text() : 1;
if (sPage == '['+getQueryString('page')+']') {
$(this).parent().html('<strong title="현재페이지">'+sPage+'</strong>');
} else {
var sHref = $(this).attr('href');
$(this).parent().html('<a href="'+sHref+'" title="'+sPage+'페이지로 이동">'+sPage+'</a>');
}
});
}
$(document).ready(function(){
// tab
$.eTab = function(ul){
$(ul).find('a').click(function(){
var _li = $(this).parent('li').addClass('selected').siblings().removeClass('selected'),
_target = $(this).attr('href'),
_siblings = '.' + $(_target).attr('class');
$(_target).show().siblings(_siblings).hide();
return false
});
}
if ( window.call_eTab ) {
call_eTab();
};
});
$.fn.extend({
center: function() {
this.each(function() {
var
$this = $(this),
$w = $(window);
$this.css({
position: "absolute",
top: ~~(($w.height() - $this.outerHeight()) / 2) + $w.scrollTop() + "px",
left: ~~(($w.width() - $this.outerWidth()) / 2) + $w.scrollLeft() + "px"
});
});
return this;
}
});
$(function() {
var $container = function(){/*
<div id="modalContainer">
<iframe id="modalContent" scroll="0" scrolling="no" frameBorder="0"></iframe>
</div>');
*/}.toString().slice(14,-3);
$('body')
.append($('<div id="modalBackpanel"></div>'))
.append($($container));
function closeModal () {
$('#modalContainer').hide();
$('#modalBackpanel').hide();
}
$('#modalBackpanel').click(closeModal);
zoom = function ($piProductNo, $piCategoryNo, $piDisplayGroup) {
var $url = '/product/image_zoom.html?product_no=' + $piProductNo + '&cate_no=' + $piCategoryNo + '&display_group=' + $piDisplayGroup;
$('#modalContent').attr('src', $url);
$('#modalContent').bind("load",function(){
$(".header .close",this.contentWindow.document.body).bind("click", closeModal);
});
$('#modalBackpanel').css({width:$("body").width(),height:$("body").height(),opacity:.4}).show();
$('#modalContainer').center().show();
}
});
/**
* 카테고리 마우스 오버 이미지
* 카테고리 서브 메뉴 출력
*/
$(document).ready(function(){
var methods = {
aCategory : [],
aSubCategory : {},
get: function()
{
$.ajax({
url : '/exec/front/Product/SubCategory',
dataType: 'json',
success: function(aData) {
if (aData == null || aData == 'undefined') return;
for (var i=0; i<aData.length; i++)
{
var sParentCateNo = aData[i].parent_cate_no;
if (!methods.aSubCategory[sParentCateNo]) {
methods.aSubCategory[sParentCateNo] = [];
}
methods.aSubCategory[sParentCateNo].push( aData[i] );
}
}
});
},
getParam: function(sUrl, sKey) {
var aUrl = sUrl.split('?');
var sQueryString = aUrl[1];
var aParam = {};
if (sQueryString) {
var aFields = sQueryString.split("&");
var aField = [];
for (var i=0; i<aFields.length; i++) {
aField = aFields[i].split('=');
aParam[aField[0]] = aField[1];
}
}
return sKey ? aParam[sKey] : aParam;
},
show: function(overNode, iCateNo) {
if (methods.aSubCategory[iCateNo].length == 0) {
return;
}
var aHtml = [];
aHtml.push('<ul>');
$(methods.aSubCategory[iCateNo]).each(function() {
aHtml.push('<li><a href="/'+this.design_page_url+this.param+'">'+this.name+'</a></li>');
});
aHtml.push('</ul>');
var offset = $(overNode).offset();
$('<div class="sub-category"></div>')
.appendTo(overNode)
.html(aHtml.join(''))
.find('li').mouseover(function(e) {
$(this).addClass('over');
}).mouseout(function(e) {
$(this).removeClass('over');
});
},
close: function() {
$('.sub-category').remove();
}
};
methods.get();
$('.xans-layout-category li').mouseenter(function(e) {
var $this = $(this).addClass('on'),
iCateNo = Number(methods.getParam($this.find('a').attr('href'), 'cate_no'));
if (!iCateNo) {
return;
}
methods.show($this, iCateNo);
}).mouseleave(function(e) {
$(this).removeClass('on');
methods.close();
});
});
/**
* @class
* 이미지 롤링를 처리 합니다.
*
* @example
* $.fn.roate.defaults = {
* 'duration' : '3000',
* 'stopButton' : '#stopButton',
* 'playButton' : '#playButton',
* 'prevButton' : '#prevButton',
* 'nextButton' : '#nextButton',
* 'movement' : 'left',
* 'scroll' : 1,
* 'autoStart' : false,
* 'interval' : 2000
* };
*
*/
;(function($){
$.fn.roate = function( options ) {
var opts = $.extend( {}, $.fn.roate.defaults, options ),
containerBox = [],
$this = $(this),
defaultWidth, defaultHeight, curentIndex = 0, distance, childLength, isAnimate = false, timer = null;
var pm = {}
var _init = function() {
_setDefaultSize();
_setDistance();
_displayOverFlow();
_setContainerBox();
if(childLength > 1) {
_setEventBind();
} else {
_displayPlayButton();
}
}
, _setDefaultSize = function() {
defaultWidth = opts.defaultWidth || $this.children().eq(0).width();
defaultHeight = opts.defaultHeight || $this.children().eq(0).height();
childLength = $this.children().length;
if ( opts.movement == 'top' ) {
defaultHeight = defaultHeight * parseInt(opts.scroll,10);
} else {
defaultWidth = defaultWidth * parseInt(opts.scroll,10);
$this.children().css('float','left');
}
}
, _setDistance = function() {
if ( opts.movement == 'top') {
distance = defaultHeight;
} else {
distance = defaultWidth;
}
}
, _displayOverFlow = function() {
var $wrap = $("<div class='containterWrap'></div>").css({
'overflow' : 'hidden',
'position' : 'relative',
'width' : defaultWidth,
'height' : opts.defaultHeight || defaultHeight
});
$this.wrap( $wrap );
$this.css({'position':'absolute', 'left': '0', 'top' : '0' });
}
, _setContainerBox = function() {
$this.children().each(function(i){
containerBox[ containerBox.length ] = this;
});
}
, _setEventBind = function() {
$(options.nextButton).bind('click.roate', function(){
pm.next();
});
$(options.prevButton).bind('click.roate', function(){
pm.prev();
});
$(options.playButton).bind('click.roate', function(){
_stopTimer();
pm.play();
});
$(options.stopButton).bind('click.roate', function(){
pm.stop();
});
$this.hover( function(){
pm.stop();
}, function(){
_stopTimer();
pm.play();
});
}
, _addCurrent = function() {
curentIndex++;
if ( curentIndex >= childLength ) {
curentIndex = 0;
}
}, _minusCurrent = function() {
curentIndex--;
if ( curentIndex < 0 ) {
curentIndex = childLength -1;
}
}
, _isAmimate = function() {
if ( isAnimate ) {
return true;
}
isAnimate = true;
return false;
}, _stopTimer = function(){
if ( timer ) {
clearInterval( timer );
_displayPlayButton();
}
}, _displayPlayButton = function() {
$(opts.playButton).css('display', 'inline');
$(opts.stopButton).css('display', 'none');
}, _displayStopButton = function() {
$(opts.playButton).css('display', 'none');
$(opts.stopButton).css('display', 'inline');
}, _setOpacity = function ( style ) {
if ( opts.opacity ) {
style['display'] = 'none';
style['opacity'] = 1;
}
return style;
};
pm.next = function() {
this.nextMovement( $(containerBox[ curentIndex ]) );
};
pm.prev = function() {
this.prevMovement( $(containerBox[ curentIndex ]) );
};
pm.play = function() {
timer = setInterval(function(){ pm.next() }, opts.interval);
_displayStopButton();
};
pm.stop = function() {
_stopTimer();
};
pm.nextMovement = function ($el) {
var moveDistance = $this.offset().left - $el.offset().left - distance;
if ( _isAmimate() === false ) {
var moveType = {},setCss = {}
moveType[opts.movement] = moveDistance;
if ( opts.opacity) {
moveType['opacity'] = 0;
}
setCss[opts.movement] = parseInt(moveDistance,10) + parseInt(distance,10);
setCss = _setOpacity( setCss );
$this.animate(moveType, opts.duration, function(){
$this.children(':last').after($el);
$this.css(setCss);
if ( opts.opacity ) {
$this.fadeIn(opts.duration);
}
isAnimate = false;
_addCurrent();
});
}
}
pm.prevMovement = function ($el) {
var moveDistance = $this.offset().left - $el.offset().left + distance;
if ( _isAmimate() === false ) {
var moveType = {},setCss = {}
moveType[opts.movement] = moveDistance;
if ( opts.opacity ) {
moveType['opacity'] = 0;
}
setCss[opts.movement] = parseInt(moveDistance,10) - parseInt(distance,10);
setCss = _setOpacity( setCss );
if ( opts.movement == 'top' ) {
$this.css('top',-defaultHeight);
moveType[opts.movement] = 0;
$this.children(':first').before($this.children(':last'));
}
$this.animate(moveType, opts.duration, function(){
if ( opts.movement == 'left' ) {
$this.children(':first').before($this.children(':last'));
}
$this.css(setCss);
if ( opts.opacity ) {
$this.fadeIn(opts.duration);
}
_minusCurrent();
isAnimate = false;
});
}
}
_init();
if ( opts.autoStart && childLength > 1) {
pm.play();
}
return pm;
};
$.fn.roate.defaults = {
'duration' : '3000',
'stopButton' : '#stopButton',
'playButton' : '#playButton',
'prevButton' : '#prevButton',
'nextButton' : '#nextButton',
'movement' : 'left',
'scroll' : 1,
'autoStart' : false,
'interval' : 2000,
'opacity' : false
};
})(jQuery);
$(document).ready(function(){
$(".xans-layout-project ul").roate({
'duration' : '1000',
'interval' : 3000,
'stopButton' : '#stopButton-project',
'playButton' : '#playButton-project',
'prevButton' : '#prevButton-project',
'nextButton' : '#nextButton-project',
'defaultWidth': '180',
'defaultHeight' : '180',
'movement' : 'top',
'opacity' : false,
'autoStart' : true
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment