PageSourceSearch

https://suubc.kr/ind-script/optimizer.php?filename=vVlbd-I4DH4ved3…5f1c7d0c1e5b6b2279669a370710ea&t=1790658558

js suubc.kr collected 2026-10-06 14:05:08 UTC 1,897,036 bytes, 47,642 lines download raw bytes

1(function (root, factory) {
2    //amd
3    if (typeof define === "function" && define.amd) {
4        define(['sprintf-js'], function (sprintf) {
5            return factory(sprintf.vsprintf);
6        });
7
8        //commonjs
9    } else if (typeof module === "object" && module.exports) {
10        module.exports = factory(require('sprintf-js').vsprintf);
11
12        //global
13    } else {
14        root.I18nTranslator = factory(window.vsprintf);
15    }
16
17    var i18n = new I18nTranslator(TRANSLATIONS);
18    window['__'] = function (sMsg, sGroupID) {
19        return i18n.p__(sGroupID, sMsg);
20    };
21
22    window['__pn'] = function (sMsgID, sGroupID, iValue) {
23        if (iValue === undefined || I18N_FN.isNumber(iValue) === false) {
24            iValue = 0;
25        }
26        return i18n.np__(sGroupID, sMsgID, sMsgID + '.PLURAL', iValue);
27    };
28
29    window['__sl'] = function (languageCode) {
30        if (!languageCode) {
31            console.error('Language code is required for __sl');
32            return false;
33        }
34        
35        // 언어코드 형식 검증 (en_US 같은 5자리 형식)
36        if (!/^[a-z]{2}_[A-Z]{2}$/.test(languageCode)) {
37            console.error('Invalid language code format. Expected format: en_US (5 characters)');
38            return false;
39        }
40
41        // G2G 환경 체크
42        if (!window.CAFE24?.SHOP?.isG2G?.() && !window.CAFE24?.SHOP?.isGlobale?.()) {
43            console.error('Language switching is only available in G2G environment');
44            return false;
45        }        
46        
47        try {
48            // 현재 시간을 버전으로 사용
49            var currentTime = new Date().getTime();
50            var apiUrl = '/ind-script/i18n.php?v=' + currentTime + '&lang=' + languageCode + '&domain=front&type=G2G&format=json';
51            
52            fetch(apiUrl)
53                .then(function(response) {
54                    if (!response.ok) {
55                        throw new Error('HTTP error! status: ' + response.status);
56                    }
57                    return response.json();
58                })
59                .then(function(translationData) {
60                    // 응답 데이터 검증 (필수 키들 체크)
61                    if (!translationData || 
62                        !translationData.domain || 
63                        !translationData['plural-forms'] || 
64                        !translationData.messages
65                    ) {
66                        console.error('Invalid translation data format');
67                        return;
68                    }
69                    
70                    // 기존 번역 데이터 초기화
71                    i18n.dictionary = {};
72                    i18n.plurals = {};
73                    i18n.domain = null;
74                    
75                    // 새로운 번역 데이터 로드
76                    i18n.loadTranslations(translationData);
77                    
78                    console.log('Language switched to:', languageCode);
79                })
80                .catch(function(error) {
81                    console.error('Failed to load language:', languageCode, error);
82                });
83        } catch (error) {
84            console.error('Error in __sl function:', error);
85            return false;
86        }
87    };
88}(this, function (vsprintf) {
89    "use strict";
90    function I18nTranslator (translations) {
91        this.dictionary = {};
92        this.plurals = {};
93        this.domain = null;
94
95        if (translations) {
96            this.loadTranslations(translations);
97        }
98    }
99
100    I18nTranslator.prototype = {
101        loadTranslations: function (translations) {
102            var domain = translations.domain || '';
103
104            if (this.domain === null) {
105                this.domain = domain;
106            }
107
108            if (this.dictionary[domain]) {
109                mergeTranslations(this.dictionary[domain], translations.messages);
110                return this;
111            }
112
113            if (translations.fn) {
114                this.plurals[domain] = { fn: translations.fn };
115            } else if (translations['plural-forms']) {
116                var plural = translations['plural-forms'].split(';', 2);
117
118                this.plurals[domain] = {
119                    count: parseInt(plural[0].replace('nplurals=', '')),
120                    code: plural[1].replace('plural=', 'return ') + ';'
121                };
122            }
123
124            this.dictionary[domain] = translations.messages;
125
126            return this;
127        },
128
129        defaultDomain: function (domain) {
130            this.domain = domain;
131
132            return this;
133        },
134
135        gettext: function (original) {
136            return this.dpgettext(this.domain, null, original);
137        },
138
139        ngettext: function (original, plural, value) {
140            return this.dnpgettext(this.domain, null, original, plural, value);
141        },
142
143        dngettext: function (domain, original, plural, value) {
144            return this.dnpgettext(domain, null, original, plural, value);
145        },
146
147        npgettext: function (context, original, plural, value) {
148            return this.dnpgettext(this.domain, context, original, plural, value);
149        },
150
151        pgettext: function (context, original) {
152            return this.dpgettext(this.domain, context, original);
153        },
154
155        dgettext: function (domain, original) {
156            return this.dpgettext(domain, null, original);
157        },
158
159        dpgettext: function (domain, context, original) {
160            var translation = getTranslation(this.dictionary, domain, context, original);
161
162            if (translation !== false && translation[0] !== '') {
163                return translation[0];
164            }
165
166            return original;
167        },
168
169        dnpgettext: function (domain, context, original, plural, value) {
170            var index = getPluralIndex(this.plurals, domain, value);
171            var translation = getTranslation(this.dictionary, domain, context, original);
172
173            if (translation[index] && translation[index] !== '') {
174                return translation[index];
175            }
176
177            return (index === 0) ? original : plural;
178        },
179
180        __: function (original) {
181            return format(
182                this.gettext(original),
183                Array.prototype.slice.call(arguments, 1)
184            );
185        },
186
187        n__: function (original, plural, value) {
188            return format(
189                this.ngettext(original, plural, value),
190                Array.prototype.slice.call(arguments, 3)
191            );
192        },
193
194        p__: function (context, original) {
195            return format(
196                this.pgettext(context, original),
197                Array.prototype.slice.call(arguments, 2)
198            );
199        },
200
201        d__: function (domain, original) {
202            return format(
203                this.dgettext(domain, original),
204                Array.prototype.slice.call(arguments, 2)
205            );
206        },
207
208        dp__: function (domain, context, original) {
209            return format(
210                this.dgettext(domain, context, original),
211                Array.prototype.slice.call(arguments, 3)
212            );
213        },
214
215        np__: function (context, original, plural, value) {
216            return format(
217                this.npgettext(context, original, plural, value),
218                Array.prototype.slice.call(arguments, 4)
219            );
220        },
221
222        dnp__: function (domain, context, original, plural, value) {
223            return format(
224                this.dnpgettext(domain, context, original, plural, value),
225                Array.prototype.slice.call(arguments, 5)
226            );
227        }
228    };
229
230    function getTranslation(dictionary, domain, context, original) {
231        context = context || '';
232
233        if (!dictionary[domain] || !dictionary[domain][context] || !dictionary[domain][context][original]) {
234            return false;
235        }
236
237        try {
238            I18N_LOG_COLLECT.set(original, context);
239        } catch (e) {}
240
241        return dictionary[domain][context][original];
242    }
243
244    function getPluralIndex(plurals, domain, value) {
245        if (!plurals[domain]) {
246            return value == 1 ? 0 : 1;
247        }
248
249        if (!plurals[domain].fn) {
250            plurals[domain].fn = new Function('n', plurals[domain].code);
251        }
252
253        return plurals[domain].fn.call(this, value) + 0;
254    }
255
256    function mergeTranslations(translations, newTranslations) {
257        for (var context in newTranslations) {
258            if (!translations[context]) {
259                translations[context] = newTranslations[context];
260                continue;
261            }
262
263            for (var original in newTranslations[context]) {
264                translations[context][original] = newTranslations[context][original];
265            }
266        }
267    }
268
269    function format (text, args) {
270        if (!args.length) {
271            return text;
272        }
273
274        if (args[0] instanceof Array) {
275            return vsprintf(text, args[0]);
276        }
277
278        return vsprintf(text, args);
279    }
280
281    return I18nTranslator;
282}));
283
284/**
285 * i18n 관련 함수 모음
286 * @type {{ordinalSuffixes: string[], ordinalNumber: I18N_FN.ordinalNumber}}
287 */
288var I18N_FN = {
289    ordinalSuffixes: ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'],
290
291    ordinalNumber: function (iValue) {
292        if (iValue === undefined) {
293            return '';
294        }
295
296        var iNum = String(iValue).replace(/,/g, "");
297        if (this.isNumber(iNum) === false) {
298            return iValue;
299        }
300        if (__('__LANGUAGE.CODE__') !== 'en_US') {
301            return iValue;
302        }
303        iNum = Math.abs(iNum);
304        iNum = parseFloat(iNum);
305        if (((iNum % 100) >= 11 && ((iNum % 100) <= 13)) || iNum % 1 != 0) {
306            return iValue + 'th';
307        }
308
309        return iValue + this.ordinalSuffixes[iNum % 10];
310    },
311    isNumber: function (v) {
312        return /^[+-]?\d*(\.?\d*)$/.test(v);
313    }
314};
315
316var I18N_LOG_COLLECT = {
317    aTranslationCodes: [],
318    bIsCallApiOnLoaded: false,
319    request_url: window.location.pathname,
320
321    call: function () {
322        var data = I18N_LOG_COLLECT.aTranslationCodes;
323        if (data.length === 0) {
324            return false;
325        }
326        I18N_LOG_COLLECT.aTranslationCodes = [];
327        $.ajax({
328            url: '/exec/common/translate/logging',
329            data: {"data": data},
330            type: 'POST',
331            dataType: 'json',
332            success: function (aData) {}
333        });
334    },
335    set: function (sMsg_id, sGroup_id) {
336        if (typeof CAFE24.TRANSLATE_LOG_STATUS === 'undefined' || CAFE24.TRANSLATE_LOG_STATUS !== 'T') {
337            return;
338        }
339
340        var item = {
341            'request_url': I18N_LOG_COLLECT.request_url,
342            'msg_id': sMsg_id,
343            'group_id': sGroup_id
344        };
345
346        if (I18N_LOG_COLLECT.bIsCallApiOnLoaded) {
347            I18N_LOG_COLLECT.aTranslationCodes.push(item);
348            I18N_LOG_COLLECT.call();
349            return true;
350        }
351        I18N_LOG_COLLECT.aTranslationCodes.push(item);
352    },
353    loadComplete: function () {
354        I18N_LOG_COLLECT.bIsCallApiOnLoaded = true;
355        I18N_LOG_COLLECT.call();
356    }
357};
358
359if (typeof CAFE24.TRANSLATE_LOG_STATUS !== 'undefined' && CAFE24.TRANSLATE_LOG_STATUS === 'T') {
360    if (document.addEventListener) {
361        document.addEventListener("DOMContentLoaded", function () {
362            I18N_LOG_COLLECT.loadComplete();
363        }, false);
364    } else if (document.attachEvent) {
365        document.attachEvent("onreadystatechange", function () {
366            if (document.readyState === "complete") {
367                document.detachEvent("onreadystatechange", arguments.callee);
368                I18N_LOG_COLLECT.loadComplete();
369            }
370        });
371    }
372}
373/*!
374 * jQuery JavaScript Library v3.6.0
375 * https://jquery.com/
376 *
377 * Includes Sizzle.js
378 * https://sizzlejs.com/
379 *
380 * Copyright OpenJS Foundation and other contributors
381 * Released under the MIT license
382 * https://jquery.org/license
383 *
384 * Date: 2021-03-02T17:08Z
385 */
386( function( global, factory ) {
387
388    "use strict";
389
390    if ( typeof module === "object" && typeof module.exports === "object" ) {
391
392        // For CommonJS and CommonJS-like environments where a proper `window`
393        // is present, execute the factory and get jQuery.
394        // For environments that do not have a `window` with a `document`
395        // (such as Node.js), expose a factory as module.exports.
396        // This accentuates the need for the creation of a real `window`.
397        // e.g. var jQuery = require("jquery")(window);
398        // See ticket #14549 for more info.
399        module.exports = global.document ?
400            factory( global, true ) :
401            function( w ) {
402                if ( !w.document ) {
403                    throw new Error( "jQuery requires a window with a document" );
404                }
405                return factory( w );
406            };
407    } else {
408        factory( global );
409    }
410
411// Pass this if window is not defined yet
412} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
413
414// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1
415// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode
416// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), str
vendor: 4,813 bytes, lines 416-570
416ict mode should be common
417// enough that all such attempts are guarded in a try block.
418    "use strict";
419
420    var arr = [];
421
422    var getProto = Object.getPrototypeOf;
423
424    var slice = arr.slice;
425
426    var flat = arr.flat ? function( array ) {
427        return arr.flat.call( array );
428    } : function( array ) {
429        return arr.concat.apply( [], array );
430    };
431
432
433    var push = arr.push;
434
435    var indexOf = arr.indexOf;
436
437    var class2type = {};
438
439    var toString = class2type.toString;
440
441    var hasOwn = class2type.hasOwnProperty;
442
443    var fnToString = hasOwn.toString;
444
445    var ObjectFunctionString = fnToString.call( Object );
446
447    var support = {};
448
449    var isFunction = function isFunction( obj ) {
450
451        // Support: Chrome <=57, Firefox <=52
452        // In some browsers, typeof returns "function" for HTML <object> elements
453        // (i.e., `typeof document.createElement( "object" ) === "function"`).
454        // We don't want to classify *any* DOM node as a function.
455        // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5
456        // Plus for old WebKit, typeof returns "function" for HTML collections
457        // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756)
458        return typeof obj === "function" && typeof obj.nodeType !== "number" &&
459            typeof obj.item !== "function";
460    };
461
462
463    var isWindow = function isWindow( obj ) {
464        return obj != null && obj === obj.window;
465    };
466
467
468    var document = window.document;
469
470
471
472    var preservedScriptAttributes = {
473        type: true,
474        src: true,
475        nonce: true,
476        noModule: true
477    };
478
479    function DOMEval( code, node, doc ) {
480        doc = doc || document;
481
482        var i, val,
483            script = doc.createElement( "script" );
484
485        script.text = code;
486        if ( node ) {
487            for ( i in preservedScriptAttributes ) {
488
489                // Support: Firefox 64+, Edge 18+
490                // Some browsers don't support the "nonce" property on scripts.
491                // On the other hand, just using `getAttribute` is not enough as
492                // the `nonce` attribute is reset to an empty string whenever it
493                // becomes browsing-context connected.
494                // See https://github.com/whatwg/html/issues/2369
495                // See https://html.spec.whatwg.org/#nonce-attributes
496                // The `node.getAttribute` check was added for the sake of
497                // `jQuery.globalEval` so that it can fake a nonce-containing node
498                // via an object.
499                val = node[ i ] || node.getAttribute && node.getAttribute( i );
500                if ( val ) {
501                    script.setAttribute( i, val );
502                }
503            }
504        }
505        doc.head.appendChild( script ).parentNode.removeChild( script );
506    }
507
508
509    function toType( obj ) {
510        if ( obj == null ) {
511            return obj + "";
512        }
513
514        // Support: Android <=2.3 only (functionish RegExp)
515        return typeof obj === "object" || typeof obj === "function" ?
516            class2type[ toString.call( obj ) ] || "object" :
517            typeof obj;
518    }
519    /* global Symbol */
520// Defining this global in .eslintrc.json would create a danger of using the global
521// unguarded in another place, it seems safer to define global only for this module
522
523
524
525    var
526        version = "3.6.0",
527
528        // Define a local copy of jQuery
529        jQuery = function( selector, context ) {
530
531            // The jQuery object is actually just the init constructor 'enhanced'
532            // Need init if jQuery is called (just allow error to be thrown if not included)
533            return new jQuery.fn.init( selector, context );
534        };
535
536    jQuery.fn = jQuery.prototype = {
537
538        // The current version of jQuery being used
539        jquery: version,
540
541        constructor: jQuery,
542
543        // The default length of a jQuery object is 0
544        length: 0,
545
546        toArray: function() {
547            return slice.call( this );
548        },
549
550        // Get the Nth element in the matched element set OR
551        // Get the whole matched element set as a clean array
552        get: function( num ) {
553
554            // Return all the elements in a clean array
555            if ( num == null ) {
556                return slice.call( this );
557            }
558
559            // Return just the one element from the set
560            return num < 0 ? this[ num + this.length ] : this[ num ];
561        },
562
563        // Take an array of elements and push it onto the stack
564        // (returning the new matched element set)
565        pushStack: function( elems ) {
566
567            // Build a new jQuery matched element set
568            var ret = jQuery.merge( this.constructor(), elems );
569
570            // Add the old object onto the stack (as a reference)
vendor: 4,654 bytes, lines 571-721
571            ret.prevObject = this;
572
573            // Return the newly-formed element set
574            return ret;
575        },
576
577        // Execute a callback for every element in the matched set.
578        each: function( callback ) {
579            return jQuery.each( this, callback );
580        },
581
582        map: function( callback ) {
583            return this.pushStack( jQuery.map( this, function( elem, i ) {
584                return callback.call( elem, i, elem );
585            } ) );
586        },
587
588        slice: function() {
589            return this.pushStack( slice.apply( this, arguments ) );
590        },
591
592        first: function() {
593            return this.eq( 0 );
594        },
595
596        last: function() {
597            return this.eq( -1 );
598        },
599
600        even: function() {
601            return this.pushStack( jQuery.grep( this, function( _elem, i ) {
602                return ( i + 1 ) % 2;
603            } ) );
604        },
605
606        odd: function() {
607            return this.pushStack( jQuery.grep( this, function( _elem, i ) {
608                return i % 2;
609            } ) );
610        },
611
612        eq: function( i ) {
613            var len = this.length,
614                j = +i + ( i < 0 ? len : 0 );
615            return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] );
616        },
617
618        end: function() {
619            return this.prevObject || this.constructor();
620        },
621
622        // For internal use only.
623        // Behaves like an Array's method, not like a jQuery method.
624        push: push,
625        sort: arr.sort,
626        splice: arr.splice
627    };
628
629    jQuery.extend = jQuery.fn.extend = function() {
630        var options, name, src, copy, copyIsArray, clone,
631            target = arguments[ 0 ] || {},
632            i = 1,
633            length = arguments.length,
634            deep = false;
635
636        // Handle a deep copy situation
637        if ( typeof target === "boolean" ) {
638            deep = target;
639
640            // Skip the boolean and the target
641            target = arguments[ i ] || {};
642            i++;
643        }
644
645        // Handle case when target is a string or something (possible in deep copy)
646        if ( typeof target !== "object" && !isFunction( target ) ) {
647            target = {};
648        }
649
650        // Extend jQuery itself if only one argument is passed
651        if ( i === length ) {
652            target = this;
653            i--;
654        }
655
656        for ( ; i < length; i++ ) {
657
658            // Only deal with non-null/undefined values
659            if ( ( options = arguments[ i ] ) != null ) {
660
661                // Extend the base object
662                for ( name in options ) {
663                    copy = options[ name ];
664
665                    // Prevent Object.prototype pollution
666                    // Prevent never-ending loop
667                    if ( name === "__proto__" || target === copy ) {
668                        continue;
669                    }
670
671                    // Recurse if we're merging plain objects or arrays
672                    if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
673                        ( copyIsArray = Array.isArray( copy ) ) ) ) {
674                        src = target[ name ];
675
676                        // Ensure proper type for the source value
677                        if ( copyIsArray && !Array.isArray( src ) ) {
678                            clone = [];
679                        } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) {
680                            clone = {};
681                        } else {
682                            clone = src;
683                        }
684                        copyIsArray = false;
685
686                        // Never move original objects, clone them
687                        target[ name ] = jQuery.extend( deep, clone, copy );
688
689                        // Don't bring in undefined values
690                    } else if ( copy !== undefined ) {
691                        target[ name ] = copy;
692                    }
693                }
694            }
695        }
696
697        // Return the modified object
698        return target;
699    };
700
701    jQuery.extend( {
702
703        // Unique for each copy of jQuery on the page
704        expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
705
706        // Assume jQuery is ready without the ready module
707        isReady: true,
708
709        error: function( msg ) {
710            throw new Error( msg );
711        },
712
713        noop: function() {},
714
715        isPlainObject: function( obj ) {
716            var key;
717
718            // Detect obvious negatives
719            // Use toString instead of jQuery.type to catch host objects
720            if ( !obj || toString.call( obj ) !== "[object Object]" ) {
721                return false;
vendor: 4,823 bytes, lines 722-882
722            }
723
724            // Not own constructor property must be Object
725            if ( obj.constructor &&
726                !hasOwn.call( obj, "constructor" ) &&
727                !hasOwn.call( obj.constructor.prototype || {}, "isPrototypeOf" ) ) {
728                return false;
729            }
730
731            // Own properties are enumerated firstly, so to speed up,
732            // if last one is own, then all properties are own
733            for ( key in obj ) {}
734
735            return key === undefined || hasOwn.call( obj, key );
736        },
737
738        isEmptyObject: function( obj ) {
739            var name;
740
741            for ( name in obj ) {
742                return false;
743            }
744            return true;
745        },
746
747        // Evaluates a script in a provided context; falls back to the global one
748        // if not specified.
749        globalEval: function( code, options, doc ) {
750            DOMEval( code, { nonce: options && options.nonce }, doc );
751        },
752
753        each: function( obj, callback ) {
754            var length, i = 0;
755
756            if ( isArrayLike( obj ) ) {
757                length = obj.length;
758                for ( ; i < length; i++ ) {
759                    if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
760                        break;
761                    }
762                }
763            } else {
764                for ( i in obj ) {
765                    if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
766                        break;
767                    }
768                }
769            }
770
771            return obj;
772        },
773
774        // results is for internal usage only
775        makeArray: function( arr, results ) {
776            var ret = results || [];
777
778            if ( arr != null ) {
779                if ( isArrayLike( Object( arr ) ) ) {
780                    jQuery.merge( ret,
781                        typeof arr === "string" ?
782                            [ arr ] : arr
783                    );
784                } else {
785                    push.call( ret, arr );
786                }
787            }
788
789            return ret;
790        },
791
792        inArray: function( elem, arr, i ) {
793            return arr == null ? -1 : indexOf.call( arr, elem, i );
794        },
795
796        // Support: Android <=4.0 only, PhantomJS 1 only
797        // push.apply(_, arraylike) throws on ancient WebKit
798        merge: function( first, second ) {
799            var len = +second.length,
800                j = 0,
801                i = first.length;
802
803            for ( ; j < len; j++ ) {
804                first[ i++ ] = second[ j ];
805            }
806
807            first.length = i;
808
809            return first;
810        },
811
812        grep: function( elems, callback, invert ) {
813            var callbackInverse,
814                matches = [],
815                i = 0,
816                length = elems.length,
817                callbackExpect = !invert;
818
819            // Go through the array, only saving the items
820            // that pass the validator function
821            for ( ; i < length; i++ ) {
822                callbackInverse = !callback( elems[ i ], i );
823                if ( callbackInverse !== callbackExpect ) {
824                    matches.push( elems[ i ] );
825                }
826            }
827
828            return matches;
829        },
830
831        // arg is for internal usage only
832        map: function( elems, callback, arg ) {
833            var length, value,
834                i = 0,
835                ret = [];
836
837            // Go through the array, translating each of the items to their new values
838            if ( isArrayLike( elems ) ) {
839                length = elems.length;
840                for ( ; i < length; i++ ) {
841                    value = callback( elems[ i ], i, arg );
842
843                    if ( value != null ) {
844                        ret.push( value );
845                    }
846                }
847
848                // Go through every key on the object,
849            } else {
850                for ( i in elems ) {
851                    value = callback( elems[ i ], i, arg );
852
853                    if ( value != null ) {
854                        ret.push( value );
855                    }
856                }
857            }
858
859            // Flatten any nested arrays
860            return flat( ret );
861        },
862
863        // A global GUID counter for objects
864        guid: 1,
865
866        // jQuery.support is not used in Core but other projects attach their
867        // properties to it so it needs to exist.
868        support: support
869    } );
870
871    if ( typeof Symbol === "function" ) {
872        jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ];
873    }
874
875// Populate the class2type map
876    jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ),
877        function( _i, name ) {
878            class2type[ "[object " + name + "]" ] = name.toLowerCase();
879        } );
880
881    function isArrayLike( obj ) {
882
vendor: 18,971 bytes, lines 883-1316
883        // Support: real iOS 8.2 only (not reproducible in simulator)
884        // `in` check used to prevent JIT error (gh-2145)
885        // hasOwn isn't used here due to false negatives
886        // regarding Nodelist length in IE
887        var length = !!obj && "length" in obj && obj.length,
888            type = toType( obj );
889
890        if ( isFunction( obj ) || isWindow( obj ) ) {
891            return false;
892        }
893
894        return type === "array" || length === 0 ||
895            typeof length === "number" && length > 0 && ( length - 1 ) in obj;
896    }
897    var Sizzle =
898        /*!
899 * Sizzle CSS Selector Engine v2.3.6
900 * https://sizzlejs.com/
901 *
902 * Copyright JS Foundation and other contributors
903 * Released under the MIT license
904 * https://js.foundation/
905 *
906 * Date: 2021-02-16
907 */
908        ( function( window ) {
909            var i,
910                support,
911                Expr,
912                getText,
913                isXML,
914                tokenize,
915                compile,
916                select,
917                outermostContext,
918                sortInput,
919                hasDuplicate,
920
921                // Local document vars
922                setDocument,
923                document,
924                docElem,
925                documentIsHTML,
926                rbuggyQSA,
927                rbuggyMatches,
928                matches,
929                contains,
930
931                // Instance-specific data
932                expando = "sizzle" + 1 * new Date(),
933                preferredDoc = window.document,
934                dirruns = 0,
935                done = 0,
936                classCache = createCache(),
937                tokenCache = createCache(),
938                compilerCache = createCache(),
939                nonnativeSelectorCache = createCache(),
940                sortOrder = function( a, b ) {
941                    if ( a === b ) {
942                        hasDuplicate = true;
943                    }
944                    return 0;
945                },
946
947                // Instance methods
948                hasOwn = ( {} ).hasOwnProperty,
949                arr = [],
950                pop = arr.pop,
951                pushNative = arr.push,
952                push = arr.push,
953                slice = arr.slice,
954
955                // Use a stripped-down indexOf as it's faster than native
956                // https://jsperf.com/thor-indexof-vs-for/5
957                indexOf = function( list, elem ) {
958                    var i = 0,
959                        len = list.length;
960                    for ( ; i < len; i++ ) {
961                        if ( list[ i ] === elem ) {
962                            return i;
963                        }
964                    }
965                    return -1;
966                },
967
968                booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" +
969                    "ismap|loop|multiple|open|readonly|required|scoped",
970
971                // Regular expressions
972
973                // http://www.w3.org/TR/css3-selectors/#whitespace
974                whitespace = "[\\x20\\t\\r\\n\\f]",
975
976                // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram
977                identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace +
978                    "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",
979
980                // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
981                attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace +
982
983                    // Operator (capture 2)
984                    "*([*^$|!~]?=)" + whitespace +
985
986                    // "Attribute values must be CSS identifiers [capture 5]
987                    // or strings [capture 3 or capture 4]"
988                    "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" +
989                    whitespace + "*\\]",
990
991                pseudos = ":(" + identifier + ")(?:\\((" +
992
993                    // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
994                    // 1. quoted (capture 3; capture 4 or capture 5)
995                    "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
996
997                    // 2. simple (capture 6)
998                    "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
999
1000                    // 3. anything else (capture 2)
1001                    ".*" +
1002                    ")\\)|)",
1003
1004                // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
1005                rwhitespace = new RegExp( whitespace + "+", "g" ),
1006                rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" +
1007                    whitespace + "+$", "g" ),
1008
1009                rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
1010                rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace +
1011                    "*" ),
1012                rdescend = new RegExp( whitespace + "|>" ),
1013
1014                rpseudo = new RegExp( pseudos ),
1015                ridentifier = new RegExp( "^" + identifier + "$" ),
1016
1017                matchExpr = {
1018                    "ID": new RegExp( "^#(" + identifier + ")" ),
1019                    "CLASS": new RegExp( "^\\.(" + identifier + ")" ),
1020                    "TAG": new RegExp( "^(" + identifier + "|[*])" ),
1021                    "ATTR": new RegExp( "^" + attributes ),
1022                    "PSEUDO": new RegExp( "^" + pseudos ),
1023                    "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" +
1024                        whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" +
1025                        whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
1026                    "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
1027
1028                    // For use in libraries implementing .is()
1029                    // We use this for POS matching in `select`
1030                    "needsContext": new RegExp( "^" + whitespace +
1031                        "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
1032                        "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
1033                },
1034
1035                rhtml = /HTML$/i,
1036                rinputs = /^(?:input|select|textarea|button)$/i,
1037                rheader = /^h\d$/i,
1038
1039                rnative = /^[^{]+\{\s*\[native \w/,
1040
1041                // Easily-parseable/retrievable ID or TAG or CLASS selectors
1042                rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
1043
1044                rsibling = /[+~]/,
1045
1046                // CSS escapes
1047                // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
1048                runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ),
1049                funescape = function( escape, nonHex ) {
1050                    var high = "0x" + escape.slice( 1 ) - 0x10000;
1051
1052                    return nonHex ?
1053
1054                        // Strip the backslash prefix from a non-hex escape sequence
1055                        nonHex :
1056
1057                        // Replace a hexadecimal escape sequence with the encoded Unicode code point
1058                        // Support: IE <=11+
1059                        // For values outside the Basic Multilingual Plane (BMP), manually construct a
1060                        // surrogate pair
1061                        high < 0 ?
1062                            String.fromCharCode( high + 0x10000 ) :
1063                            String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
1064                },
1065
1066                // CSS string/identifier serialization
1067                // https://drafts.csswg.org/cssom/#common-serializing-idioms
1068                rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,
1069                fcssescape = function( ch, asCodePoint ) {
1070                    if ( asCodePoint ) {
1071
1072                        // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
1073                        if ( ch === "\0" ) {
1074                            return "\uFFFD";
1075                        }
1076
1077                        // Control characters and (dependent upon position) numbers get escaped as code points
1078                        return ch.slice( 0, -1 ) + "\\" +
1079                            ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
1080                    }
1081
1082                    // Other potentially-special ASCII characters get backslash-escaped
1083                    return "\\" + ch;
1084                },
1085
1086                // Used for iframes
1087                // See setDocument()
1088                // Removing the function wrapper causes a "Permission Denied"
1089                // error in IE
1090                unloadHandler = function() {
1091                    setDocument();
1092                },
1093
1094                inDisabledFieldset = addCombinator(
1095                    function( elem ) {
1096                        return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset";
1097                    },
1098                    { dir: "parentNode", next: "legend" }
1099                );
1100
1101// Optimize for push.apply( _, NodeList )
1102            try {
1103                push.apply(
1104                    ( arr = slice.call( preferredDoc.childNodes ) ),
1105                    preferredDoc.childNodes
1106                );
1107
1108                // Support: Android<4.0
1109                // Detect silently failing push.apply
1110                // eslint-disable-next-line no-unused-expressions
1111                arr[ preferredDoc.childNodes.length ].nodeType;
1112            } catch ( e ) {
1113                push = { apply: arr.length ?
1114
1115                        // Leverage slice if possible
1116                        function( target, els ) {
1117                            pushNative.apply( target, slice.call( els ) );
1118                        } :
1119
1120                        // Support: IE<9
1121                        // Otherwise append directly
1122                        function( target, els ) {
1123                            var j = target.length,
1124                                i = 0;
1125
1126                            // Can't trust NodeList.length
1127                            while ( ( target[ j++ ] = els[ i++ ] ) ) {}
1128                            target.length = j - 1;
1129                        }
1130                };
1131            }
1132
1133            function Sizzle( selector, context, results, seed ) {
1134                var m, i, elem, nid, match, groups, newSelector,
1135                    newContext = context && context.ownerDocument,
1136
1137                    // nodeType defaults to 9, since context defaults to document
1138                    nodeType = context ? context.nodeType : 9;
1139
1140                results = results || [];
1141
1142                // Return early from calls with invalid selector or context
1143                if ( typeof selector !== "string" || !selector ||
1144                    nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) {
1145
1146                    return results;
1147                }
1148
1149                // Try to shortcut find operations (as opposed to filters) in HTML documents
1150                if ( !seed ) {
1151                    setDocument( context );
1152                    context = context || document;
1153
1154                    if ( documentIsHTML ) {
1155
1156                        // If the selector is sufficiently simple, try using a "get*By*" DOM method
1157                        // (excepting DocumentFragment context, where the methods don't exist)
1158                        if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) {
1159
1160                            // ID selector
1161                            if ( ( m = match[ 1 ] ) ) {
1162
1163                                // Document context
1164                                if ( nodeType === 9 ) {
1165                                    if ( ( elem = context.getElementById( m ) ) ) {
1166
1167                                        // Support: IE, Opera, Webkit
1168                                        // TODO: identify versions
1169                                        // getElementById can match elements by name instead of ID
1170                                        if ( elem.id === m ) {
1171                                            results.push( elem );
1172                                            return results;
1173                                        }
1174                                    } else {
1175                                        return results;
1176                                    }
1177
1178                                    // Element context
1179                                } else {
1180
1181                                    // Support: IE, Opera, Webkit
1182                                    // TODO: identify versions
1183                                    // getElementById can match elements by name instead of ID
1184                                    if ( newContext && ( elem = newContext.getElementById( m ) ) &&
1185                                        contains( context, elem ) &&
1186                                        elem.id === m ) {
1187
1188                                        results.push( elem );
1189                                        return results;
1190                                    }
1191                                }
1192
1193                                // Type selector
1194                            } else if ( match[ 2 ] ) {
1195                                push.apply( results, context.getElementsByTagName( selector ) );
1196                                return results;
1197
1198                                // Class selector
1199                            } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName &&
1200                                context.getElementsByClassName ) {
1201
1202                                push.apply( results, context.getElementsByClassName( m ) );
1203                                return results;
1204                            }
1205                        }
1206
1207                        // Take advantage of querySelectorAll
1208                        if ( support.qsa &&
1209                            !nonnativeSelectorCache[ selector + " " ] &&
1210                            ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) &&
1211
1212                            // Support: IE 8 only
1213                            // Exclude object elements
1214                            ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) {
1215
1216                            newSelector = selector;
1217                            newContext = context;
1218
1219                            // qSA considers elements outside a scoping root when evaluating child or
1220                            // descendant combinators, which is not what we want.
1221                            // In such cases, we work around the behavior by prefixing every selector in the
1222                            // list with an ID selector referencing the scope context.
1223                            // The technique has to be used as well when a leading combinator is used
1224                            // as such selectors are not recognized by querySelectorAll.
1225                            // Thanks to Andrew Dupont for this technique.
1226                            if ( nodeType === 1 &&
1227                                ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) {
1228
1229                                // Expand context for sibling selectors
1230                                newContext = rsibling.test( selector ) && testContext( context.parentNode ) ||
1231                                    context;
1232
1233                                // We can use :scope instead of the ID hack if the browser
1234                                // supports it & if we're not changing the context.
1235                                if ( newContext !== context || !support.scope ) {
1236
1237                                    // Capture the context ID, setting it first if necessary
1238                                    if ( ( nid = context.getAttribute( "id" ) ) ) {
1239                                        nid = nid.replace( rcssescape, fcssescape );
1240                                    } else {
1241                                        context.setAttribute( "id", ( nid = expando ) );
1242                                    }
1243                                }
1244
1245                                // Prefix every selector in the list
1246                                groups = tokenize( selector );
1247                                i = groups.length;
1248                                while ( i-- ) {
1249                                    groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " +
1250                                        toSelector( groups[ i ] );
1251                                }
1252                                newSelector = groups.join( "," );
1253                            }
1254
1255                            try {
1256                                push.apply( results,
1257                                    newContext.querySelectorAll( newSelector )
1258                                );
1259                                return results;
1260                            } catch ( qsaError ) {
1261                                nonnativeSelectorCache( selector, true );
1262                            } finally {
1263                                if ( nid === expando ) {
1264                                    context.removeAttribute( "id" );
1265                                }
1266                            }
1267                        }
1268                    }
1269                }
1270
1271                // All others
1272                return select( selector.replace( rtrim, "$1" ), context, results, seed );
1273            }
1274
1275            /**
1276             * Create key-value caches of limited size
1277             * @returns {function(string, object)} Returns the Object data after storing it on itself with
1278             *	property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
1279             *	deleting the oldest entry
1280             */
1281            function createCache() {
1282                var keys = [];
1283
1284                function cache( key, value ) {
1285
1286                    // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
1287                    if ( keys.push( key + " " ) > Expr.cacheLength ) {
1288
1289                        // Only keep the most recent entries
1290                        delete cache[ keys.shift() ];
1291                    }
1292                    return ( cache[ key + " " ] = value );
1293                }
1294                return cache;
1295            }
1296
1297            /**
1298             * Mark a function for special use by Sizzle
1299             * @param {Function} fn The function to mark
1300             */
1301            function markFunction( fn ) {
1302                fn[ expando ] = true;
1303                return fn;
1304            }
1305
1306            /**
1307             * Support testing using an element
1308             * @param {Function} fn Passed the created element and returns a boolean result
1309             */
1310            function assert( fn ) {
1311                var el = document.createElement( "fieldset" );
1312
1313                try {
1314                    return !!fn( el );
1315                } catch ( e ) {
1316                    return false;
vendor: 4,414 bytes, lines 1317-1424
1317                } finally {
1318
1319                    // Remove from its parent by default
1320                    if ( el.parentNode ) {
1321                        el.parentNode.removeChild( el );
1322                    }
1323
1324                    // release memory in IE
1325                    el = null;
1326                }
1327            }
1328
1329            /**
1330             * Adds the same handler for all of the specified attrs
1331             * @param {String} attrs Pipe-separated list of attributes
1332             * @param {Function} handler The method that will be applied
1333             */
1334            function addHandle( attrs, handler ) {
1335                var arr = attrs.split( "|" ),
1336                    i = arr.length;
1337
1338                while ( i-- ) {
1339                    Expr.attrHandle[ arr[ i ] ] = handler;
1340                }
1341            }
1342
1343            /**
1344             * Checks document order of two siblings
1345             * @param {Element} a
1346             * @param {Element} b
1347             * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
1348             */
1349            function siblingCheck( a, b ) {
1350                var cur = b && a,
1351                    diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
1352                        a.sourceIndex - b.sourceIndex;
1353
1354                // Use IE sourceIndex if available on both nodes
1355                if ( diff ) {
1356                    return diff;
1357                }
1358
1359                // Check if b follows a
1360                if ( cur ) {
1361                    while ( ( cur = cur.nextSibling ) ) {
1362                        if ( cur === b ) {
1363                            return -1;
1364                        }
1365                    }
1366                }
1367
1368                return a ? 1 : -1;
1369            }
1370
1371            /**
1372             * Returns a function to use in pseudos for input types
1373             * @param {String} type
1374             */
1375            function createInputPseudo( type ) {
1376                return function( elem ) {
1377                    var name = elem.nodeName.toLowerCase();
1378                    return name === "input" && elem.type === type;
1379                };
1380            }
1381
1382            /**
1383             * Returns a function to use in pseudos for buttons
1384             * @param {String} type
1385             */
1386            function createButtonPseudo( type ) {
1387                return function( elem ) {
1388                    var name = elem.nodeName.toLowerCase();
1389                    return ( name === "input" || name === "button" ) && elem.type === type;
1390                };
1391            }
1392
1393            /**
1394             * Returns a function to use in pseudos for :enabled/:disabled
1395             * @param {Boolean} disabled true for :disabled; false for :enabled
1396             */
1397            function createDisabledPseudo( disabled ) {
1398
1399                // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable
1400                return function( elem ) {
1401
1402                    // Only certain elements can match :enabled or :disabled
1403                    // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled
1404                    // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled
1405                    if ( "form" in elem ) {
1406
1407                        // Check for inherited disabledness on relevant non-disabled elements:
1408                        // * listed form-associated elements in a disabled fieldset
1409                        //   https://html.spec.whatwg.org/multipage/forms.html#category-listed
1410                        //   https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled
1411                        // * option elements in a disabled optgroup
1412                        //   https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled
1413                        // All such elements have a "form" property.
1414                        if ( elem.parentNode && elem.disabled === false ) {
1415
1416                            // Option elements defer to a parent optgroup if present
1417                            if ( "label" in elem ) {
1418                                if ( "label" in elem.parentNode ) {
1419                                    return elem.parentNode.disabled === disabled;
1420                                } else {
1421                                    return elem.disabled === disabled;
1422                                }
1423                            }
1424
vendor: 32,617 bytes, lines 1425-2125
1425                            // Support: IE 6 - 11
1426                            // Use the isDisabled shortcut property to check for disabled fieldset ancestors
1427                            return elem.isDisabled === disabled ||
1428
1429                                // Where there is no isDisabled, check manually
1430                                /* jshint -W018 */
1431                                elem.isDisabled !== !disabled &&
1432                                inDisabledFieldset( elem ) === disabled;
1433                        }
1434
1435                        return elem.disabled === disabled;
1436
1437                        // Try to winnow out elements that can't be disabled before trusting the disabled property.
1438                        // Some victims get caught in our net (label, legend, menu, track), but it shouldn't
1439                        // even exist on them, let alone have a boolean value.
1440                    } else if ( "label" in elem ) {
1441                        return elem.disabled === disabled;
1442                    }
1443
1444                    // Remaining elements are neither :enabled nor :disabled
1445                    return false;
1446                };
1447            }
1448
1449            /**
1450             * Returns a function to use in pseudos for positionals
1451             * @param {Function} fn
1452             */
1453            function createPositionalPseudo( fn ) {
1454                return markFunction( function( argument ) {
1455                    argument = +argument;
1456                    return markFunction( function( seed, matches ) {
1457                        var j,
1458                            matchIndexes = fn( [], seed.length, argument ),
1459                            i = matchIndexes.length;
1460
1461                        // Match elements found at the specified indexes
1462                        while ( i-- ) {
1463                            if ( seed[ ( j = matchIndexes[ i ] ) ] ) {
1464                                seed[ j ] = !( matches[ j ] = seed[ j ] );
1465                            }
1466                        }
1467                    } );
1468                } );
1469            }
1470
1471            /**
1472             * Checks a node for validity as a Sizzle context
1473             * @param {Element|Object=} context
1474             * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
1475             */
1476            function testContext( context ) {
1477                return context && typeof context.getElementsByTagName !== "undefined" && context;
1478            }
1479
1480// Expose support vars for convenience
1481            support = Sizzle.support = {};
1482
1483            /**
1484             * Detects XML nodes
1485             * @param {Element|Object} elem An element or a document
1486             * @returns {Boolean} True iff elem is a non-HTML XML node
1487             */
1488            isXML = Sizzle.isXML = function( elem ) {
1489                var namespace = elem && elem.namespaceURI,
1490                    docElem = elem && ( elem.ownerDocument || elem ).documentElement;
1491
1492                // Support: IE <=8
1493                // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes
1494                // https://bugs.jquery.com/ticket/4833
1495                return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" );
1496            };
1497
1498            /**
1499             * Sets document-related variables once based on the current document
1500             * @param {Element|Object} [doc] An element or document object to use to set the document
1501             * @returns {Object} Returns the current document
1502             */
1503            setDocument = Sizzle.setDocument = function( node ) {
1504                var hasCompare, subWindow,
1505                    doc = node ? node.ownerDocument || node : preferredDoc;
1506
1507                // Return early if doc is invalid or already selected
1508                // Support: IE 11+, Edge 17 - 18+
1509                // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1510                // two documents; shallow comparisons work.
1511                // eslint-disable-next-line eqeqeq
1512                if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) {
1513                    return document;
1514                }
1515
1516                // Update global variables
1517                document = doc;
1518                docElem = document.documentElement;
1519                documentIsHTML = !isXML( document );
1520
1521                // Support: IE 9 - 11+, Edge 12 - 18+
1522                // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936)
1523                // Support: IE 11+, Edge 17 - 18+
1524                // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1525                // two documents; shallow comparisons work.
1526                // eslint-disable-next-line eqeqeq
1527                if ( preferredDoc != document &&
1528                    ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) {
1529
1530                    // Support: IE 11, Edge
1531                    if ( subWindow.addEventListener ) {
1532                        subWindow.addEventListener( "unload", unloadHandler, false );
1533
1534                        // Support: IE 9 - 10 only
1535                    } else if ( subWindow.attachEvent ) {
1536                        subWindow.attachEvent( "onunload", unloadHandler );
1537                    }
1538                }
1539
1540                // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only,
1541                // Safari 4 - 5 only, Opera <=11.6 - 12.x only
1542                // IE/Edge & older browsers don't support the :scope pseudo-class.
1543                // Support: Safari 6.0 only
1544                // Safari 6.0 supports :scope but it's an alias of :root there.
1545                support.scope = assert( function( el ) {
1546                    docElem.appendChild( el ).appendChild( document.createElement( "div" ) );
1547                    return typeof el.querySelectorAll !== "undefined" &&
1548                        !el.querySelectorAll( ":scope fieldset div" ).length;
1549                } );
1550
1551                /* Attributes
1552	---------------------------------------------------------------------- */
1553
1554                // Support: IE<8
1555                // Verify that getAttribute really returns attributes and not properties
1556                // (excepting IE8 booleans)
1557                support.attributes = assert( function( el ) {
1558                    el.className = "i";
1559                    return !el.getAttribute( "className" );
1560                } );
1561
1562                /* getElement(s)By*
1563	---------------------------------------------------------------------- */
1564
1565                // Check if getElementsByTagName("*") returns only elements
1566                support.getElementsByTagName = assert( function( el ) {
1567                    el.appendChild( document.createComment( "" ) );
1568                    return !el.getElementsByTagName( "*" ).length;
1569                } );
1570
1571                // Support: IE<9
1572                support.getElementsByClassName = rnative.test( document.getElementsByClassName );
1573
1574                // Support: IE<10
1575                // Check if getElementById returns elements by name
1576                // The broken getElementById methods don't pick up programmatically-set names,
1577                // so use a roundabout getElementsByName test
1578                support.getById = assert( function( el ) {
1579                    docElem.appendChild( el ).id = expando;
1580                    return !document.getElementsByName || !document.getElementsByName( expando ).length;
1581                } );
1582
1583                // ID filter and find
1584                if ( support.getById ) {
1585                    Expr.filter[ "ID" ] = function( id ) {
1586                        var attrId = id.replace( runescape, funescape );
1587                        return function( elem ) {
1588                            return elem.getAttribute( "id" ) === attrId;
1589                        };
1590                    };
1591                    Expr.find[ "ID" ] = function( id, context ) {
1592                        if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
1593                            var elem = context.getElementById( id );
1594                            return elem ? [ elem ] : [];
1595                        }
1596                    };
1597                } else {
1598                    Expr.filter[ "ID" ] =  function( id ) {
1599                        var attrId = id.replace( runescape, funescape );
1600                        return function( elem ) {
1601                            var node = typeof elem.getAttributeNode !== "undefined" &&
1602                                elem.getAttributeNode( "id" );
1603                            return node && node.value === attrId;
1604                        };
1605                    };
1606
1607                    // Support: IE 6 - 7 only
1608                    // getElementById is not reliable as a find shortcut
1609                    Expr.find[ "ID" ] = function( id, context ) {
1610                        if ( typeof context.getElementById !== "undefined" && documentIsHTML ) {
1611                            var node, i, elems,
1612                                elem = context.getElementById( id );
1613
1614                            if ( elem ) {
1615
1616                                // Verify the id attribute
1617                                node = elem.getAttributeNode( "id" );
1618                                if ( node && node.value === id ) {
1619                                    return [ elem ];
1620                                }
1621
1622                                // Fall back on getElementsByName
1623                                elems = context.getElementsByName( id );
1624                                i = 0;
1625                                while ( ( elem = elems[ i++ ] ) ) {
1626                                    node = elem.getAttributeNode( "id" );
1627                                    if ( node && node.value === id ) {
1628                                        return [ elem ];
1629                                    }
1630                                }
1631                            }
1632
1633                            return [];
1634                        }
1635                    };
1636                }
1637
1638                // Tag
1639                Expr.find[ "TAG" ] = support.getElementsByTagName ?
1640                    function( tag, context ) {
1641                        if ( typeof context.getElementsByTagName !== "undefined" ) {
1642                            return context.getElementsByTagName( tag );
1643
1644                            // DocumentFragment nodes don't have gEBTN
1645                        } else if ( support.qsa ) {
1646                            return context.querySelectorAll( tag );
1647                        }
1648                    } :
1649
1650                    function( tag, context ) {
1651                        var elem,
1652                            tmp = [],
1653                            i = 0,
1654
1655                            // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too
1656                            results = context.getElementsByTagName( tag );
1657
1658                        // Filter out possible comments
1659                        if ( tag === "*" ) {
1660                            while ( ( elem = results[ i++ ] ) ) {
1661                                if ( elem.nodeType === 1 ) {
1662                                    tmp.push( elem );
1663                                }
1664                            }
1665
1666                            return tmp;
1667                        }
1668                        return results;
1669                    };
1670
1671                // Class
1672                Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) {
1673                    if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) {
1674                        return context.getElementsByClassName( className );
1675                    }
1676                };
1677
1678                /* QSA/matchesSelector
1679	---------------------------------------------------------------------- */
1680
1681                // QSA and matchesSelector support
1682
1683                // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
1684                rbuggyMatches = [];
1685
1686                // qSa(:focus) reports false when true (Chrome 21)
1687                // We allow this because of a bug in IE8/9 that throws an error
1688                // whenever `document.activeElement` is accessed on an iframe
1689                // So, we allow :focus to pass through QSA all the time to avoid the IE error
1690                // See https://bugs.jquery.com/ticket/13378
1691                rbuggyQSA = [];
1692
1693                if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) {
1694
1695                    // Build QSA regex
1696                    // Regex strategy adopted from Diego Perini
1697                    assert( function( el ) {
1698
1699                        var input;
1700
1701                        // Select is set to empty string on purpose
1702                        // This is to test IE's treatment of not explicitly
1703                        // setting a boolean content attribute,
1704                        // since its presence should be enough
1705                        // https://bugs.jquery.com/ticket/12359
1706                        docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" +
1707                            "<select id='" + expando + "-\r\\' msallowcapture=''>" +
1708                            "<option selected=''></option></select>";
1709
1710                        // Support: IE8, Opera 11-12.16
1711                        // Nothing should be selected when empty strings follow ^= or $= or *=
1712                        // The test attribute must be unknown in Opera but "safe" for WinRT
1713                        // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
1714                        if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) {
1715                            rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
1716                        }
1717
1718                        // Support: IE8
1719                        // Boolean attributes and "value" are not treated correctly
1720                        if ( !el.querySelectorAll( "[selected]" ).length ) {
1721                            rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
1722                        }
1723
1724                        // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+
1725                        if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) {
1726                            rbuggyQSA.push( "~=" );
1727                        }
1728
1729                        // Support: IE 11+, Edge 15 - 18+
1730                        // IE 11/Edge don't find elements on a `[name='']` query in some cases.
1731                        // Adding a temporary attribute to the document before the selection works
1732                        // around the issue.
1733                        // Interestingly, IE 10 & older don't seem to have the issue.
1734                        input = document.createElement( "input" );
1735                        input.setAttribute( "name", "" );
1736                        el.appendChild( input );
1737                        if ( !el.querySelectorAll( "[name='']" ).length ) {
1738                            rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" +
1739                                whitespace + "*(?:''|\"\")" );
1740                        }
1741
1742                        // Webkit/Opera - :checked should return selected option elements
1743                        // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
1744                        // IE8 throws error here and will not see later tests
1745                        if ( !el.querySelectorAll( ":checked" ).length ) {
1746                            rbuggyQSA.push( ":checked" );
1747                        }
1748
1749                        // Support: Safari 8+, iOS 8+
1750                        // https://bugs.webkit.org/show_bug.cgi?id=136851
1751                        // In-page `selector#id sibling-combinator selector` fails
1752                        if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) {
1753                            rbuggyQSA.push( ".#.+[+~]" );
1754                        }
1755
1756                        // Support: Firefox <=3.6 - 5 only
1757                        // Old Firefox doesn't throw on a badly-escaped identifier.
1758                        el.querySelectorAll( "\\\f" );
1759                        rbuggyQSA.push( "[\\r\\n\\f]" );
1760                    } );
1761
1762                    assert( function( el ) {
1763                        el.innerHTML = "<a href='' disabled='disabled'></a>" +
1764                            "<select disabled='disabled'><option/></select>";
1765
1766                        // Support: Windows 8 Native Apps
1767                        // The type and name attributes are restricted during .innerHTML assignment
1768                        var input = document.createElement( "input" );
1769                        input.setAttribute( "type", "hidden" );
1770                        el.appendChild( input ).setAttribute( "name", "D" );
1771
1772                        // Support: IE8
1773                        // Enforce case-sensitivity of name attribute
1774                        if ( el.querySelectorAll( "[name=d]" ).length ) {
1775                            rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
1776                        }
1777
1778                        // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
1779                        // IE8 throws error here and will not see later tests
1780                        if ( el.querySelectorAll( ":enabled" ).length !== 2 ) {
1781                            rbuggyQSA.push( ":enabled", ":disabled" );
1782                        }
1783
1784                        // Support: IE9-11+
1785                        // IE's :disabled selector does not pick up the children of disabled fieldsets
1786                        docElem.appendChild( el ).disabled = true;
1787                        if ( el.querySelectorAll( ":disabled" ).length !== 2 ) {
1788                            rbuggyQSA.push( ":enabled", ":disabled" );
1789                        }
1790
1791                        // Support: Opera 10 - 11 only
1792                        // Opera 10-11 does not throw on post-comma invalid pseudos
1793                        el.querySelectorAll( "*,:x" );
1794                        rbuggyQSA.push( ",.*:" );
1795                    } );
1796                }
1797
1798                if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches ||
1799                    docElem.webkitMatchesSelector ||
1800                    docElem.mozMatchesSelector ||
1801                    docElem.oMatchesSelector ||
1802                    docElem.msMatchesSelector ) ) ) ) {
1803
1804                    assert( function( el ) {
1805
1806                        // Check to see if it's possible to do matchesSelector
1807                        // on a disconnected node (IE 9)
1808                        support.disconnectedMatch = matches.call( el, "*" );
1809
1810                        // This should fail with an exception
1811                        // Gecko does not error, returns false instead
1812                        matches.call( el, "[s!='']:x" );
1813                        rbuggyMatches.push( "!=", pseudos );
1814                    } );
1815                }
1816
1817                rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) );
1818                rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) );
1819
1820                /* Contains
1821	---------------------------------------------------------------------- */
1822                hasCompare = rnative.test( docElem.compareDocumentPosition );
1823
1824                // Element contains another
1825                // Purposefully self-exclusive
1826                // As in, an element does not contain itself
1827                contains = hasCompare || rnative.test( docElem.contains ) ?
1828                    function( a, b ) {
1829                        var adown = a.nodeType === 9 ? a.documentElement : a,
1830                            bup = b && b.parentNode;
1831                        return a === bup || !!( bup && bup.nodeType === 1 && (
1832                            adown.contains ?
1833                                adown.contains( bup ) :
1834                                a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
1835                        ) );
1836                    } :
1837                    function( a, b ) {
1838                        if ( b ) {
1839                            while ( ( b = b.parentNode ) ) {
1840                                if ( b === a ) {
1841                                    return true;
1842                                }
1843                            }
1844                        }
1845                        return false;
1846                    };
1847
1848                /* Sorting
1849	---------------------------------------------------------------------- */
1850
1851                // Document order sorting
1852                sortOrder = hasCompare ?
1853                    function( a, b ) {
1854
1855                        // Flag for duplicate removal
1856                        if ( a === b ) {
1857                            hasDuplicate = true;
1858                            return 0;
1859                        }
1860
1861                        // Sort on method existence if only one input has compareDocumentPosition
1862                        var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
1863                        if ( compare ) {
1864                            return compare;
1865                        }
1866
1867                        // Calculate position if both inputs belong to the same document
1868                        // Support: IE 11+, Edge 17 - 18+
1869                        // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1870                        // two documents; shallow comparisons work.
1871                        // eslint-disable-next-line eqeqeq
1872                        compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ?
1873                            a.compareDocumentPosition( b ) :
1874
1875                            // Otherwise we know they are disconnected
1876                            1;
1877
1878                        // Disconnected nodes
1879                        if ( compare & 1 ||
1880                            ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) {
1881
1882                            // Choose the first element that is related to our preferred document
1883                            // Support: IE 11+, Edge 17 - 18+
1884                            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1885                            // two documents; shallow comparisons work.
1886                            // eslint-disable-next-line eqeqeq
1887                            if ( a == document || a.ownerDocument == preferredDoc &&
1888                                contains( preferredDoc, a ) ) {
1889                                return -1;
1890                            }
1891
1892                            // Support: IE 11+, Edge 17 - 18+
1893                            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1894                            // two documents; shallow comparisons work.
1895                            // eslint-disable-next-line eqeqeq
1896                            if ( b == document || b.ownerDocument == preferredDoc &&
1897                                contains( preferredDoc, b ) ) {
1898                                return 1;
1899                            }
1900
1901                            // Maintain original order
1902                            return sortInput ?
1903                                ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1904                                0;
1905                        }
1906
1907                        return compare & 4 ? -1 : 1;
1908                    } :
1909                    function( a, b ) {
1910
1911                        // Exit early if the nodes are identical
1912                        if ( a === b ) {
1913                            hasDuplicate = true;
1914                            return 0;
1915                        }
1916
1917                        var cur,
1918                            i = 0,
1919                            aup = a.parentNode,
1920                            bup = b.parentNode,
1921                            ap = [ a ],
1922                            bp = [ b ];
1923
1924                        // Parentless nodes are either documents or disconnected
1925                        if ( !aup || !bup ) {
1926
1927                            // Support: IE 11+, Edge 17 - 18+
1928                            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1929                            // two documents; shallow comparisons work.
1930                            /* eslint-disable eqeqeq */
1931                            return a == document ? -1 :
1932                                b == document ? 1 :
1933                                    /* eslint-enable eqeqeq */
1934                                    aup ? -1 :
1935                                        bup ? 1 :
1936                                            sortInput ?
1937                                                ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) :
1938                                                0;
1939
1940                            // If the nodes are siblings, we can do a quick check
1941                        } else if ( aup === bup ) {
1942                            return siblingCheck( a, b );
1943                        }
1944
1945                        // Otherwise we need full lists of their ancestors for comparison
1946                        cur = a;
1947                        while ( ( cur = cur.parentNode ) ) {
1948                            ap.unshift( cur );
1949                        }
1950                        cur = b;
1951                        while ( ( cur = cur.parentNode ) ) {
1952                            bp.unshift( cur );
1953                        }
1954
1955                        // Walk down the tree looking for a discrepancy
1956                        while ( ap[ i ] === bp[ i ] ) {
1957                            i++;
1958                        }
1959
1960                        return i ?
1961
1962                            // Do a sibling check if the nodes have a common ancestor
1963                            siblingCheck( ap[ i ], bp[ i ] ) :
1964
1965                            // Otherwise nodes in our document sort first
1966                            // Support: IE 11+, Edge 17 - 18+
1967                            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
1968                            // two documents; shallow comparisons work.
1969                            /* eslint-disable eqeqeq */
1970                            ap[ i ] == preferredDoc ? -1 :
1971                                bp[ i ] == preferredDoc ? 1 :
1972                                    /* eslint-enable eqeqeq */
1973                                    0;
1974                    };
1975
1976                return document;
1977            };
1978
1979            Sizzle.matches = function( expr, elements ) {
1980                return Sizzle( expr, null, null, elements );
1981            };
1982
1983            Sizzle.matchesSelector = function( elem, expr ) {
1984                setDocument( elem );
1985
1986                if ( support.matchesSelector && documentIsHTML &&
1987                    !nonnativeSelectorCache[ expr + " " ] &&
1988                    ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
1989                    ( !rbuggyQSA     || !rbuggyQSA.test( expr ) ) ) {
1990
1991                    try {
1992                        var ret = matches.call( elem, expr );
1993
1994                        // IE 9's matchesSelector returns false on disconnected nodes
1995                        if ( ret || support.disconnectedMatch ||
1996
1997                            // As well, disconnected nodes are said to be in a document
1998                            // fragment in IE 9
1999                            elem.document && elem.document.nodeType !== 11 ) {
2000                            return ret;
2001                        }
2002                    } catch ( e ) {
2003                        nonnativeSelectorCache( expr, true );
2004                    }
2005                }
2006
2007                return Sizzle( expr, document, null, [ elem ] ).length > 0;
2008            };
2009
2010            Sizzle.contains = function( context, elem ) {
2011
2012                // Set document vars if needed
2013                // Support: IE 11+, Edge 17 - 18+
2014                // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
2015                // two documents; shallow comparisons work.
2016                // eslint-disable-next-line eqeqeq
2017                if ( ( context.ownerDocument || context ) != document ) {
2018                    setDocument( context );
2019                }
2020                return contains( context, elem );
2021            };
2022
2023            Sizzle.attr = function( elem, name ) {
2024
2025                // Set document vars if needed
2026                // Support: IE 11+, Edge 17 - 18+
2027                // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
2028                // two documents; shallow comparisons work.
2029                // eslint-disable-next-line eqeqeq
2030                if ( ( elem.ownerDocument || elem ) != document ) {
2031                    setDocument( elem );
2032                }
2033
2034                var fn = Expr.attrHandle[ name.toLowerCase() ],
2035
2036                    // Don't get fooled by Object.prototype properties (jQuery #13807)
2037                    val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
2038                        fn( elem, name, !documentIsHTML ) :
2039                        undefined;
2040
2041                return val !== undefined ?
2042                    val :
2043                    support.attributes || !documentIsHTML ?
2044                        elem.getAttribute( name ) :
2045                        ( val = elem.getAttributeNode( name ) ) && val.specified ?
2046                            val.value :
2047                            null;
2048            };
2049
2050            Sizzle.escape = function( sel ) {
2051                return ( sel + "" ).replace( rcssescape, fcssescape );
2052            };
2053
2054            Sizzle.error = function( msg ) {
2055                throw new Error( "Syntax error, unrecognized expression: " + msg );
2056            };
2057
2058            /**
2059             * Document sorting and removing duplicates
2060             * @param {ArrayLike} results
2061             */
2062            Sizzle.uniqueSort = function( results ) {
2063                var elem,
2064                    duplicates = [],
2065                    j = 0,
2066                    i = 0;
2067
2068                // Unless we *know* we can detect duplicates, assume their presence
2069                hasDuplicate = !support.detectDuplicates;
2070                sortInput = !support.sortStable && results.slice( 0 );
2071                results.sort( sortOrder );
2072
2073                if ( hasDuplicate ) {
2074                    while ( ( elem = results[ i++ ] ) ) {
2075                        if ( elem === results[ i ] ) {
2076                            j = duplicates.push( i );
2077                        }
2078                    }
2079                    while ( j-- ) {
2080                        results.splice( duplicates[ j ], 1 );
2081                    }
2082                }
2083
2084                // Clear input after sorting to release objects
2085                // See https://github.com/jquery/sizzle/pull/225
2086                sortInput = null;
2087
2088                return results;
2089            };
2090
2091            /**
2092             * Utility function for retrieving the text value of an array of DOM nodes
2093             * @param {Array|Element} elem
2094             */
2095            getText = Sizzle.getText = function( elem ) {
2096                var node,
2097                    ret = "",
2098                    i = 0,
2099                    nodeType = elem.nodeType;
2100
2101                if ( !nodeType ) {
2102
2103                    // If no nodeType, this is expected to be an array
2104                    while ( ( node = elem[ i++ ] ) ) {
2105
2106                        // Do not traverse comment nodes
2107                        ret += getText( node );
2108                    }
2109                } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
2110
2111                    // Use textContent for elements
2112                    // innerText usage removed for consistency of new lines (jQuery #11153)
2113                    if ( typeof elem.textContent === "string" ) {
2114                        return elem.textContent;
2115                    } else {
2116
2117                        // Traverse its children
2118                        for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
2119                            ret += getText( elem );
2120                        }
2121                    }
2122                } else if ( nodeType === 3 || nodeType === 4 ) {
2123                    return elem.nodeValue;
2124                }
2125
vendor: 13,229 bytes, lines 2126-2400
2126                // Do not include comment or processing instruction nodes
2127
2128                return ret;
2129            };
2130
2131            Expr = Sizzle.selectors = {
2132
2133                // Can be adjusted by the user
2134                cacheLength: 50,
2135
2136                createPseudo: markFunction,
2137
2138                match: matchExpr,
2139
2140                attrHandle: {},
2141
2142                find: {},
2143
2144                relative: {
2145                    ">": { dir: "parentNode", first: true },
2146                    " ": { dir: "parentNode" },
2147                    "+": { dir: "previousSibling", first: true },
2148                    "~": { dir: "previousSibling" }
2149                },
2150
2151                preFilter: {
2152                    "ATTR": function( match ) {
2153                        match[ 1 ] = match[ 1 ].replace( runescape, funescape );
2154
2155                        // Move the given value to match[3] whether quoted or unquoted
2156                        match[ 3 ] = ( match[ 3 ] || match[ 4 ] ||
2157                            match[ 5 ] || "" ).replace( runescape, funescape );
2158
2159                        if ( match[ 2 ] === "~=" ) {
2160                            match[ 3 ] = " " + match[ 3 ] + " ";
2161                        }
2162
2163                        return match.slice( 0, 4 );
2164                    },
2165
2166                    "CHILD": function( match ) {
2167
2168                        /* matches from matchExpr["CHILD"]
2169				1 type (only|nth|...)
2170				2 what (child|of-type)
2171				3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
2172				4 xn-component of xn+y argument ([+-]?\d*n|)
2173				5 sign of xn-component
2174				6 x of xn-component
2175				7 sign of y-component
2176				8 y of y-component
2177			*/
2178                        match[ 1 ] = match[ 1 ].toLowerCase();
2179
2180                        if ( match[ 1 ].slice( 0, 3 ) === "nth" ) {
2181
2182                            // nth-* requires argument
2183                            if ( !match[ 3 ] ) {
2184                                Sizzle.error( match[ 0 ] );
2185                            }
2186
2187                            // numeric x and y parameters for Expr.filter.CHILD
2188                            // remember that false/true cast respectively to 0/1
2189                            match[ 4 ] = +( match[ 4 ] ?
2190                                match[ 5 ] + ( match[ 6 ] || 1 ) :
2191                                2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) );
2192                            match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" );
2193
2194                            // other types prohibit arguments
2195                        } else if ( match[ 3 ] ) {
2196                            Sizzle.error( match[ 0 ] );
2197                        }
2198
2199                        return match;
2200                    },
2201
2202                    "PSEUDO": function( match ) {
2203                        var excess,
2204                            unquoted = !match[ 6 ] && match[ 2 ];
2205
2206                        if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) {
2207                            return null;
2208                        }
2209
2210                        // Accept quoted arguments as-is
2211                        if ( match[ 3 ] ) {
2212                            match[ 2 ] = match[ 4 ] || match[ 5 ] || "";
2213
2214                            // Strip excess characters from unquoted arguments
2215                        } else if ( unquoted && rpseudo.test( unquoted ) &&
2216
2217                            // Get excess from tokenize (recursively)
2218                            ( excess = tokenize( unquoted, true ) ) &&
2219
2220                            // advance to the next closing parenthesis
2221                            ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) {
2222
2223                            // excess is a negative index
2224                            match[ 0 ] = match[ 0 ].slice( 0, excess );
2225                            match[ 2 ] = unquoted.slice( 0, excess );
2226                        }
2227
2228                        // Return only captures needed by the pseudo filter method (type and argument)
2229                        return match.slice( 0, 3 );
2230                    }
2231                },
2232
2233                filter: {
2234
2235                    "TAG": function( nodeNameSelector ) {
2236                        var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
2237                        return nodeNameSelector === "*" ?
2238                            function() {
2239                                return true;
2240                            } :
2241                            function( elem ) {
2242                                return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
2243                            };
2244                    },
2245
2246                    "CLASS": function( className ) {
2247                        var pattern = classCache[ className + " " ];
2248
2249                        return pattern ||
2250                            ( pattern = new RegExp( "(^|" + whitespace +
2251                                ")" + className + "(" + whitespace + "|$)" ) ) && classCache(
2252                                className, function( elem ) {
2253                                    return pattern.test(
2254                                        typeof elem.className === "string" && elem.className ||
2255                                        typeof elem.getAttribute !== "undefined" &&
2256                                        elem.getAttribute( "class" ) ||
2257                                        ""
2258                                    );
2259                                } );
2260                    },
2261
2262                    "ATTR": function( name, operator, check ) {
2263                        return function( elem ) {
2264                            var result = Sizzle.attr( elem, name );
2265
2266                            if ( result == null ) {
2267                                return operator === "!=";
2268                            }
2269                            if ( !operator ) {
2270                                return true;
2271                            }
2272
2273                            result += "";
2274
2275                            /* eslint-disable max-len */
2276
2277                            return operator === "=" ? result === check :
2278                                operator === "!=" ? result !== check :
2279                                    operator === "^=" ? check && result.indexOf( check ) === 0 :
2280                                        operator === "*=" ? check && result.indexOf( check ) > -1 :
2281                                            operator === "$=" ? check && result.slice( -check.length ) === check :
2282                                                operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 :
2283                                                    operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
2284                                                        false;
2285                            /* eslint-enable max-len */
2286
2287                        };
2288                    },
2289
2290                    "CHILD": function( type, what, _argument, first, last ) {
2291                        var simple = type.slice( 0, 3 ) !== "nth",
2292                            forward = type.slice( -4 ) !== "last",
2293                            ofType = what === "of-type";
2294
2295                        return first === 1 && last === 0 ?
2296
2297                            // Shortcut for :nth-*(n)
2298                            function( elem ) {
2299                                return !!elem.parentNode;
2300                            } :
2301
2302                            function( elem, _context, xml ) {
2303                                var cache, uniqueCache, outerCache, node, nodeIndex, start,
2304                                    dir = simple !== forward ? "nextSibling" : "previousSibling",
2305                                    parent = elem.parentNode,
2306                                    name = ofType && elem.nodeName.toLowerCase(),
2307                                    useCache = !xml && !ofType,
2308                                    diff = false;
2309
2310                                if ( parent ) {
2311
2312                                    // :(first|last|only)-(child|of-type)
2313                                    if ( simple ) {
2314                                        while ( dir ) {
2315                                            node = elem;
2316                                            while ( ( node = node[ dir ] ) ) {
2317                                                if ( ofType ?
2318                                                    node.nodeName.toLowerCase() === name :
2319                                                    node.nodeType === 1 ) {
2320
2321                                                    return false;
2322                                                }
2323                                            }
2324
2325                                            // Reverse direction for :only-* (if we haven't yet done so)
2326                                            start = dir = type === "only" && !start && "nextSibling";
2327                                        }
2328                                        return true;
2329                                    }
2330
2331                                    start = [ forward ? parent.firstChild : parent.lastChild ];
2332
2333                                    // non-xml :nth-child(...) stores cache data on `parent`
2334                                    if ( forward && useCache ) {
2335
2336                                        // Seek `elem` from a previously-cached index
2337
2338                                        // ...in a gzip-friendly way
2339                                        node = parent;
2340                                        outerCache = node[ expando ] || ( node[ expando ] = {} );
2341
2342                                        // Support: IE <9 only
2343                                        // Defend against cloned attroperties (jQuery gh-1709)
2344                                        uniqueCache = outerCache[ node.uniqueID ] ||
2345                                            ( outerCache[ node.uniqueID ] = {} );
2346
2347                                        cache = uniqueCache[ type ] || [];
2348                                        nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
2349                                        diff = nodeIndex && cache[ 2 ];
2350                                        node = nodeIndex && parent.childNodes[ nodeIndex ];
2351
2352                                        while ( ( node = ++nodeIndex && node && node[ dir ] ||
2353
2354                                            // Fallback to seeking `elem` from the start
2355                                            ( diff = nodeIndex = 0 ) || start.pop() ) ) {
2356
2357                                            // When found, cache indexes on `parent` and break
2358                                            if ( node.nodeType === 1 && ++diff && node === elem ) {
2359                                                uniqueCache[ type ] = [ dirruns, nodeIndex, diff ];
2360                                                break;
2361                                            }
2362                                        }
2363
2364                                    } else {
2365
2366                                        // Use previously-cached element index if available
2367                                        if ( useCache ) {
2368
2369                                            // ...in a gzip-friendly way
2370                                            node = elem;
2371                                            outerCache = node[ expando ] || ( node[ expando ] = {} );
2372
2373                                            // Support: IE <9 only
2374                                            // Defend against cloned attroperties (jQuery gh-1709)
2375                                            uniqueCache = outerCache[ node.uniqueID ] ||
2376                                                ( outerCache[ node.uniqueID ] = {} );
2377
2378                                            cache = uniqueCache[ type ] || [];
2379                                            nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ];
2380                                            diff = nodeIndex;
2381                                        }
2382
2383                                        // xml :nth-child(...)
2384                                        // or :nth-last-child(...) or :nth(-last)?-of-type(...)
2385                                        if ( diff === false ) {
2386
2387                                            // Use the same loop as above to seek `elem` from the start
2388                                            while ( ( node = ++nodeIndex && node && node[ dir ] ||
2389                                                ( diff = nodeIndex = 0 ) || start.pop() ) ) {
2390
2391                                                if ( ( ofType ?
2392                                                    node.nodeName.toLowerCase() === name :
2393                                                    node.nodeType === 1 ) &&
2394                                                    ++diff ) {
2395
2396                                                    // Cache the index of each encountered element
2397                                                    if ( useCache ) {
2398                                                        outerCache = node[ expando ] ||
2399                                                            ( node[ expando ] = {} );
2400
vendor: 14,491 bytes, lines 2401-2716
2401                                                        // Support: IE <9 only
2402                                                        // Defend against cloned attroperties (jQuery gh-1709)
2403                                                        uniqueCache = outerCache[ node.uniqueID ] ||
2404                                                            ( outerCache[ node.uniqueID ] = {} );
2405
2406                                                        uniqueCache[ type ] = [ dirruns, diff ];
2407                                                    }
2408
2409                                                    if ( node === elem ) {
2410                                                        break;
2411                                                    }
2412                                                }
2413                                            }
2414                                        }
2415                                    }
2416
2417                                    // Incorporate the offset, then check against cycle size
2418                                    diff -= last;
2419                                    return diff === first || ( diff % first === 0 && diff / first >= 0 );
2420                                }
2421                            };
2422                    },
2423
2424                    "PSEUDO": function( pseudo, argument ) {
2425
2426                        // pseudo-class names are case-insensitive
2427                        // http://www.w3.org/TR/selectors/#pseudo-classes
2428                        // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
2429                        // Remember that setFilters inherits from pseudos
2430                        var args,
2431                            fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
2432                                Sizzle.error( "unsupported pseudo: " + pseudo );
2433
2434                        // The user may use createPseudo to indicate that
2435                        // arguments are needed to create the filter function
2436                        // just as Sizzle does
2437                        if ( fn[ expando ] ) {
2438                            return fn( argument );
2439                        }
2440
2441                        // But maintain support for old signatures
2442                        if ( fn.length > 1 ) {
2443                            args = [ pseudo, pseudo, "", argument ];
2444                            return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
2445                                markFunction( function( seed, matches ) {
2446                                    var idx,
2447                                        matched = fn( seed, argument ),
2448                                        i = matched.length;
2449                                    while ( i-- ) {
2450                                        idx = indexOf( seed, matched[ i ] );
2451                                        seed[ idx ] = !( matches[ idx ] = matched[ i ] );
2452                                    }
2453                                } ) :
2454                                function( elem ) {
2455                                    return fn( elem, 0, args );
2456                                };
2457                        }
2458
2459                        return fn;
2460                    }
2461                },
2462
2463                pseudos: {
2464
2465                    // Potentially complex pseudos
2466                    "not": markFunction( function( selector ) {
2467
2468                        // Trim the selector passed to compile
2469                        // to avoid treating leading and trailing
2470                        // spaces as combinators
2471                        var input = [],
2472                            results = [],
2473                            matcher = compile( selector.replace( rtrim, "$1" ) );
2474
2475                        return matcher[ expando ] ?
2476                            markFunction( function( seed, matches, _context, xml ) {
2477                                var elem,
2478                                    unmatched = matcher( seed, null, xml, [] ),
2479                                    i = seed.length;
2480
2481                                // Match elements unmatched by `matcher`
2482                                while ( i-- ) {
2483                                    if ( ( elem = unmatched[ i ] ) ) {
2484                                        seed[ i ] = !( matches[ i ] = elem );
2485                                    }
2486                                }
2487                            } ) :
2488                            function( elem, _context, xml ) {
2489                                input[ 0 ] = elem;
2490                                matcher( input, null, xml, results );
2491
2492                                // Don't keep the element (issue #299)
2493                                input[ 0 ] = null;
2494                                return !results.pop();
2495                            };
2496                    } ),
2497
2498                    "has": markFunction( function( selector ) {
2499                        return function( elem ) {
2500                            return Sizzle( selector, elem ).length > 0;
2501                        };
2502                    } ),
2503
2504                    "contains": markFunction( function( text ) {
2505                        text = text.replace( runescape, funescape );
2506                        return function( elem ) {
2507                            return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1;
2508                        };
2509                    } ),
2510
2511                    // "Whether an element is represented by a :lang() selector
2512                    // is based solely on the element's language value
2513                    // being equal to the identifier C,
2514                    // or beginning with the identifier C immediately followed by "-".
2515                    // The matching of C against the element's language value is performed case-insensitively.
2516                    // The identifier C does not have to be a valid language name."
2517                    // http://www.w3.org/TR/selectors/#lang-pseudo
2518                    "lang": markFunction( function( lang ) {
2519
2520                        // lang value must be a valid identifier
2521                        if ( !ridentifier.test( lang || "" ) ) {
2522                            Sizzle.error( "unsupported lang: " + lang );
2523                        }
2524                        lang = lang.replace( runescape, funescape ).toLowerCase();
2525                        return function( elem ) {
2526                            var elemLang;
2527                            do {
2528                                if ( ( elemLang = documentIsHTML ?
2529                                    elem.lang :
2530                                    elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) {
2531
2532                                    elemLang = elemLang.toLowerCase();
2533                                    return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
2534                                }
2535                            } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 );
2536                            return false;
2537                        };
2538                    } ),
2539
2540                    // Miscellaneous
2541                    "target": function( elem ) {
2542                        var hash = window.location && window.location.hash;
2543                        return hash && hash.slice( 1 ) === elem.id;
2544                    },
2545
2546                    "root": function( elem ) {
2547                        return elem === docElem;
2548                    },
2549
2550                    "focus": function( elem ) {
2551                        return elem === document.activeElement &&
2552                            ( !document.hasFocus || document.hasFocus() ) &&
2553                            !!( elem.type || elem.href || ~elem.tabIndex );
2554                    },
2555
2556                    // Boolean properties
2557                    "enabled": createDisabledPseudo( false ),
2558                    "disabled": createDisabledPseudo( true ),
2559
2560                    "checked": function( elem ) {
2561
2562                        // In CSS3, :checked should return both checked and selected elements
2563                        // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
2564                        var nodeName = elem.nodeName.toLowerCase();
2565                        return ( nodeName === "input" && !!elem.checked ) ||
2566                            ( nodeName === "option" && !!elem.selected );
2567                    },
2568
2569                    "selected": function( elem ) {
2570
2571                        // Accessing this property makes selected-by-default
2572                        // options in Safari work properly
2573                        if ( elem.parentNode ) {
2574                            // eslint-disable-next-line no-unused-expressions
2575                            elem.parentNode.selectedIndex;
2576                        }
2577
2578                        return elem.selected === true;
2579                    },
2580
2581                    // Contents
2582                    "empty": function( elem ) {
2583
2584                        // http://www.w3.org/TR/selectors/#empty-pseudo
2585                        // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
2586                        //   but not by others (comment: 8; processing instruction: 7; etc.)
2587                        // nodeType < 6 works because attributes (2) do not appear as children
2588                        for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
2589                            if ( elem.nodeType < 6 ) {
2590                                return false;
2591                            }
2592                        }
2593                        return true;
2594                    },
2595
2596                    "parent": function( elem ) {
2597                        return !Expr.pseudos[ "empty" ]( elem );
2598                    },
2599
2600                    // Element/input types
2601                    "header": function( elem ) {
2602                        return rheader.test( elem.nodeName );
2603                    },
2604
2605                    "input": function( elem ) {
2606                        return rinputs.test( elem.nodeName );
2607                    },
2608
2609                    "button": function( elem ) {
2610                        var name = elem.nodeName.toLowerCase();
2611                        return name === "input" && elem.type === "button" || name === "button";
2612                    },
2613
2614                    "text": function( elem ) {
2615                        var attr;
2616                        return elem.nodeName.toLowerCase() === "input" &&
2617                            elem.type === "text" &&
2618
2619                            // Support: IE<8
2620                            // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
2621                            ( ( attr = elem.getAttribute( "type" ) ) == null ||
2622                                attr.toLowerCase() === "text" );
2623                    },
2624
2625                    // Position-in-collection
2626                    "first": createPositionalPseudo( function() {
2627                        return [ 0 ];
2628                    } ),
2629
2630                    "last": createPositionalPseudo( function( _matchIndexes, length ) {
2631                        return [ length - 1 ];
2632                    } ),
2633
2634                    "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) {
2635                        return [ argument < 0 ? argument + length : argument ];
2636                    } ),
2637
2638                    "even": createPositionalPseudo( function( matchIndexes, length ) {
2639                        var i = 0;
2640                        for ( ; i < length; i += 2 ) {
2641                            matchIndexes.push( i );
2642                        }
2643                        return matchIndexes;
2644                    } ),
2645
2646                    "odd": createPositionalPseudo( function( matchIndexes, length ) {
2647                        var i = 1;
2648                        for ( ; i < length; i += 2 ) {
2649                            matchIndexes.push( i );
2650                        }
2651                        return matchIndexes;
2652                    } ),
2653
2654                    "lt": createPositionalPseudo( function( matchIndexes, length, argument ) {
2655                        var i = argument < 0 ?
2656                            argument + length :
2657                            argument > length ?
2658                                length :
2659                                argument;
2660                        for ( ; --i >= 0; ) {
2661                            matchIndexes.push( i );
2662                        }
2663                        return matchIndexes;
2664                    } ),
2665
2666                    "gt": createPositionalPseudo( function( matchIndexes, length, argument ) {
2667                        var i = argument < 0 ? argument + length : argument;
2668                        for ( ; ++i < length; ) {
2669                            matchIndexes.push( i );
2670                        }
2671                        return matchIndexes;
2672                    } )
2673                }
2674            };
2675
2676            Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ];
2677
2678// Add button/input type pseudos
2679            for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
2680                Expr.pseudos[ i ] = createInputPseudo( i );
2681            }
2682            for ( i in { submit: true, reset: true } ) {
2683                Expr.pseudos[ i ] = createButtonPseudo( i );
2684            }
2685
2686// Easy API for creating new setFilters
2687            function setFilters() {}
2688            setFilters.prototype = Expr.filters = Expr.pseudos;
2689            Expr.setFilters = new setFilters();
2690
2691            tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
2692                var matched, match, tokens, type,
2693                    soFar, groups, preFilters,
2694                    cached = tokenCache[ selector + " " ];
2695
2696                if ( cached ) {
2697                    return parseOnly ? 0 : cached.slice( 0 );
2698                }
2699
2700                soFar = selector;
2701                groups = [];
2702                preFilters = Expr.preFilter;
2703
2704                while ( soFar ) {
2705
2706                    // Comma and first run
2707                    if ( !matched || ( match = rcomma.exec( soFar ) ) ) {
2708                        if ( match ) {
2709
2710                            // Don't consume trailing commas as valid
2711                            soFar = soFar.slice( match[ 0 ].length ) || soFar;
2712                        }
2713                        groups.push( ( tokens = [] ) );
2714                    }
2715
2716                    matched = false;
vendor: 5,359 bytes, lines 2717-2834
2717
2718                    // Combinators
2719                    if ( ( match = rcombinators.exec( soFar ) ) ) {
2720                        matched = match.shift();
2721                        tokens.push( {
2722                            value: matched,
2723
2724                            // Cast descendant combinators to space
2725                            type: match[ 0 ].replace( rtrim, " " )
2726                        } );
2727                        soFar = soFar.slice( matched.length );
2728                    }
2729
2730                    // Filters
2731                    for ( type in Expr.filter ) {
2732                        if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] ||
2733                            ( match = preFilters[ type ]( match ) ) ) ) {
2734                            matched = match.shift();
2735                            tokens.push( {
2736                                value: matched,
2737                                type: type,
2738                                matches: match
2739                            } );
2740                            soFar = soFar.slice( matched.length );
2741                        }
2742                    }
2743
2744                    if ( !matched ) {
2745                        break;
2746                    }
2747                }
2748
2749                // Return the length of the invalid excess
2750                // if we're just parsing
2751                // Otherwise, throw an error or return tokens
2752                return parseOnly ?
2753                    soFar.length :
2754                    soFar ?
2755                        Sizzle.error( selector ) :
2756
2757                        // Cache the tokens
2758                        tokenCache( selector, groups ).slice( 0 );
2759            };
2760
2761            function toSelector( tokens ) {
2762                var i = 0,
2763                    len = tokens.length,
2764                    selector = "";
2765                for ( ; i < len; i++ ) {
2766                    selector += tokens[ i ].value;
2767                }
2768                return selector;
2769            }
2770
2771            function addCombinator( matcher, combinator, base ) {
2772                var dir = combinator.dir,
2773                    skip = combinator.next,
2774                    key = skip || dir,
2775                    checkNonElements = base && key === "parentNode",
2776                    doneName = done++;
2777
2778                return combinator.first ?
2779
2780                    // Check against closest ancestor/preceding element
2781                    function( elem, context, xml ) {
2782                        while ( ( elem = elem[ dir ] ) ) {
2783                            if ( elem.nodeType === 1 || checkNonElements ) {
2784                                return matcher( elem, context, xml );
2785                            }
2786                        }
2787                        return false;
2788                    } :
2789
2790                    // Check against all ancestor/preceding elements
2791                    function( elem, context, xml ) {
2792                        var oldCache, uniqueCache, outerCache,
2793                            newCache = [ dirruns, doneName ];
2794
2795                        // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching
2796                        if ( xml ) {
2797                            while ( ( elem = elem[ dir ] ) ) {
2798                                if ( elem.nodeType === 1 || checkNonElements ) {
2799                                    if ( matcher( elem, context, xml ) ) {
2800                                        return true;
2801                                    }
2802                                }
2803                            }
2804                        } else {
2805                            while ( ( elem = elem[ dir ] ) ) {
2806                                if ( elem.nodeType === 1 || checkNonElements ) {
2807                                    outerCache = elem[ expando ] || ( elem[ expando ] = {} );
2808
2809                                    // Support: IE <9 only
2810                                    // Defend against cloned attroperties (jQuery gh-1709)
2811                                    uniqueCache = outerCache[ elem.uniqueID ] ||
2812                                        ( outerCache[ elem.uniqueID ] = {} );
2813
2814                                    if ( skip && skip === elem.nodeName.toLowerCase() ) {
2815                                        elem = elem[ dir ] || elem;
2816                                    } else if ( ( oldCache = uniqueCache[ key ] ) &&
2817                                        oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
2818
2819                                        // Assign to newCache so results back-propagate to previous elements
2820                                        return ( newCache[ 2 ] = oldCache[ 2 ] );
2821                                    } else {
2822
2823                                        // Reuse newcache so results back-propagate to previous elements
2824                                        uniqueCache[ key ] = newCache;
2825
2826                                        // A match means we're done; a fail means we have to keep checking
2827                                        if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) {
2828                                            return true;
2829                                        }
2830                                    }
2831                                }
2832                            }
2833                        }
2834                        return false;
vendor: 8,930 bytes, lines 2835-3031
2835                    };
2836            }
2837
2838            function elementMatcher( matchers ) {
2839                return matchers.length > 1 ?
2840                    function( elem, context, xml ) {
2841                        var i = matchers.length;
2842                        while ( i-- ) {
2843                            if ( !matchers[ i ]( elem, context, xml ) ) {
2844                                return false;
2845                            }
2846                        }
2847                        return true;
2848                    } :
2849                    matchers[ 0 ];
2850            }
2851
2852            function multipleContexts( selector, contexts, results ) {
2853                var i = 0,
2854                    len = contexts.length;
2855                for ( ; i < len; i++ ) {
2856                    Sizzle( selector, contexts[ i ], results );
2857                }
2858                return results;
2859            }
2860
2861            function condense( unmatched, map, filter, context, xml ) {
2862                var elem,
2863                    newUnmatched = [],
2864                    i = 0,
2865                    len = unmatched.length,
2866                    mapped = map != null;
2867
2868                for ( ; i < len; i++ ) {
2869                    if ( ( elem = unmatched[ i ] ) ) {
2870                        if ( !filter || filter( elem, context, xml ) ) {
2871                            newUnmatched.push( elem );
2872                            if ( mapped ) {
2873                                map.push( i );
2874                            }
2875                        }
2876                    }
2877                }
2878
2879                return newUnmatched;
2880            }
2881
2882            function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
2883                if ( postFilter && !postFilter[ expando ] ) {
2884                    postFilter = setMatcher( postFilter );
2885                }
2886                if ( postFinder && !postFinder[ expando ] ) {
2887                    postFinder = setMatcher( postFinder, postSelector );
2888                }
2889                return markFunction( function( seed, results, context, xml ) {
2890                    var temp, i, elem,
2891                        preMap = [],
2892                        postMap = [],
2893                        preexisting = results.length,
2894
2895                        // Get initial elements from seed or context
2896                        elems = seed || multipleContexts(
2897                            selector || "*",
2898                            context.nodeType ? [ context ] : context,
2899                            []
2900                        ),
2901
2902                        // Prefilter to get matcher input, preserving a map for seed-results synchronization
2903                        matcherIn = preFilter && ( seed || !selector ) ?
2904                            condense( elems, preMap, preFilter, context, xml ) :
2905                            elems,
2906
2907                        matcherOut = matcher ?
2908
2909                            // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
2910                            postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
2911
2912                                // ...intermediate processing is necessary
2913                                [] :
2914
2915                                // ...otherwise use results directly
2916                                results :
2917                            matcherIn;
2918
2919                    // Find primary matches
2920                    if ( matcher ) {
2921                        matcher( matcherIn, matcherOut, context, xml );
2922                    }
2923
2924                    // Apply postFilter
2925                    if ( postFilter ) {
2926                        temp = condense( matcherOut, postMap );
2927                        postFilter( temp, [], context, xml );
2928
2929                        // Un-match failing elements by moving them back to matcherIn
2930                        i = temp.length;
2931                        while ( i-- ) {
2932                            if ( ( elem = temp[ i ] ) ) {
2933                                matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem );
2934                            }
2935                        }
2936                    }
2937
2938                    if ( seed ) {
2939                        if ( postFinder || preFilter ) {
2940                            if ( postFinder ) {
2941
2942                                // Get the final matcherOut by condensing this intermediate into postFinder contexts
2943                                temp = [];
2944                                i = matcherOut.length;
2945                                while ( i-- ) {
2946                                    if ( ( elem = matcherOut[ i ] ) ) {
2947
2948                                        // Restore matcherIn since elem is not yet a final match
2949                                        temp.push( ( matcherIn[ i ] = elem ) );
2950                                    }
2951                                }
2952                                postFinder( null, ( matcherOut = [] ), temp, xml );
2953                            }
2954
2955                            // Move matched elements from seed to results to keep them synchronized
2956                            i = matcherOut.length;
2957                            while ( i-- ) {
2958                                if ( ( elem = matcherOut[ i ] ) &&
2959                                    ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) {
2960
2961                                    seed[ temp ] = !( results[ temp ] = elem );
2962                                }
2963                            }
2964                        }
2965
2966                        // Add elements to results, through postFinder if defined
2967                    } else {
2968                        matcherOut = condense(
2969                            matcherOut === results ?
2970                                matcherOut.splice( preexisting, matcherOut.length ) :
2971                                matcherOut
2972                        );
2973                        if ( postFinder ) {
2974                            postFinder( null, results, matcherOut, xml );
2975                        } else {
2976                            push.apply( results, matcherOut );
2977                        }
2978                    }
2979                } );
2980            }
2981
2982            function matcherFromTokens( tokens ) {
2983                var checkContext, matcher, j,
2984                    len = tokens.length,
2985                    leadingRelative = Expr.relative[ tokens[ 0 ].type ],
2986                    implicitRelative = leadingRelative || Expr.relative[ " " ],
2987                    i = leadingRelative ? 1 : 0,
2988
2989                    // The foundational matcher ensures that elements are reachable from top-level context(s)
2990                    matchContext = addCombinator( function( elem ) {
2991                        return elem === checkContext;
2992                    }, implicitRelative, true ),
2993                    matchAnyContext = addCombinator( function( elem ) {
2994                        return indexOf( checkContext, elem ) > -1;
2995                    }, implicitRelative, true ),
2996                    matchers = [ function( elem, context, xml ) {
2997                        var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
2998                            ( checkContext = context ).nodeType ?
2999                                matchContext( elem, context, xml ) :
3000                                matchAnyContext( elem, context, xml ) );
3001
3002                        // Avoid hanging onto element (issue #299)
3003                        checkContext = null;
3004                        return ret;
3005                    } ];
3006
3007                for ( ; i < len; i++ ) {
3008                    if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) {
3009                        matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
3010                    } else {
3011                        matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches );
3012
3013                        // Return special upon seeing a positional matcher
3014                        if ( matcher[ expando ] ) {
3015
3016                            // Find the next relative operator (if any) for proper handling
3017                            j = ++i;
3018                            for ( ; j < len; j++ ) {
3019                                if ( Expr.relative[ tokens[ j ].type ] ) {
3020                                    break;
3021                                }
3022                            }
3023                            return setMatcher(
3024                                i > 1 && elementMatcher( matchers ),
3025                                i > 1 && toSelector(
3026
3027                                // If the preceding token was a descendant combinator, insert an implicit any-element `*`
3028                                tokens
3029                                    .slice( 0, i - 1 )
3030                                    .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } )
3031                                ).replace( rtrim, "$1" ),
vendor: 17,588 bytes, lines 3032-3460
3032                                matcher,
3033                                i < j && matcherFromTokens( tokens.slice( i, j ) ),
3034                                j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ),
3035                                j < len && toSelector( tokens )
3036                            );
3037                        }
3038                        matchers.push( matcher );
3039                    }
3040                }
3041
3042                return elementMatcher( matchers );
3043            }
3044
3045            function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
3046                var bySet = setMatchers.length > 0,
3047                    byElement = elementMatchers.length > 0,
3048                    superMatcher = function( seed, context, xml, results, outermost ) {
3049                        var elem, j, matcher,
3050                            matchedCount = 0,
3051                            i = "0",
3052                            unmatched = seed && [],
3053                            setMatched = [],
3054                            contextBackup = outermostContext,
3055
3056                            // We must always have either seed elements or outermost context
3057                            elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ),
3058
3059                            // Use integer dirruns iff this is the outermost matcher
3060                            dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ),
3061                            len = elems.length;
3062
3063                        if ( outermost ) {
3064
3065                            // Support: IE 11+, Edge 17 - 18+
3066                            // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
3067                            // two documents; shallow comparisons work.
3068                            // eslint-disable-next-line eqeqeq
3069                            outermostContext = context == document || context || outermost;
3070                        }
3071
3072                        // Add elements passing elementMatchers directly to results
3073                        // Support: IE<9, Safari
3074                        // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
3075                        for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) {
3076                            if ( byElement && elem ) {
3077                                j = 0;
3078
3079                                // Support: IE 11+, Edge 17 - 18+
3080                                // IE/Edge sometimes throw a "Permission denied" error when strict-comparing
3081                                // two documents; shallow comparisons work.
3082                                // eslint-disable-next-line eqeqeq
3083                                if ( !context && elem.ownerDocument != document ) {
3084                                    setDocument( elem );
3085                                    xml = !documentIsHTML;
3086                                }
3087                                while ( ( matcher = elementMatchers[ j++ ] ) ) {
3088                                    if ( matcher( elem, context || document, xml ) ) {
3089                                        results.push( elem );
3090                                        break;
3091                                    }
3092                                }
3093                                if ( outermost ) {
3094                                    dirruns = dirrunsUnique;
3095                                }
3096                            }
3097
3098                            // Track unmatched elements for set filters
3099                            if ( bySet ) {
3100
3101                                // They will have gone through all possible matchers
3102                                if ( ( elem = !matcher && elem ) ) {
3103                                    matchedCount--;
3104                                }
3105
3106                                // Lengthen the array for every element, matched or not
3107                                if ( seed ) {
3108                                    unmatched.push( elem );
3109                                }
3110                            }
3111                        }
3112
3113                        // `i` is now the count of elements visited above, and adding it to `matchedCount`
3114                        // makes the latter nonnegative.
3115                        matchedCount += i;
3116
3117                        // Apply set filters to unmatched elements
3118                        // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount`
3119                        // equals `i`), unless we didn't visit _any_ elements in the above loop because we have
3120                        // no element matchers and no seed.
3121                        // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that
3122                        // case, which will result in a "00" `matchedCount` that differs from `i` but is also
3123                        // numerically zero.
3124                        if ( bySet && i !== matchedCount ) {
3125                            j = 0;
3126                            while ( ( matcher = setMatchers[ j++ ] ) ) {
3127                                matcher( unmatched, setMatched, context, xml );
3128                            }
3129
3130                            if ( seed ) {
3131
3132                                // Reintegrate element matches to eliminate the need for sorting
3133                                if ( matchedCount > 0 ) {
3134                                    while ( i-- ) {
3135                                        if ( !( unmatched[ i ] || setMatched[ i ] ) ) {
3136                                            setMatched[ i ] = pop.call( results );
3137                                        }
3138                                    }
3139                                }
3140
3141                                // Discard index placeholder values to get only actual matches
3142                                setMatched = condense( setMatched );
3143                            }
3144
3145                            // Add matches to results
3146                            push.apply( results, setMatched );
3147
3148                            // Seedless set matches succeeding multiple successful matchers stipulate sorting
3149                            if ( outermost && !seed && setMatched.length > 0 &&
3150                                ( matchedCount + setMatchers.length ) > 1 ) {
3151
3152                                Sizzle.uniqueSort( results );
3153                            }
3154                        }
3155
3156                        // Override manipulation of globals by nested matchers
3157                        if ( outermost ) {
3158                            dirruns = dirrunsUnique;
3159                            outermostContext = contextBackup;
3160                        }
3161
3162                        return unmatched;
3163                    };
3164
3165                return bySet ?
3166                    markFunction( superMatcher ) :
3167                    superMatcher;
3168            }
3169
3170            compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
3171                var i,
3172                    setMatchers = [],
3173                    elementMatchers = [],
3174                    cached = compilerCache[ selector + " " ];
3175
3176                if ( !cached ) {
3177
3178                    // Generate a function of recursive functions that can be used to check each element
3179                    if ( !match ) {
3180                        match = tokenize( selector );
3181                    }
3182                    i = match.length;
3183                    while ( i-- ) {
3184                        cached = matcherFromTokens( match[ i ] );
3185                        if ( cached[ expando ] ) {
3186                            setMatchers.push( cached );
3187                        } else {
3188                            elementMatchers.push( cached );
3189                        }
3190                    }
3191
3192                    // Cache the compiled function
3193                    cached = compilerCache(
3194                        selector,
3195                        matcherFromGroupMatchers( elementMatchers, setMatchers )
3196                    );
3197
3198                    // Save selector and tokenization
3199                    cached.selector = selector;
3200                }
3201                return cached;
3202            };
3203
3204            /**
3205             * A low-level selection function that works with Sizzle's compiled
3206             *  selector functions
3207             * @param {String|Function} selector A selector or a pre-compiled
3208             *  selector function built with Sizzle.compile
3209             * @param {Element} context
3210             * @param {Array} [results]
3211             * @param {Array} [seed] A set of elements to match against
3212             */
3213            select = Sizzle.select = function( selector, context, results, seed ) {
3214                var i, tokens, token, type, find,
3215                    compiled = typeof selector === "function" && selector,
3216                    match = !seed && tokenize( ( selector = compiled.selector || selector ) );
3217
3218                results = results || [];
3219
3220                // Try to minimize operations if there is only one selector in the list and no seed
3221                // (the latter of which guarantees us context)
3222                if ( match.length === 1 ) {
3223
3224                    // Reduce context if the leading compound selector is an ID
3225                    tokens = match[ 0 ] = match[ 0 ].slice( 0 );
3226                    if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" &&
3227                        context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) {
3228
3229                        context = ( Expr.find[ "ID" ]( token.matches[ 0 ]
3230                            .replace( runescape, funescape ), context ) || [] )[ 0 ];
3231                        if ( !context ) {
3232                            return results;
3233
3234                            // Precompiled matchers will still verify ancestry, so step up a level
3235                        } else if ( compiled ) {
3236                            context = context.parentNode;
3237                        }
3238
3239                        selector = selector.slice( tokens.shift().value.length );
3240                    }
3241
3242                    // Fetch a seed set for right-to-left matching
3243                    i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length;
3244                    while ( i-- ) {
3245                        token = tokens[ i ];
3246
3247                        // Abort if we hit a combinator
3248                        if ( Expr.relative[ ( type = token.type ) ] ) {
3249                            break;
3250                        }
3251                        if ( ( find = Expr.find[ type ] ) ) {
3252
3253                            // Search, expanding context for leading sibling combinators
3254                            if ( ( seed = find(
3255                                token.matches[ 0 ].replace( runescape, funescape ),
3256                                rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) ||
3257                                context
3258                            ) ) ) {
3259
3260                                // If seed is empty or no tokens remain, we can return early
3261                                tokens.splice( i, 1 );
3262                                selector = seed.length && toSelector( tokens );
3263                                if ( !selector ) {
3264                                    push.apply( results, seed );
3265                                    return results;
3266                                }
3267
3268                                break;
3269                            }
3270                        }
3271                    }
3272                }
3273
3274                // Compile and execute a filtering function if one is not provided
3275                // Provide `match` to avoid retokenization if we modified the selector above
3276                ( compiled || compile( selector, match ) )(
3277                    seed,
3278                    context,
3279                    !documentIsHTML,
3280                    results,
3281                    !context || rsibling.test( selector ) && testContext( context.parentNode ) || context
3282                );
3283                return results;
3284            };
3285
3286// One-time assignments
3287
3288// Sort stability
3289            support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando;
3290
3291// Support: Chrome 14-35+
3292// Always assume duplicates if they aren't passed to the comparison function
3293            support.detectDuplicates = !!hasDuplicate;
3294
3295// Initialize against the default document
3296            setDocument();
3297
3298// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
3299// Detached nodes confoundingly follow *each other*
3300            support.sortDetached = assert( function( el ) {
3301
3302                // Should return 1, but returns 4 (following)
3303                return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1;
3304            } );
3305
3306// Support: IE<8
3307// Prevent attribute/property "interpolation"
3308// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
3309            if ( !assert( function( el ) {
3310                el.innerHTML = "<a href='#'></a>";
3311                return el.firstChild.getAttribute( "href" ) === "#";
3312            } ) ) {
3313                addHandle( "type|href|height|width", function( elem, name, isXML ) {
3314                    if ( !isXML ) {
3315                        return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
3316                    }
3317                } );
3318            }
3319
3320// Support: IE<9
3321// Use defaultValue in place of getAttribute("value")
3322            if ( !support.attributes || !assert( function( el ) {
3323                el.innerHTML = "<input/>";
3324                el.firstChild.setAttribute( "value", "" );
3325                return el.firstChild.getAttribute( "value" ) === "";
3326            } ) ) {
3327                addHandle( "value", function( elem, _name, isXML ) {
3328                    if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
3329                        return elem.defaultValue;
3330                    }
3331                } );
3332            }
3333
3334// Support: IE<9
3335// Use getAttributeNode to fetch booleans when getAttribute lies
3336            if ( !assert( function( el ) {
3337                return el.getAttribute( "disabled" ) == null;
3338            } ) ) {
3339                addHandle( booleans, function( elem, name, isXML ) {
3340                    var val;
3341                    if ( !isXML ) {
3342                        return elem[ name ] === true ? name.toLowerCase() :
3343                            ( val = elem.getAttributeNode( name ) ) && val.specified ?
3344                                val.value :
3345                                null;
3346                    }
3347                } );
3348            }
3349
3350            return Sizzle;
3351
3352        } )( window );
3353
3354
3355
3356    jQuery.find = Sizzle;
3357    jQuery.expr = Sizzle.selectors;
3358
3359// Deprecated
3360    jQuery.expr[ ":" ] = jQuery.expr.pseudos;
3361    jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
3362    jQuery.text = Sizzle.getText;
3363    jQuery.isXMLDoc = Sizzle.isXML;
3364    jQuery.contains = Sizzle.contains;
3365    jQuery.escapeSelector = Sizzle.escape;
3366
3367
3368
3369
3370    var dir = function( elem, dir, until ) {
3371        var matched = [],
3372            truncate = until !== undefined;
3373
3374        while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) {
3375            if ( elem.nodeType === 1 ) {
3376                if ( truncate && jQuery( elem ).is( until ) ) {
3377                    break;
3378                }
3379                matched.push( elem );
3380            }
3381        }
3382        return matched;
3383    };
3384
3385
3386    var siblings = function( n, elem ) {
3387        var matched = [];
3388
3389        for ( ; n; n = n.nextSibling ) {
3390            if ( n.nodeType === 1 && n !== elem ) {
3391                matched.push( n );
3392            }
3393        }
3394
3395        return matched;
3396    };
3397
3398
3399    var rneedsContext = jQuery.expr.match.needsContext;
3400
3401
3402
3403    function nodeName( elem, name ) {
3404
3405        return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
3406
3407    }
3408    var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i );
3409
3410
3411
3412// Implement the identical functionality for filter and not
3413    function winnow( elements, qualifier, not ) {
3414        if ( isFunction( qualifier ) ) {
3415            return jQuery.grep( elements, function( elem, i ) {
3416                return !!qualifier.call( elem, i, elem ) !== not;
3417            } );
3418        }
3419
3420        // Single element
3421        if ( qualifier.nodeType ) {
3422            return jQuery.grep( elements, function( elem ) {
3423                return ( elem === qualifier ) !== not;
3424            } );
3425        }
3426
3427        // Arraylike of elements (jQuery, arguments, Array)
3428        if ( typeof qualifier !== "string" ) {
3429            return jQuery.grep( elements, function( elem ) {
3430                return ( indexOf.call( qualifier, elem ) > -1 ) !== not;
3431            } );
3432        }
3433
3434        // Filtered directly for both simple and complex selectors
3435        return jQuery.filter( qualifier, elements, not );
3436    }
3437
3438    jQuery.filter = function( expr, elems, not ) {
3439        var elem = elems[ 0 ];
3440
3441        if ( not ) {
3442            expr = ":not(" + expr + ")";
3443        }
3444
3445        if ( elems.length === 1 && elem.nodeType === 1 ) {
3446            return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [];
3447        }
3448
3449        return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
3450            return elem.nodeType === 1;
3451        } ) );
3452    };
3453
3454    jQuery.fn.extend( {
3455        find: function( selector ) {
3456            var i, ret,
3457                len = this.length,
3458                self = this;
3459
3460            if ( typeof selector !== "string" ) {
vendor: 6,677 bytes, lines 3461-3647
3461                return this.pushStack( jQuery( selector ).filter( function() {
3462                    for ( i = 0; i < len; i++ ) {
3463                        if ( jQuery.contains( self[ i ], this ) ) {
3464                            return true;
3465                        }
3466                    }
3467                } ) );
3468            }
3469
3470            ret = this.pushStack( [] );
3471
3472            for ( i = 0; i < len; i++ ) {
3473                jQuery.find( selector, self[ i ], ret );
3474            }
3475
3476            return len > 1 ? jQuery.uniqueSort( ret ) : ret;
3477        },
3478        filter: function( selector ) {
3479            return this.pushStack( winnow( this, selector || [], false ) );
3480        },
3481        not: function( selector ) {
3482            return this.pushStack( winnow( this, selector || [], true ) );
3483        },
3484        is: function( selector ) {
3485            return !!winnow(
3486                this,
3487
3488                // If this is a positional/relative selector, check membership in the returned set
3489                // so $("p:first").is("p:last") won't return true for a doc with two "p".
3490                typeof selector === "string" && rneedsContext.test( selector ) ?
3491                    jQuery( selector ) :
3492                    selector || [],
3493                false
3494            ).length;
3495        }
3496    } );
3497
3498
3499// Initialize a jQuery object
3500
3501
3502// A central reference to the root jQuery(document)
3503    var rootjQuery,
3504
3505        // A simple way to check for HTML strings
3506        // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
3507        // Strict HTML recognition (#11290: must start with <)
3508        // Shortcut simple #id case for speed
3509        rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,
3510
3511        init = jQuery.fn.init = function( selector, context, root ) {
3512            var match, elem;
3513
3514            // HANDLE: $(""), $(null), $(undefined), $(false)
3515            if ( !selector ) {
3516                return this;
3517            }
3518
3519            // Method init() accepts an alternate rootjQuery
3520            // so migrate can support jQuery.sub (gh-2101)
3521            root = root || rootjQuery;
3522
3523            // Handle HTML strings
3524            if ( typeof selector === "string" ) {
3525                if ( selector[ 0 ] === "<" &&
3526                    selector[ selector.length - 1 ] === ">" &&
3527                    selector.length >= 3 ) {
3528
3529                    // Assume that strings that start and end with <> are HTML and skip the regex check
3530                    match = [ null, selector, null ];
3531
3532                } else {
3533                    match = rquickExpr.exec( selector );
3534                }
3535
3536                // Match html or make sure no context is specified for #id
3537                if ( match && ( match[ 1 ] || !context ) ) {
3538
3539                    // HANDLE: $(html) -> $(array)
3540                    if ( match[ 1 ] ) {
3541                        context = context instanceof jQuery ? context[ 0 ] : context;
3542
3543                        // Option to run scripts is true for back-compat
3544                        // Intentionally let the error be thrown if parseHTML is not present
3545                        jQuery.merge( this, jQuery.parseHTML(
3546                            match[ 1 ],
3547                            context && context.nodeType ? context.ownerDocument || context : document,
3548                            true
3549                        ) );
3550
3551                        // HANDLE: $(html, props)
3552                        if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) {
3553                            for ( match in context ) {
3554
3555                                // Properties of context are called as methods if possible
3556                                if ( isFunction( this[ match ] ) ) {
3557                                    this[ match ]( context[ match ] );
3558
3559                                    // ...and otherwise set as attributes
3560                                } else {
3561                                    this.attr( match, context[ match ] );
3562                                }
3563                            }
3564                        }
3565
3566                        return this;
3567
3568                        // HANDLE: $(#id)
3569                    } else {
3570                        elem = document.getElementById( match[ 2 ] );
3571
3572                        if ( elem ) {
3573
3574                            // Inject the element directly into the jQuery object
3575                            this[ 0 ] = elem;
3576                            this.length = 1;
3577                        }
3578                        return this;
3579                    }
3580
3581                    // HANDLE: $(expr, $(...))
3582                } else if ( !context || context.jquery ) {
3583                    return ( context || root ).find( selector );
3584
3585                    // HANDLE: $(expr, context)
3586                    // (which is just equivalent to: $(context).find(expr)
3587                } else {
3588                    return this.constructor( context ).find( selector );
3589                }
3590
3591                // HANDLE: $(DOMElement)
3592            } else if ( selector.nodeType ) {
3593                this[ 0 ] = selector;
3594                this.length = 1;
3595                return this;
3596
3597                // HANDLE: $(function)
3598                // Shortcut for document ready
3599            } else if ( isFunction( selector ) ) {
3600                return root.ready !== undefined ?
3601                    root.ready( selector ) :
3602
3603                    // Execute immediately if ready is not present
3604                    selector( jQuery );
3605            }
3606
3607            return jQuery.makeArray( selector, this );
3608        };
3609
3610// Give the init function the jQuery prototype for later instantiation
3611    init.prototype = jQuery.fn;
3612
3613// Initialize central reference
3614    rootjQuery = jQuery( document );
3615
3616
3617    var rparentsprev = /^(?:parents|prev(?:Until|All))/,
3618
3619        // Methods guaranteed to produce a unique set when starting from a unique set
3620        guaranteedUnique = {
3621            children: true,
3622            contents: true,
3623            next: true,
3624            prev: true
3625        };
3626
3627    jQuery.fn.extend( {
3628        has: function( target ) {
3629            var targets = jQuery( target, this ),
3630                l = targets.length;
3631
3632            return this.filter( function() {
3633                var i = 0;
3634                for ( ; i < l; i++ ) {
3635                    if ( jQuery.contains( this, targets[ i ] ) ) {
3636                        return true;
3637                    }
3638                }
3639            } );
3640        },
3641
3642        closest: function( selectors, context ) {
3643            var cur,
3644                i = 0,
3645                l = this.length,
3646                matched = [],
3647                targets = typeof selectors !== "string" && jQuery( 
vendor: 4,293 bytes, lines 3647-3771
3647selectors );
3648
3649            // Positional selectors never match, since there's no _selection_ context
3650            if ( !rneedsContext.test( selectors ) ) {
3651                for ( ; i < l; i++ ) {
3652                    for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) {
3653
3654                        // Always skip document fragments
3655                        if ( cur.nodeType < 11 && ( targets ?
3656                            targets.index( cur ) > -1 :
3657
3658                            // Don't pass non-elements to Sizzle
3659                            cur.nodeType === 1 &&
3660                            jQuery.find.matchesSelector( cur, selectors ) ) ) {
3661
3662                            matched.push( cur );
3663                            break;
3664                        }
3665                    }
3666                }
3667            }
3668
3669            return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
3670        },
3671
3672        // Determine the position of an element within the set
3673        index: function( elem ) {
3674
3675            // No argument, return index in parent
3676            if ( !elem ) {
3677                return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
3678            }
3679
3680            // Index in selector
3681            if ( typeof elem === "string" ) {
3682                return indexOf.call( jQuery( elem ), this[ 0 ] );
3683            }
3684
3685            // Locate the position of the desired element
3686            return indexOf.call( this,
3687
3688                // If it receives a jQuery object, the first element is used
3689                elem.jquery ? elem[ 0 ] : elem
3690            );
3691        },
3692
3693        add: function( selector, context ) {
3694            return this.pushStack(
3695                jQuery.uniqueSort(
3696                    jQuery.merge( this.get(), jQuery( selector, context ) )
3697                )
3698            );
3699        },
3700
3701        addBack: function( selector ) {
3702            return this.add( selector == null ?
3703                this.prevObject : this.prevObject.filter( selector )
3704            );
3705        }
3706    } );
3707
3708    function sibling( cur, dir ) {
3709        while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {}
3710        return cur;
3711    }
3712
3713    jQuery.each( {
3714        parent: function( elem ) {
3715            var parent = elem.parentNode;
3716            return parent && parent.nodeType !== 11 ? parent : null;
3717        },
3718        parents: function( elem ) {
3719            return dir( elem, "parentNode" );
3720        },
3721        parentsUntil: function( elem, _i, until ) {
3722            return dir( elem, "parentNode", until );
3723        },
3724        next: function( elem ) {
3725            return sibling( elem, "nextSibling" );
3726        },
3727        prev: function( elem ) {
3728            return sibling( elem, "previousSibling" );
3729        },
3730        nextAll: function( elem ) {
3731            return dir( elem, "nextSibling" );
3732        },
3733        prevAll: function( elem ) {
3734            return dir( elem, "previousSibling" );
3735        },
3736        nextUntil: function( elem, _i, until ) {
3737            return dir( elem, "nextSibling", until );
3738        },
3739        prevUntil: function( elem, _i, until ) {
3740            return dir( elem, "previousSibling", until );
3741        },
3742        siblings: function( elem ) {
3743            return siblings( ( elem.parentNode || {} ).firstChild, elem );
3744        },
3745        children: function( elem ) {
3746            return siblings( elem.firstChild );
3747        },
3748        contents: function( elem ) {
3749            if ( elem.contentDocument != null &&
3750
3751                // Support: IE 11+
3752                // <object> elements with no `data` attribute has an object
3753                // `contentDocument` with a `null` prototype.
3754                getProto( elem.contentDocument ) ) {
3755
3756                return elem.contentDocument;
3757            }
3758
3759            // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only
3760            // Treat the template element as a regular one in browsers that
3761            // don't support it.
3762            if ( nodeName( elem, "template" ) ) {
3763                elem = elem.content || elem;
3764            }
3765
3766            return jQuery.merge( [], elem.childNodes );
3767        }
3768    }, function( name, fn ) {
3769        jQuery.fn[ name ] = function( until, selector ) {
3770            var matched = jQuery.map( this, fn, until );
3771
vendor: 35,404 bytes, lines 3772-4703
3772            if ( name.slice( -5 ) !== "Until" ) {
3773                selector = until;
3774            }
3775
3776            if ( selector && typeof selector === "string" ) {
3777                matched = jQuery.filter( selector, matched );
3778            }
3779
3780            if ( this.length > 1 ) {
3781
3782                // Remove duplicates
3783                if ( !guaranteedUnique[ name ] ) {
3784                    jQuery.uniqueSort( matched );
3785                }
3786
3787                // Reverse order for parents* and prev-derivatives
3788                if ( rparentsprev.test( name ) ) {
3789                    matched.reverse();
3790                }
3791            }
3792
3793            return this.pushStack( matched );
3794        };
3795    } );
3796    var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g );
3797
3798
3799
3800// Convert String-formatted options into Object-formatted ones
3801    function createOptions( options ) {
3802        var object = {};
3803        jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) {
3804            object[ flag ] = true;
3805        } );
3806        return object;
3807    }
3808
3809    /*
3810 * Create a callback list using the following parameters:
3811 *
3812 *	options: an optional list of space-separated options that will change how
3813 *			the callback list behaves or a more traditional option object
3814 *
3815 * By default a callback list will act like an event callback list and can be
3816 * "fired" multiple times.
3817 *
3818 * Possible options:
3819 *
3820 *	once:			will ensure the callback list can only be fired once (like a Deferred)
3821 *
3822 *	memory:			will keep track of previous values and will call any callback added
3823 *					after the list has been fired right away with the latest "memorized"
3824 *					values (like a Deferred)
3825 *
3826 *	unique:			will ensure a callback can only be added once (no duplicate in the list)
3827 *
3828 *	stopOnFalse:	interrupt callings when a callback returns false
3829 *
3830 */
3831    jQuery.Callbacks = function( options ) {
3832
3833        // Convert options from String-formatted to Object-formatted if needed
3834        // (we check in cache first)
3835        options = typeof options === "string" ?
3836            createOptions( options ) :
3837            jQuery.extend( {}, options );
3838
3839        var // Flag to know if list is currently firing
3840            firing,
3841
3842            // Last fire value for non-forgettable lists
3843            memory,
3844
3845            // Flag to know if list was already fired
3846            fired,
3847
3848            // Flag to prevent firing
3849            locked,
3850
3851            // Actual callback list
3852            list = [],
3853
3854            // Queue of execution data for repeatable lists
3855            queue = [],
3856
3857            // Index of currently firing callback (modified by add/remove as needed)
3858            firingIndex = -1,
3859
3860            // Fire callbacks
3861            fire = function() {
3862
3863                // Enforce single-firing
3864                locked = locked || options.once;
3865
3866                // Execute callbacks for all pending executions,
3867                // respecting firingIndex overrides and runtime changes
3868                fired = firing = true;
3869                for ( ; queue.length; firingIndex = -1 ) {
3870                    memory = queue.shift();
3871                    while ( ++firingIndex < list.length ) {
3872
3873                        // Run callback and check for early termination
3874                        if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false &&
3875                            options.stopOnFalse ) {
3876
3877                            // Jump to end and forget the data so .add doesn't re-fire
3878                            firingIndex = list.length;
3879                            memory = false;
3880                        }
3881                    }
3882                }
3883
3884                // Forget the data if we're done with it
3885                if ( !options.memory ) {
3886                    memory = false;
3887                }
3888
3889                firing = false;
3890
3891                // Clean up if we're done firing for good
3892                if ( locked ) {
3893
3894                    // Keep an empty list if we have data for future add calls
3895                    if ( memory ) {
3896                        list = [];
3897
3898                        // Otherwise, this object is spent
3899                    } else {
3900                        list = "";
3901                    }
3902                }
3903            },
3904
3905            // Actual Callbacks object
3906            self = {
3907
3908                // Add a callback or a collection of callbacks to the list
3909                add: function() {
3910                    if ( list ) {
3911
3912                        // If we have memory from a past run, we should fire after adding
3913                        if ( memory && !firing ) {
3914                            firingIndex = list.length - 1;
3915                            queue.push( memory );
3916                        }
3917
3918                        ( function add( args ) {
3919                            jQuery.each( args, function( _, arg ) {
3920                                if ( isFunction( arg ) ) {
3921                                    if ( !options.unique || !self.has( arg ) ) {
3922                                        list.push( arg );
3923                                    }
3924                                } else if ( arg && arg.length && toType( arg ) !== "string" ) {
3925
3926                                    // Inspect recursively
3927                                    add( arg );
3928                                }
3929                            } );
3930                        } )( arguments );
3931
3932                        if ( memory && !firing ) {
3933                            fire();
3934                        }
3935                    }
3936                    return this;
3937                },
3938
3939                // Remove a callback from the list
3940                remove: function() {
3941                    jQuery.each( arguments, function( _, arg ) {
3942                        var index;
3943                        while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
3944                            list.splice( index, 1 );
3945
3946                            // Handle firing indexes
3947                            if ( index <= firingIndex ) {
3948                                firingIndex--;
3949                            }
3950                        }
3951                    } );
3952                    return this;
3953                },
3954
3955                // Check if a given callback is in the list.
3956                // If no argument is given, return whether or not list has callbacks attached.
3957                has: function( fn ) {
3958                    return fn ?
3959                        jQuery.inArray( fn, list ) > -1 :
3960                        list.length > 0;
3961                },
3962
3963                // Remove all callbacks from the list
3964                empty: function() {
3965                    if ( list ) {
3966                        list = [];
3967                    }
3968                    return this;
3969                },
3970
3971                // Disable .fire and .add
3972                // Abort any current/pending executions
3973                // Clear all callbacks and values
3974                disable: function() {
3975                    locked = queue = [];
3976                    list = memory = "";
3977                    return this;
3978                },
3979                disabled: function() {
3980                    return !list;
3981                },
3982
3983                // Disable .fire
3984                // Also disable .add unless we have memory (since it would have no effect)
3985                // Abort any pending executions
3986                lock: function() {
3987                    locked = queue = [];
3988                    if ( !memory && !firing ) {
3989                        list = memory = "";
3990                    }
3991                    return this;
3992                },
3993                locked: function() {
3994                    return !!locked;
3995                },
3996
3997                // Call all callbacks with the given context and arguments
3998                fireWith: function( context, args ) {
3999                    if ( !locked ) {
4000                        args = args || [];
4001                        args = [ context, args.slice ? args.slice() : args ];
4002                        queue.push( args );
4003                        if ( !firing ) {
4004                            fire();
4005                        }
4006                    }
4007                    return this;
4008                },
4009
4010                // Call all the callbacks with the given arguments
4011                fire: function() {
4012                    self.fireWith( this, arguments );
4013                    return this;
4014                },
4015
4016                // To know if the callbacks have already been called at least once
4017                fired: function() {
4018                    return !!fired;
4019                }
4020            };
4021
4022        return self;
4023    };
4024
4025
4026    function Identity( v ) {
4027        return v;
4028    }
4029    function Thrower( ex ) {
4030        throw ex;
4031    }
4032
4033    function adoptValue( value, resolve, reject, noValue ) {
4034        var method;
4035
4036        try {
4037
4038            // Check for promise aspect first to privilege synchronous behavior
4039            if ( value && isFunction( ( method = value.promise ) ) ) {
4040                method.call( value ).done( resolve ).fail( reject );
4041
4042                // Other thenables
4043            } else if ( value && isFunction( ( method = value.then ) ) ) {
4044                method.call( value, resolve, reject );
4045
4046                // Other non-thenables
4047            } else {
4048
4049                // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer:
4050                // * false: [ value ].slice( 0 ) => resolve( value )
4051                // * true: [ value ].slice( 1 ) => resolve()
4052                resolve.apply( undefined, [ value ].slice( noValue ) );
4053            }
4054
4055            // For Promises/A+, convert exceptions into rejections
4056            // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in
4057            // Deferred#then to conditionally suppress rejection.
4058        } catch ( value ) {
4059
4060            // Support: Android 4.0 only
4061            // Strict mode functions invoked without .call/.apply get global-object context
4062            reject.apply( undefined, [ value ] );
4063        }
4064    }
4065
4066    jQuery.extend( {
4067
4068        Deferred: function( func ) {
4069            var tuples = [
4070
4071                    // action, add listener, callbacks,
4072                    // ... .then handlers, argument index, [final state]
4073                    [ "notify", "progress", jQuery.Callbacks( "memory" ),
4074                        jQuery.Callbacks( "memory" ), 2 ],
4075                    [ "resolve", "done", jQuery.Callbacks( "once memory" ),
4076                        jQuery.Callbacks( "once memory" ), 0, "resolved" ],
4077                    [ "reject", "fail", jQuery.Callbacks( "once memory" ),
4078                        jQuery.Callbacks( "once memory" ), 1, "rejected" ]
4079                ],
4080                state = "pending",
4081                promise = {
4082                    state: function() {
4083                        return state;
4084                    },
4085                    always: function() {
4086                        deferred.done( arguments ).fail( arguments );
4087                        return this;
4088                    },
4089                    "catch": function( fn ) {
4090                        return promise.then( null, fn );
4091                    },
4092
4093                    // Keep pipe for back-compat
4094                    pipe: function( /* fnDone, fnFail, fnProgress */ ) {
4095                        var fns = arguments;
4096
4097                        return jQuery.Deferred( function( newDefer ) {
4098                            jQuery.each( tuples, function( _i, tuple ) {
4099
4100                                // Map tuples (progress, done, fail) to arguments (done, fail, progress)
4101                                var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ];
4102
4103                                // deferred.progress(function() { bind to newDefer or newDefer.notify })
4104                                // deferred.done(function() { bind to newDefer or newDefer.resolve })
4105                                // deferred.fail(function() { bind to newDefer or newDefer.reject })
4106                                deferred[ tuple[ 1 ] ]( function() {
4107                                    var returned = fn && fn.apply( this, arguments );
4108                                    if ( returned && isFunction( returned.promise ) ) {
4109                                        returned.promise()
4110                                            .progress( newDefer.notify )
4111                                            .done( newDefer.resolve )
4112                                            .fail( newDefer.reject );
4113                                    } else {
4114                                        newDefer[ tuple[ 0 ] + "With" ](
4115                                            this,
4116                                            fn ? [ returned ] : arguments
4117                                        );
4118                                    }
4119                                } );
4120                            } );
4121                            fns = null;
4122                        } ).promise();
4123                    },
4124                    then: function( onFulfilled, onRejected, onProgress ) {
4125                        var maxDepth = 0;
4126                        function resolve( depth, deferred, handler, special ) {
4127                            return function() {
4128                                var that = this,
4129                                    args = arguments,
4130                                    mightThrow = function() {
4131                                        var returned, then;
4132
4133                                        // Support: Promises/A+ section 2.3.3.3.3
4134                                        // https://promisesaplus.com/#point-59
4135                                        // Ignore double-resolution attempts
4136                                        if ( depth < maxDepth ) {
4137                                            return;
4138                                        }
4139
4140                                        returned = handler.apply( that, args );
4141
4142                                        // Support: Promises/A+ section 2.3.1
4143                                        // https://promisesaplus.com/#point-48
4144                                        if ( returned === deferred.promise() ) {
4145                                            throw new TypeError( "Thenable self-resolution" );
4146                                        }
4147
4148                                        // Support: Promises/A+ sections 2.3.3.1, 3.5
4149                                        // https://promisesaplus.com/#point-54
4150                                        // https://promisesaplus.com/#point-75
4151                                        // Retrieve `then` only once
4152                                        then = returned &&
4153
4154                                            // Support: Promises/A+ section 2.3.4
4155                                            // https://promisesaplus.com/#point-64
4156                                            // Only check objects and functions for thenability
4157                                            ( typeof returned === "object" ||
4158                                                typeof returned === "function" ) &&
4159                                            returned.then;
4160
4161                                        // Handle a returned thenable
4162                                        if ( isFunction( then ) ) {
4163
4164                                            // Special processors (notify) just wait for resolution
4165                                            if ( special ) {
4166                                                then.call(
4167                                                    returned,
4168                                                    resolve( maxDepth, deferred, Identity, special ),
4169                                                    resolve( maxDepth, deferred, Thrower, special )
4170                                                );
4171
4172                                                // Normal processors (resolve) also hook into progress
4173                                            } else {
4174
4175                                                // ...and disregard older resolution values
4176                                                maxDepth++;
4177
4178                                                then.call(
4179                                                    returned,
4180                                                    resolve( maxDepth, deferred, Identity, special ),
4181                                                    resolve( maxDepth, deferred, Thrower, special ),
4182                                                    resolve( maxDepth, deferred, Identity,
4183                                                        deferred.notifyWith )
4184                                                );
4185                                            }
4186
4187                                            // Handle all other returned values
4188                                        } else {
4189
4190                                            // Only substitute handlers pass on context
4191                                            // and multiple values (non-spec behavior)
4192                                            if ( handler !== Identity ) {
4193                                                that = undefined;
4194                                                args = [ returned ];
4195                                            }
4196
4197                                            // Process the value(s)
4198                                            // Default process is resolve
4199                                            ( special || deferred.resolveWith )( that, args );
4200                                        }
4201                                    },
4202
4203                                    // Only normal processors (resolve) catch and reject exceptions
4204                                    process = special ?
4205                                        mightThrow :
4206                                        function() {
4207                                            try {
4208                                                mightThrow();
4209                                            } catch ( e ) {
4210
4211                                                if ( jQuery.Deferred.exceptionHook ) {
4212                                                    jQuery.Deferred.exceptionHook( e,
4213                                                        process.stackTrace );
4214                                                }
4215
4216                                                // Support: Promises/A+ section 2.3.3.3.4.1
4217                                                // https://promisesaplus.com/#point-61
4218                                                // Ignore post-resolution exceptions
4219                                                if ( depth + 1 >= maxDepth ) {
4220
4221                                                    // Only substitute handlers pass on context
4222                                                    // and multiple values (non-spec behavior)
4223                                                    if ( handler !== Thrower ) {
4224                                                        that = undefined;
4225                                                        args = [ e ];
4226                                                    }
4227
4228                                                    deferred.rejectWith( that, args );
4229                                                }
4230                                            }
4231                                        };
4232
4233                                // Support: Promises/A+ section 2.3.3.3.1
4234                                // https://promisesaplus.com/#point-57
4235                                // Re-resolve promises immediately to dodge false rejection from
4236                                // subsequent errors
4237                                if ( depth ) {
4238                                    process();
4239                                } else {
4240
4241                                    // Call an optional hook to record the stack, in case of exception
4242                                    // since it's otherwise lost when execution goes async
4243                                    if ( jQuery.Deferred.getStackHook ) {
4244                                        process.stackTrace = jQuery.Deferred.getStackHook();
4245                                    }
4246                                    window.setTimeout( process );
4247                                }
4248                            };
4249                        }
4250
4251                        return jQuery.Deferred( function( newDefer ) {
4252
4253                            // progress_handlers.add( ... )
4254                            tuples[ 0 ][ 3 ].add(
4255                                resolve(
4256                                    0,
4257                                    newDefer,
4258                                    isFunction( onProgress ) ?
4259                                        onProgress :
4260                                        Identity,
4261                                    newDefer.notifyWith
4262                                )
4263                            );
4264
4265                            // fulfilled_handlers.add( ... )
4266                            tuples[ 1 ][ 3 ].add(
4267                                resolve(
4268                                    0,
4269                                    newDefer,
4270                                    isFunction( onFulfilled ) ?
4271                                        onFulfilled :
4272                                        Identity
4273                                )
4274                            );
4275
4276                            // rejected_handlers.add( ... )
4277                            tuples[ 2 ][ 3 ].add(
4278                                resolve(
4279                                    0,
4280                                    newDefer,
4281                                    isFunction( onRejected ) ?
4282                                        onRejected :
4283                                        Thrower
4284                                )
4285                            );
4286                        } ).promise();
4287                    },
4288
4289                    // Get a promise for this deferred
4290                    // If obj is provided, the promise aspect is added to the object
4291                    promise: function( obj ) {
4292                        return obj != null ? jQuery.extend( obj, promise ) : promise;
4293                    }
4294                },
4295                deferred = {};
4296
4297            // Add list-specific methods
4298            jQuery.each( tuples, function( i, tuple ) {
4299                var list = tuple[ 2 ],
4300                    stateString = tuple[ 5 ];
4301
4302                // promise.progress = list.add
4303                // promise.done = list.add
4304                // promise.fail = list.add
4305                promise[ tuple[ 1 ] ] = list.add;
4306
4307                // Handle state
4308                if ( stateString ) {
4309                    list.add(
4310                        function() {
4311
4312                            // state = "resolved" (i.e., fulfilled)
4313                            // state = "rejected"
4314                            state = stateString;
4315                        },
4316
4317                        // rejected_callbacks.disable
4318                        // fulfilled_callbacks.disable
4319                        tuples[ 3 - i ][ 2 ].disable,
4320
4321                        // rejected_handlers.disable
4322                        // fulfilled_handlers.disable
4323                        tuples[ 3 - i ][ 3 ].disable,
4324
4325                        // progress_callbacks.lock
4326                        tuples[ 0 ][ 2 ].lock,
4327
4328                        // progress_handlers.lock
4329                        tuples[ 0 ][ 3 ].lock
4330                    );
4331                }
4332
4333                // progress_handlers.fire
4334                // fulfilled_handlers.fire
4335                // rejected_handlers.fire
4336                list.add( tuple[ 3 ].fire );
4337
4338                // deferred.notify = function() { deferred.notifyWith(...) }
4339                // deferred.resolve = function() { deferred.resolveWith(...) }
4340                // deferred.reject = function() { deferred.rejectWith(...) }
4341                deferred[ tuple[ 0 ] ] = function() {
4342                    deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments );
4343                    return this;
4344                };
4345
4346                // deferred.notifyWith = list.fireWith
4347                // deferred.resolveWith = list.fireWith
4348                // deferred.rejectWith = list.fireWith
4349                deferred[ tuple[ 0 ] + "With" ] = list.fireWith;
4350            } );
4351
4352            // Make the deferred a promise
4353            promise.promise( deferred );
4354
4355            // Call given func if any
4356            if ( func ) {
4357                func.call( deferred, deferred );
4358            }
4359
4360            // All done!
4361            return deferred;
4362        },
4363
4364        // Deferred helper
4365        when: function( singleValue ) {
4366            var
4367
4368                // count of uncompleted subordinates
4369                remaining = arguments.length,
4370
4371                // count of unprocessed arguments
4372                i = remaining,
4373
4374                // subordinate fulfillment data
4375                resolveContexts = Array( i ),
4376                resolveValues = slice.call( arguments ),
4377
4378                // the primary Deferred
4379                primary = jQuery.Deferred(),
4380
4381                // subordinate callback factory
4382                updateFunc = function( i ) {
4383                    return function( value ) {
4384                        resolveContexts[ i ] = this;
4385                        resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
4386                        if ( !( --remaining ) ) {
4387                            primary.resolveWith( resolveContexts, resolveValues );
4388                        }
4389                    };
4390                };
4391
4392            // Single- and empty arguments are adopted like Promise.resolve
4393            if ( remaining <= 1 ) {
4394                adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject,
4395                    !remaining );
4396
4397                // Use .then() to unwrap secondary thenables (cf. gh-3000)
4398                if ( primary.state() === "pending" ||
4399                    isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) {
4400
4401                    return primary.then();
4402                }
4403            }
4404
4405            // Multiple arguments are aggregated like Promise.all array elements
4406            while ( i-- ) {
4407                adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject );
4408            }
4409
4410            return primary.promise();
4411        }
4412    } );
4413
4414
4415// These usually indicate a programmer mistake during development,
4416// warn about them ASAP rather than swallowing them by default.
4417    var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;
4418
4419    jQuery.Deferred.exceptionHook = function( error, stack ) {
4420
4421        // Support: IE 8 - 9 only
4422        // Console exists when dev tools are open, which can happen at any time
4423        if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) {
4424            window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack );
4425        }
4426    };
4427
4428
4429
4430
4431    jQuery.readyException = function( error ) {
4432        window.setTimeout( function() {
4433            throw error;
4434        } );
4435    };
4436
4437
4438
4439
4440// The deferred used on DOM ready
4441    var readyList = jQuery.Deferred();
4442
4443    jQuery.fn.ready = function( fn ) {
4444
4445        readyList
4446            .then( fn )
4447
4448            // Wrap jQuery.readyException in a function so that the lookup
4449            // happens at the time of error handling instead of callback
4450            // registration.
4451            .catch( function( error ) {
4452                jQuery.readyException( error );
4453            } );
4454
4455        return this;
4456    };
4457
4458    jQuery.extend( {
4459
4460        // Is the DOM ready to be used? Set to true once it occurs.
4461        isReady: false,
4462
4463        // A counter to track how many items to wait for before
4464        // the ready event fires. See #6781
4465        readyWait: 1,
4466
4467        // Handle when the DOM is ready
4468        ready: function( wait ) {
4469
4470            // Abort if there are pending holds or we're already ready
4471            if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
4472                return;
4473            }
4474
4475            // Remember that the DOM is ready
4476            jQuery.isReady = true;
4477
4478            // If a normal DOM Ready event fired, decrement, and wait if need be
4479            if ( wait !== true && --jQuery.readyWait > 0 ) {
4480                return;
4481            }
4482
4483            // If there are functions bound, to execute
4484            readyList.resolveWith( document, [ jQuery ] );
4485        }
4486    } );
4487
4488    jQuery.ready.then = readyList.then;
4489
4490// The ready event handler and self cleanup method
4491    function completed() {
4492        document.removeEventListener( "DOMContentLoaded", completed );
4493        window.removeEventListener( "load", completed );
4494        jQuery.ready();
4495    }
4496
4497// Catch cases where $(document).ready() is called
4498// after the browser event has already occurred.
4499// Support: IE <=9 - 10 only
4500// Older IE sometimes signals "interactive" too soon
4501    if ( document.readyState === "complete" ||
4502        ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) {
4503
4504        // Handle it asynchronously to allow scripts the opportunity to delay ready
4505        window.setTimeout( jQuery.ready );
4506
4507    } else {
4508
4509        // Use the handy event callback
4510        document.addEventListener( "DOMContentLoaded", completed );
4511
4512        // A fallback to window.onload, that will always work
4513        window.addEventListener( "load", completed );
4514    }
4515
4516
4517
4518
4519// Multifunctional method to get and set values of a collection
4520// The value/s can optionally be executed if it's a function
4521    var access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
4522        var i = 0,
4523            len = elems.length,
4524            bulk = key == null;
4525
4526        // Sets many values
4527        if ( toType( key ) === "object" ) {
4528            chainable = true;
4529            for ( i in key ) {
4530                access( elems, fn, i, key[ i ], true, emptyGet, raw );
4531            }
4532
4533            // Sets one value
4534        } else if ( value !== undefined ) {
4535            chainable = true;
4536
4537            if ( !isFunction( value ) ) {
4538                raw = true;
4539            }
4540
4541            if ( bulk ) {
4542
4543                // Bulk operations run against the entire set
4544                if ( raw ) {
4545                    fn.call( elems, value );
4546                    fn = null;
4547
4548                    // ...except when executing function values
4549                } else {
4550                    bulk = fn;
4551                    fn = function( elem, _key, value ) {
4552                        return bulk.call( jQuery( elem ), value );
4553                    };
4554                }
4555            }
4556
4557            if ( fn ) {
4558                for ( ; i < len; i++ ) {
4559                    fn(
4560                        elems[ i ], key, raw ?
4561                            value :
4562                            value.call( elems[ i ], i, fn( elems[ i ], key ) )
4563                    );
4564                }
4565            }
4566        }
4567
4568        if ( chainable ) {
4569            return elems;
4570        }
4571
4572        // Gets
4573        if ( bulk ) {
4574            return fn.call( elems );
4575        }
4576
4577        return len ? fn( elems[ 0 ], key ) : emptyGet;
4578    };
4579
4580
4581// Matches dashed string for camelizing
4582    var rmsPrefix = /^-ms-/,
4583        rdashAlpha = /-([a-z])/g;
4584
4585// Used by camelCase as callback to replace()
4586    function fcamelCase( _all, letter ) {
4587        return letter.toUpperCase();
4588    }
4589
4590// Convert dashed to camelCase; used by the css and data modules
4591// Support: IE <=9 - 11, Edge 12 - 15
4592// Microsoft forgot to hump their vendor prefix (#9572)
4593    function camelCase( string ) {
4594        return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
4595    }
4596    var acceptData = function( owner ) {
4597
4598        // Accepts only:
4599        //  - Node
4600        //    - Node.ELEMENT_NODE
4601        //    - Node.DOCUMENT_NODE
4602        //  - Object
4603        //    - Any
4604        return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
4605    };
4606
4607
4608
4609
4610    function Data() {
4611        this.expando = jQuery.expando + Data.uid++;
4612    }
4613
4614    Data.uid = 1;
4615
4616    Data.prototype = {
4617
4618        cache: function( owner ) {
4619
4620            // Check if the owner object already has a cache
4621            var value = owner[ this.expando ];
4622
4623            // If not, create one
4624            if ( !value ) {
4625                value = {};
4626
4627                // We can accept data for non-element nodes in modern browsers,
4628                // but we should not, see #8335.
4629                // Always return an empty object.
4630                if ( acceptData( owner ) ) {
4631
4632                    // If it is a node unlikely to be stringify-ed or looped over
4633                    // use plain assignment
4634                    if ( owner.nodeType ) {
4635                        owner[ this.expando ] = value;
4636
4637                        // Otherwise secure it in a non-enumerable property
4638                        // configurable must be true to allow the property to be
4639                        // deleted when data is removed
4640                    } else {
4641                        Object.defineProperty( owner, this.expando, {
4642                            value: value,
4643                            configurable: true
4644                        } );
4645                    }
4646                }
4647            }
4648
4649            return value;
4650        },
4651        set: function( owner, data, value ) {
4652            var prop,
4653                cache = this.cache( owner );
4654
4655            // Handle: [ owner, key, value ] args
4656            // Always use camelCase key (gh-2257)
4657            if ( typeof data === "string" ) {
4658                cache[ camelCase( data ) ] = value;
4659
4660                // Handle: [ owner, { properties } ] args
4661            } else {
4662
4663                // Copy the properties one-by-one to the cache object
4664                for ( prop in data ) {
4665                    cache[ camelCase( prop ) ] = data[ prop ];
4666                }
4667            }
4668            return cache;
4669        },
4670        get: function( owner, key ) {
4671            return key === undefined ?
4672                this.cache( owner ) :
4673
4674                // Always use camelCase key (gh-2257)
4675                owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ];
4676        },
4677        access: function( owner, key, value ) {
4678
4679            // In cases where either:
4680            //
4681            //   1. No key was specified
4682            //   2. A string key was specified, but no value provided
4683            //
4684            // Take the "read" path and allow the get method to determine
4685            // which value to return, respectively either:
4686            //
4687            //   1. The entire cache object
4688            //   2. The data stored at the key
4689            //
4690            if ( key === undefined ||
4691                ( ( key && typeof key === "string" ) && value === undefined ) ) {
4692
4693                return this.get( owner, key );
4694            }
4695
4696            // When the key is not a string, or both a key and value
4697            // are specified, set or extend (existing objects) with either:
4698            //
4699            //   1. An object of properties
4700            //   2. A key and value
4701            //
4702            this.set( owner, key, value );
4703
vendor: 9,776 bytes, lines 4704-4994
4704            // Since the "set" path can have two possible entry points
4705            // return the expected data based on which path was taken[*]
4706            return value !== undefined ? value : key;
4707        },
4708        remove: function( owner, key ) {
4709            var i,
4710                cache = owner[ this.expando ];
4711
4712            if ( cache === undefined ) {
4713                return;
4714            }
4715
4716            if ( key !== undefined ) {
4717
4718                // Support array or space separated string of keys
4719                if ( Array.isArray( key ) ) {
4720
4721                    // If key is an array of keys...
4722                    // We always set camelCase keys, so remove that.
4723                    key = key.map( camelCase );
4724                } else {
4725                    key = camelCase( key );
4726
4727                    // If a key with the spaces exists, use it.
4728                    // Otherwise, create an array by matching non-whitespace
4729                    key = key in cache ?
4730                        [ key ] :
4731                        ( key.match( rnothtmlwhite ) || [] );
4732                }
4733
4734                i = key.length;
4735
4736                while ( i-- ) {
4737                    delete cache[ key[ i ] ];
4738                }
4739            }
4740
4741            // Remove the expando if there's no more data
4742            if ( key === undefined || jQuery.isEmptyObject( cache ) ) {
4743
4744                // Support: Chrome <=35 - 45
4745                // Webkit & Blink performance suffers when deleting properties
4746                // from DOM nodes, so set to undefined instead
4747                // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted)
4748                if ( owner.nodeType ) {
4749                    owner[ this.expando ] = undefined;
4750                } else {
4751                    delete owner[ this.expando ];
4752                }
4753            }
4754        },
4755        hasData: function( owner ) {
4756            var cache = owner[ this.expando ];
4757            return cache !== undefined && !jQuery.isEmptyObject( cache );
4758        }
4759    };
4760    var dataPriv = new Data();
4761
4762    var dataUser = new Data();
4763
4764
4765
4766//	Implementation Summary
4767//
4768//	1. Enforce API surface and semantic compatibility with 1.9.x branch
4769//	2. Improve the module's maintainability by reducing the storage
4770//		paths to a single mechanism.
4771//	3. Use the same single mechanism to support "private" and "user" data.
4772//	4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
4773//	5. Avoid exposing implementation details on user objects (eg. expando properties)
4774//	6. Provide a clear path for implementation upgrade to WeakMap in 2014
4775
4776    var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
4777        rmultiDash = /[A-Z]/g;
4778
4779    function getData( data ) {
4780        if ( data === "true" ) {
4781            return true;
4782        }
4783
4784        if ( data === "false" ) {
4785            return false;
4786        }
4787
4788        if ( data === "null" ) {
4789            return null;
4790        }
4791
4792        // Only convert to a number if it doesn't change the string
4793        if ( data === +data + "" ) {
4794            return +data;
4795        }
4796
4797        if ( rbrace.test( data ) ) {
4798            return JSON.parse( data );
4799        }
4800
4801        return data;
4802    }
4803
4804    function dataAttr( elem, key, data ) {
4805        var name;
4806
4807        // If nothing was found internally, try to fetch any
4808        // data from the HTML5 data-* attribute
4809        if ( data === undefined && elem.nodeType === 1 ) {
4810            name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase();
4811            data = elem.getAttribute( name );
4812
4813            if ( typeof data === "string" ) {
4814                try {
4815                    data = getData( data );
4816                } catch ( e ) {}
4817
4818                // Make sure we set the data so it isn't changed later
4819                dataUser.set( elem, key, data );
4820            } else {
4821                data = undefined;
4822            }
4823        }
4824        return data;
4825    }
4826
4827    jQuery.extend( {
4828        hasData: function( elem ) {
4829            return dataUser.hasData( elem ) || dataPriv.hasData( elem );
4830        },
4831
4832        data: function( elem, name, data ) {
4833            return dataUser.access( elem, name, data );
4834        },
4835
4836        removeData: function( elem, name ) {
4837            dataUser.remove( elem, name );
4838        },
4839
4840        // TODO: Now that all calls to _data and _removeData have been replaced
4841        // with direct calls to dataPriv methods, these can be deprecated.
4842        _data: function( elem, name, data ) {
4843            return dataPriv.access( elem, name, data );
4844        },
4845
4846        _removeData: function( elem, name ) {
4847            dataPriv.remove( elem, name );
4848        }
4849    } );
4850
4851    jQuery.fn.extend( {
4852        data: function( key, value ) {
4853            var i, name, data,
4854                elem = this[ 0 ],
4855                attrs = elem && elem.attributes;
4856
4857            // Gets all values
4858            if ( key === undefined ) {
4859                if ( this.length ) {
4860                    data = dataUser.get( elem );
4861
4862                    if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) {
4863                        i = attrs.length;
4864                        while ( i-- ) {
4865
4866                            // Support: IE 11 only
4867                            // The attrs elements can be null (#14894)
4868                            if ( attrs[ i ] ) {
4869                                name = attrs[ i ].name;
4870                                if ( name.indexOf( "data-" ) === 0 ) {
4871                                    name = camelCase( name.slice( 5 ) );
4872                                    dataAttr( elem, name, data[ name ] );
4873                                }
4874                            }
4875                        }
4876                        dataPriv.set( elem, "hasDataAttrs", true );
4877                    }
4878                }
4879
4880                return data;
4881            }
4882
4883            // Sets multiple values
4884            if ( typeof key === "object" ) {
4885                return this.each( function() {
4886                    dataUser.set( this, key );
4887                } );
4888            }
4889
4890            return access( this, function( value ) {
4891                var data;
4892
4893                // The calling jQuery object (element matches) is not empty
4894                // (and therefore has an element appears at this[ 0 ]) and the
4895                // `value` parameter was not undefined. An empty jQuery object
4896                // will result in `undefined` for elem = this[ 0 ] which will
4897                // throw an exception if an attempt to read a data cache is made.
4898                if ( elem && value === undefined ) {
4899
4900                    // Attempt to get data from the cache
4901                    // The key will always be camelCased in Data
4902                    data = dataUser.get( elem, key );
4903                    if ( data !== undefined ) {
4904                        return data;
4905                    }
4906
4907                    // Attempt to "discover" the data in
4908                    // HTML5 custom data-* attrs
4909                    data = dataAttr( elem, key );
4910                    if ( data !== undefined ) {
4911                        return data;
4912                    }
4913
4914                    // We tried really hard, but the data doesn't exist.
4915                    return;
4916                }
4917
4918                // Set the data...
4919                this.each( function() {
4920
4921                    // We always store the camelCased key
4922                    dataUser.set( this, key, value );
4923                } );
4924            }, null, value, arguments.length > 1, null, true );
4925        },
4926
4927        removeData: function( key ) {
4928            return this.each( function() {
4929                dataUser.remove( this, key );
4930            } );
4931        }
4932    } );
4933
4934
4935    jQuery.extend( {
4936        queue: function( elem, type, data ) {
4937            var queue;
4938
4939            if ( elem ) {
4940                type = ( type || "fx" ) + "queue";
4941                queue = dataPriv.get( elem, type );
4942
4943                // Speed up dequeue by getting out quickly if this is just a lookup
4944                if ( data ) {
4945                    if ( !queue || Array.isArray( data ) ) {
4946                        queue = dataPriv.access( elem, type, jQuery.makeArray( data ) );
4947                    } else {
4948                        queue.push( data );
4949                    }
4950                }
4951                return queue || [];
4952            }
4953        },
4954
4955        dequeue: function( elem, type ) {
4956            type = type || "fx";
4957
4958            var queue = jQuery.queue( elem, type ),
4959                startLength = queue.length,
4960                fn = queue.shift(),
4961                hooks = jQuery._queueHooks( elem, type ),
4962                next = function() {
4963                    jQuery.dequeue( elem, type );
4964                };
4965
4966            // If the fx queue is dequeued, always remove the progress sentinel
4967            if ( fn === "inprogress" ) {
4968                fn = queue.shift();
4969                startLength--;
4970            }
4971
4972            if ( fn ) {
4973
4974                // Add a progress sentinel to prevent the fx queue from being
4975                // automatically dequeued
4976                if ( type === "fx" ) {
4977                    queue.unshift( "inprogress" );
4978                }
4979
4980                // Clear up the last queue stop function
4981                delete hooks.stop;
4982                fn.call( elem, next, hooks );
4983            }
4984
4985            if ( !startLength && hooks ) {
4986                hooks.empty.fire();
4987            }
4988        },
4989
4990        // Not public - generate a queueHooks object, or return the current one
4991        _queueHooks: function( elem, type ) {
4992            var key = type + "queueHooks";
4993            return dataPriv.get( elem, key ) || dataPriv.access( elem, key, {
4994                empty: jQuery.Callbacks( "once memory" ).add( function() {
vendor: 14,054 bytes, lines 4995-5417
4995                    dataPriv.remove( elem, [ type + "queue", key ] );
4996                } )
4997            } );
4998        }
4999    } );
5000
5001    jQuery.fn.extend( {
5002        queue: function( type, data ) {
5003            var setter = 2;
5004
5005            if ( typeof type !== "string" ) {
5006                data = type;
5007                type = "fx";
5008                setter--;
5009            }
5010
5011            if ( arguments.length < setter ) {
5012                return jQuery.queue( this[ 0 ], type );
5013            }
5014
5015            return data === undefined ?
5016                this :
5017                this.each( function() {
5018                    var queue = jQuery.queue( this, type, data );
5019
5020                    // Ensure a hooks for this queue
5021                    jQuery._queueHooks( this, type );
5022
5023                    if ( type === "fx" && queue[ 0 ] !== "inprogress" ) {
5024                        jQuery.dequeue( this, type );
5025                    }
5026                } );
5027        },
5028        dequeue: function( type ) {
5029            return this.each( function() {
5030                jQuery.dequeue( this, type );
5031            } );
5032        },
5033        clearQueue: function( type ) {
5034            return this.queue( type || "fx", [] );
5035        },
5036
5037        // Get a promise resolved when queues of a certain type
5038        // are emptied (fx is the type by default)
5039        promise: function( type, obj ) {
5040            var tmp,
5041                count = 1,
5042                defer = jQuery.Deferred(),
5043                elements = this,
5044                i = this.length,
5045                resolve = function() {
5046                    if ( !( --count ) ) {
5047                        defer.resolveWith( elements, [ elements ] );
5048                    }
5049                };
5050
5051            if ( typeof type !== "string" ) {
5052                obj = type;
5053                type = undefined;
5054            }
5055            type = type || "fx";
5056
5057            while ( i-- ) {
5058                tmp = dataPriv.get( elements[ i ], type + "queueHooks" );
5059                if ( tmp && tmp.empty ) {
5060                    count++;
5061                    tmp.empty.add( resolve );
5062                }
5063            }
5064            resolve();
5065            return defer.promise( obj );
5066        }
5067    } );
5068    var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source;
5069
5070    var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" );
5071
5072
5073    var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
5074
5075    var documentElement = document.documentElement;
5076
5077
5078
5079    var isAttached = function( elem ) {
5080            return jQuery.contains( elem.ownerDocument, elem );
5081        },
5082        composed = { composed: true };
5083
5084    // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only
5085    // Check attachment across shadow DOM boundaries when possible (gh-3504)
5086    // Support: iOS 10.0-10.2 only
5087    // Early iOS 10 versions support `attachShadow` but not `getRootNode`,
5088    // leading to errors. We need to check for `getRootNode`.
5089    if ( documentElement.getRootNode ) {
5090        isAttached = function( elem ) {
5091            return jQuery.contains( elem.ownerDocument, elem ) ||
5092                elem.getRootNode( composed ) === elem.ownerDocument;
5093        };
5094    }
5095    var isHiddenWithinTree = function( elem, el ) {
5096
5097        // isHiddenWithinTree might be called from jQuery#filter function;
5098        // in that case, element will be second argument
5099        elem = el || elem;
5100
5101        // Inline style trumps all
5102        return elem.style.display === "none" ||
5103            elem.style.display === "" &&
5104
5105            // Otherwise, check computed style
5106            // Support: Firefox <=43 - 45
5107            // Disconnected elements can have computed display: none, so first confirm that elem is
5108            // in the document.
5109            isAttached( elem ) &&
5110
5111            jQuery.css( elem, "display" ) === "none";
5112    };
5113
5114
5115
5116    function adjustCSS( elem, prop, valueParts, tween ) {
5117        var adjusted, scale,
5118            maxIterations = 20,
5119            currentValue = tween ?
5120                function() {
5121                    return tween.cur();
5122                } :
5123                function() {
5124                    return jQuery.css( elem, prop, "" );
5125                },
5126            initial = currentValue(),
5127            unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
5128
5129            // Starting value computation is required for potential unit mismatches
5130            initialInUnit = elem.nodeType &&
5131                ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) &&
5132                rcssNum.exec( jQuery.css( elem, prop ) );
5133
5134        if ( initialInUnit && initialInUnit[ 3 ] !== unit ) {
5135
5136            // Support: Firefox <=54
5137            // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144)
5138            initial = initial / 2;
5139
5140            // Trust units reported by jQuery.css
5141            unit = unit || initialInUnit[ 3 ];
5142
5143            // Iteratively approximate from a nonzero starting point
5144            initialInUnit = +initial || 1;
5145
5146            while ( maxIterations-- ) {
5147
5148                // Evaluate and update our best guess (doubling guesses that zero out).
5149                // Finish if the scale equals or crosses 1 (making the old*new product non-positive).
5150                jQuery.style( elem, prop, initialInUnit + unit );
5151                if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) {
5152                    maxIterations = 0;
5153                }
5154                initialInUnit = initialInUnit / scale;
5155
5156            }
5157
5158            initialInUnit = initialInUnit * 2;
5159            jQuery.style( elem, prop, initialInUnit + unit );
5160
5161            // Make sure we update the tween properties later on
5162            valueParts = valueParts || [];
5163        }
5164
5165        if ( valueParts ) {
5166            initialInUnit = +initialInUnit || +initial || 0;
5167
5168            // Apply relative offset (+=/-=) if specified
5169            adjusted = valueParts[ 1 ] ?
5170                initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] :
5171                +valueParts[ 2 ];
5172            if ( tween ) {
5173                tween.unit = unit;
5174                tween.start = initialInUnit;
5175                tween.end = adjusted;
5176            }
5177        }
5178        return adjusted;
5179    }
5180
5181
5182    var defaultDisplayMap = {};
5183
5184    function getDefaultDisplay( elem ) {
5185        var temp,
5186            doc = elem.ownerDocument,
5187            nodeName = elem.nodeName,
5188            display = defaultDisplayMap[ nodeName ];
5189
5190        if ( display ) {
5191            return display;
5192        }
5193
5194        temp = doc.body.appendChild( doc.createElement( nodeName ) );
5195        display = jQuery.css( temp, "display" );
5196
5197        temp.parentNode.removeChild( temp );
5198
5199        if ( display === "none" ) {
5200            display = "block";
5201        }
5202        defaultDisplayMap[ nodeName ] = display;
5203
5204        return display;
5205    }
5206
5207    function showHide( elements, show ) {
5208        var display, elem,
5209            values = [],
5210            index = 0,
5211            length = elements.length;
5212
5213        // Determine new display value for elements that need to change
5214        for ( ; index < length; index++ ) {
5215            elem = elements[ index ];
5216            if ( !elem.style ) {
5217                continue;
5218            }
5219
5220            display = elem.style.display;
5221            if ( show ) {
5222
5223                // Since we force visibility upon cascade-hidden elements, an immediate (and slow)
5224                // check is required in this first loop unless we have a nonempty display value (either
5225                // inline or about-to-be-restored)
5226                if ( display === "none" ) {
5227                    values[ index ] = dataPriv.get( elem, "display" ) || null;
5228                    if ( !values[ index ] ) {
5229                        elem.style.display = "";
5230                    }
5231                }
5232                if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) {
5233                    values[ index ] = getDefaultDisplay( elem );
5234                }
5235            } else {
5236                if ( display !== "none" ) {
5237                    values[ index ] = "none";
5238
5239                    // Remember what we're overwriting
5240                    dataPriv.set( elem, "display", display );
5241                }
5242            }
5243        }
5244
5245        // Set the display of the elements in a second loop to avoid constant reflow
5246        for ( index = 0; index < length; index++ ) {
5247            if ( values[ index ] != null ) {
5248                elements[ index ].style.display = values[ index ];
5249            }
5250        }
5251
5252        return elements;
5253    }
5254
5255    jQuery.fn.extend( {
5256        show: function() {
5257            return showHide( this, true );
5258        },
5259        hide: function() {
5260            return showHide( this );
5261        },
5262        toggle: function( state ) {
5263            if ( typeof state === "boolean" ) {
5264                return state ? this.show() : this.hide();
5265            }
5266
5267            return this.each( function() {
5268                if ( isHiddenWithinTree( this ) ) {
5269                    jQuery( this ).show();
5270                } else {
5271                    jQuery( this ).hide();
5272                }
5273            } );
5274        }
5275    } );
5276    var rcheckableType = ( /^(?:checkbox|radio)$/i );
5277
5278    var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i );
5279
5280    var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i );
5281
5282
5283
5284    ( function() {
5285        var fragment = document.createDocumentFragment(),
5286            div = fragment.appendChild( document.createElement( "div" ) ),
5287            input = document.createElement( "input" );
5288
5289        // Support: Android 4.0 - 4.3 only
5290        // Check state lost if the name is set (#11217)
5291        // Support: Windows Web Apps (WWA)
5292        // `name` and `type` must use .setAttribute for WWA (#14901)
5293        input.setAttribute( "type", "radio" );
5294        input.setAttribute( "checked", "checked" );
5295        input.setAttribute( "name", "t" );
5296
5297        div.appendChild( input );
5298
5299        // Support: Android <=4.1 only
5300        // Older WebKit doesn't clone checked state correctly in fragments
5301        support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
5302
5303        // Support: IE <=11 only
5304        // Make sure textarea (and checkbox) defaultValue is properly cloned
5305        div.innerHTML = "<textarea>x</textarea>";
5306        support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
5307
5308        // Support: IE <=9 only
5309        // IE <=9 replaces <option> tags with their contents when inserted outside of
5310        // the select element.
5311        div.innerHTML = "<option></option>";
5312        support.option = !!div.lastChild;
5313    } )();
5314
5315
5316// We have to close these tags to support XHTML (#13200)
5317    var wrapMap = {
5318
5319        // XHTML parsers do not magically insert elements in the
5320        // same way that tag soup parsers do. So we cannot shorten
5321        // this by omitting <tbody> or other required elements.
5322        thead: [ 1, "<table>", "</table>" ],
5323        col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
5324        tr: [ 2, "<table><tbody>", "</tbody></table>" ],
5325        td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
5326
5327        _default: [ 0, "", "" ]
5328    };
5329
5330    wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
5331    wrapMap.th = wrapMap.td;
5332
5333// Support: IE <=9 only
5334    if ( !support.option ) {
5335        wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ];
5336    }
5337
5338
5339    function getAll( context, tag ) {
5340
5341        // Support: IE <=9 - 11 only
5342        // Use typeof to avoid zero-argument method invocation on host objects (#15151)
5343        var ret;
5344
5345        if ( typeof context.getElementsByTagName !== "undefined" ) {
5346            ret = context.getElementsByTagName( tag || "*" );
5347
5348        } else if ( typeof context.querySelectorAll !== "undefined" ) {
5349            ret = context.querySelectorAll( tag || "*" );
5350
5351        } else {
5352            ret = [];
5353        }
5354
5355        if ( tag === undefined || tag && nodeName( context, tag ) ) {
5356            return jQuery.merge( [ context ], ret );
5357        }
5358
5359        return ret;
5360    }
5361
5362
5363// Mark scripts as having already been evaluated
5364    function setGlobalEval( elems, refElements ) {
5365        var i = 0,
5366            l = elems.length;
5367
5368        for ( ; i < l; i++ ) {
5369            dataPriv.set(
5370                elems[ i ],
5371                "globalEval",
5372                !refElements || dataPriv.get( refElements[ i ], "globalEval" )
5373            );
5374        }
5375    }
5376
5377
5378    var rhtml = /<|&#?\w+;/;
5379
5380    function buildFragment( elems, context, scripts, selection, ignored ) {
5381        var elem, tmp, tag, wrap, attached, j,
5382            fragment = context.createDocumentFragment(),
5383            nodes = [],
5384            i = 0,
5385            l = elems.length;
5386
5387        for ( ; i < l; i++ ) {
5388            elem = elems[ i ];
5389
5390            if ( elem || elem === 0 ) {
5391
5392                // Add nodes directly
5393                if ( toType( elem ) === "object" ) {
5394
5395                    // Support: Android <=4.0 only, PhantomJS 1 only
5396                    // push.apply(_, arraylike) throws on ancient WebKit
5397                    jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
5398
5399                    // Convert non-html into a text node
5400                } else if ( !rhtml.test( elem ) ) {
5401                    nodes.push( context.createTextNode( elem ) );
5402
5403                    // Convert html into DOM nodes
5404                } else {
5405                    tmp = tmp || fragment.appendChild( context.createElement( "div" ) );
5406
5407                    // Deserialize a standard representation
5408                    tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
5409                    wrap = wrapMap[ tag ] || wrapMap._default;
5410                    tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ];
5411
5412                    // Descend through wrappers to the right content
5413                    j = wrap[ 0 ];
5414                    while ( j-- ) {
5415                        tmp = tmp.lastChild;
5416                    }
5417
vendor: 9,502 bytes, lines 5418-5693
5418                    // Support: Android <=4.0 only, PhantomJS 1 only
5419                    // push.apply(_, arraylike) throws on ancient WebKit
5420                    jQuery.merge( nodes, tmp.childNodes );
5421
5422                    // Remember the top-level container
5423                    tmp = fragment.firstChild;
5424
5425                    // Ensure the created nodes are orphaned (#12392)
5426                    tmp.textContent = "";
5427                }
5428            }
5429        }
5430
5431        // Remove wrapper from fragment
5432        fragment.textContent = "";
5433
5434        i = 0;
5435        while ( ( elem = nodes[ i++ ] ) ) {
5436
5437            // Skip elements already in the context collection (trac-4087)
5438            if ( selection && jQuery.inArray( elem, selection ) > -1 ) {
5439                if ( ignored ) {
5440                    ignored.push( elem );
5441                }
5442                continue;
5443            }
5444
5445            attached = isAttached( elem );
5446
5447            // Append to fragment
5448            tmp = getAll( fragment.appendChild( elem ), "script" );
5449
5450            // Preserve script evaluation history
5451            if ( attached ) {
5452                setGlobalEval( tmp );
5453            }
5454
5455            // Capture executables
5456            if ( scripts ) {
5457                j = 0;
5458                while ( ( elem = tmp[ j++ ] ) ) {
5459                    if ( rscriptType.test( elem.type || "" ) ) {
5460                        scripts.push( elem );
5461                    }
5462                }
5463            }
5464        }
5465
5466        return fragment;
5467    }
5468
5469
5470    var rtypenamespace = /^([^.]*)(?:\.(.+)|)/;
5471
5472    function returnTrue() {
5473        return true;
5474    }
5475
5476    function returnFalse() {
5477        return false;
5478    }
5479
5480// Support: IE <=9 - 11+
5481// focus() and blur() are asynchronous, except when they are no-op.
5482// So expect focus to be synchronous when the element is already active,
5483// and blur to be synchronous when the element is not already active.
5484// (focus and blur are always synchronous in other supported browsers,
5485// this just defines when we can count on it).
5486    function expectSync( elem, type ) {
5487        return ( elem === safeActiveElement() ) === ( type === "focus" );
5488    }
5489
5490// Support: IE <=9 only
5491// Accessing document.activeElement can throw unexpectedly
5492// https://bugs.jquery.com/ticket/13393
5493    function safeActiveElement() {
5494        try {
5495            return document.activeElement;
5496        } catch ( err ) { }
5497    }
5498
5499    function on( elem, types, selector, data, fn, one ) {
5500        var origFn, type;
5501
5502        // Types can be a map of types/handlers
5503        if ( typeof types === "object" ) {
5504
5505            // ( types-Object, selector, data )
5506            if ( typeof selector !== "string" ) {
5507
5508                // ( types-Object, data )
5509                data = data || selector;
5510                selector = undefined;
5511            }
5512            for ( type in types ) {
5513                on( elem, type, selector, data, types[ type ], one );
5514            }
5515            return elem;
5516        }
5517
5518        if ( data == null && fn == null ) {
5519
5520            // ( types, fn )
5521            fn = selector;
5522            data = selector = undefined;
5523        } else if ( fn == null ) {
5524            if ( typeof selector === "string" ) {
5525
5526                // ( types, selector, fn )
5527                fn = data;
5528                data = undefined;
5529            } else {
5530
5531                // ( types, data, fn )
5532                fn = data;
5533                data = selector;
5534                selector = undefined;
5535            }
5536        }
5537        if ( fn === false ) {
5538            fn = returnFalse;
5539        } else if ( !fn ) {
5540            return elem;
5541        }
5542
5543        if ( one === 1 ) {
5544            origFn = fn;
5545            fn = function( event ) {
5546
5547                // Can use an empty set, since event contains the info
5548                jQuery().off( event );
5549                return origFn.apply( this, arguments );
5550            };
5551
5552            // Use same guid so caller can remove using origFn
5553            fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
5554        }
5555        return elem.each( function() {
5556            jQuery.event.add( this, types, fn, data, selector );
5557        } );
5558    }
5559
5560    /*
5561 * Helper functions for managing events -- not part of the public interface.
5562 * Props to Dean Edwards' addEvent library for many of the ideas.
5563 */
5564    jQuery.event = {
5565
5566        global: {},
5567
5568        add: function( elem, types, handler, data, selector ) {
5569
5570            var handleObjIn, eventHandle, tmp,
5571                events, t, handleObj,
5572                special, handlers, type, namespaces, origType,
5573                elemData = dataPriv.get( elem );
5574
5575            // Only attach events to objects that accept data
5576            if ( !acceptData( elem ) ) {
5577                return;
5578            }
5579
5580            // Caller can pass in an object of custom data in lieu of the handler
5581            if ( handler.handler ) {
5582                handleObjIn = handler;
5583                handler = handleObjIn.handler;
5584                selector = handleObjIn.selector;
5585            }
5586
5587            // Ensure that invalid selectors throw exceptions at attach time
5588            // Evaluate against documentElement in case elem is a non-element node (e.g., document)
5589            if ( selector ) {
5590                jQuery.find.matchesSelector( documentElement, selector );
5591            }
5592
5593            // Make sure that the handler has a unique ID, used to find/remove it later
5594            if ( !handler.guid ) {
5595                handler.guid = jQuery.guid++;
5596            }
5597
5598            // Init the element's event structure and main handler, if this is the first
5599            if ( !( events = elemData.events ) ) {
5600                events = elemData.events = Object.create( null );
5601            }
5602            if ( !( eventHandle = elemData.handle ) ) {
5603                eventHandle = elemData.handle = function( e ) {
5604
5605                    // Discard the second event of a jQuery.event.trigger() and
5606                    // when an event is called after a page has unloaded
5607                    return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ?
5608                        jQuery.event.dispatch.apply( elem, arguments ) : undefined;
5609                };
5610            }
5611
5612            // Handle multiple events separated by a space
5613            types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
5614            t = types.length;
5615            while ( t-- ) {
5616                tmp = rtypenamespace.exec( types[ t ] ) || [];
5617                type = origType = tmp[ 1 ];
5618                namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
5619
5620                // There *must* be a type, no attaching namespace-only handlers
5621                if ( !type ) {
5622                    continue;
5623                }
5624
5625                // If event changes its type, use the special event handlers for the changed type
5626                special = jQuery.event.special[ type ] || {};
5627
5628                // If selector defined, determine special event api type, otherwise given type
5629                type = ( selector ? special.delegateType : special.bindType ) || type;
5630
5631                // Update special based on newly reset type
5632                special = jQuery.event.special[ type ] || {};
5633
5634                // handleObj is passed to all event handlers
5635                handleObj = jQuery.extend( {
5636                    type: type,
5637                    origType: origType,
5638                    data: data,
5639                    handler: handler,
5640                    guid: handler.guid,
5641                    selector: selector,
5642                    needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
5643                    namespace: namespaces.join( "." )
5644                }, handleObjIn );
5645
5646                // Init the event handler queue if we're the first
5647                if ( !( handlers = events[ type ] ) ) {
5648                    handlers = events[ type ] = [];
5649                    handlers.delegateCount = 0;
5650
5651                    // Only use addEventListener if the special events handler returns false
5652                    if ( !special.setup ||
5653                        special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
5654
5655                        if ( elem.addEventListener ) {
5656                            elem.addEventListener( type, eventHandle );
5657                        }
5658                    }
5659                }
5660
5661                if ( special.add ) {
5662                    special.add.call( elem, handleObj );
5663
5664                    if ( !handleObj.handler.guid ) {
5665                        handleObj.handler.guid = handler.guid;
5666                    }
5667                }
5668
5669                // Add to the element's handler list, delegates in front
5670                if ( selector ) {
5671                    handlers.splice( handlers.delegateCount++, 0, handleObj );
5672                } else {
5673                    handlers.push( handleObj );
5674                }
5675
5676                // Keep track of which events have ever been used, for event optimization
5677                jQuery.event.global[ type ] = true;
5678            }
5679
5680        },
5681
5682        // Detach an event or set of events from an element
5683        remove: function( elem, types, handler, selector, mappedTypes ) {
5684
5685            var j, origCount, tmp,
5686                events, t, handleObj,
5687                special, handlers, type, namespaces, origType,
5688                elemData = dataPriv.hasData( elem ) && dataPriv.get( elem );
5689
5690            if ( !elemData || !( events = elemData.events ) ) {
5691                return;
5692            }
5693
vendor: 4,497 bytes, lines 5694-5797
5694            // Once for each type.namespace in types; type may be omitted
5695            types = ( types || "" ).match( rnothtmlwhite ) || [ "" ];
5696            t = types.length;
5697            while ( t-- ) {
5698                tmp = rtypenamespace.exec( types[ t ] ) || [];
5699                type = origType = tmp[ 1 ];
5700                namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort();
5701
5702                // Unbind all events (on this namespace, if provided) for the element
5703                if ( !type ) {
5704                    for ( type in events ) {
5705                        jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
5706                    }
5707                    continue;
5708                }
5709
5710                special = jQuery.event.special[ type ] || {};
5711                type = ( selector ? special.delegateType : special.bindType ) || type;
5712                handlers = events[ type ] || [];
5713                tmp = tmp[ 2 ] &&
5714                    new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" );
5715
5716                // Remove matching events
5717                origCount = j = handlers.length;
5718                while ( j-- ) {
5719                    handleObj = handlers[ j ];
5720
5721                    if ( ( mappedTypes || origType === handleObj.origType ) &&
5722                        ( !handler || handler.guid === handleObj.guid ) &&
5723                        ( !tmp || tmp.test( handleObj.namespace ) ) &&
5724                        ( !selector || selector === handleObj.selector ||
5725                            selector === "**" && handleObj.selector ) ) {
5726                        handlers.splice( j, 1 );
5727
5728                        if ( handleObj.selector ) {
5729                            handlers.delegateCount--;
5730                        }
5731                        if ( special.remove ) {
5732                            special.remove.call( elem, handleObj );
5733                        }
5734                    }
5735                }
5736
5737                // Remove generic event handler if we removed something and no more handlers exist
5738                // (avoids potential for endless recursion during removal of special event handlers)
5739                if ( origCount && !handlers.length ) {
5740                    if ( !special.teardown ||
5741                        special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
5742
5743                        jQuery.removeEvent( elem, type, elemData.handle );
5744                    }
5745
5746                    delete events[ type ];
5747                }
5748            }
5749
5750            // Remove data and the expando if it's no longer used
5751            if ( jQuery.isEmptyObject( events ) ) {
5752                dataPriv.remove( elem, "handle events" );
5753            }
5754        },
5755
5756        dispatch: function( nativeEvent ) {
5757
5758            var i, j, ret, matched, handleObj, handlerQueue,
5759                args = new Array( arguments.length ),
5760
5761                // Make a writable jQuery.Event from the native event object
5762                event = jQuery.event.fix( nativeEvent ),
5763
5764                handlers = (
5765                    dataPriv.get( this, "events" ) || Object.create( null )
5766                )[ event.type ] || [],
5767                special = jQuery.event.special[ event.type ] || {};
5768
5769            // Use the fix-ed jQuery.Event rather than the (read-only) native event
5770            args[ 0 ] = event;
5771
5772            for ( i = 1; i < arguments.length; i++ ) {
5773                args[ i ] = arguments[ i ];
5774            }
5775
5776            event.delegateTarget = this;
5777
5778            // Call the preDispatch hook for the mapped type, and let it bail if desired
5779            if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
5780                return;
5781            }
5782
5783            // Determine handlers
5784            handlerQueue = jQuery.event.handlers.call( this, event, handlers );
5785
5786            // Run delegates first; they may want to stop propagation beneath us
5787            i = 0;
5788            while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) {
5789                event.currentTarget = matched.elem;
5790
5791                j = 0;
5792                while ( ( handleObj = matched.handlers[ j++ ] ) &&
5793                !event.isImmediatePropagationStopped() ) {
5794
5795                    // If the event is namespaced, then each handler is only invoked if it is
5796                    // specially universal or its namespaces are a superset of the event's.
5797                    if ( !event.rnamespace || handleObj.namespace === false ||
vendor: 15,374 bytes, lines 5798-6184
5798                        event.rnamespace.test( handleObj.namespace ) ) {
5799
5800                        event.handleObj = handleObj;
5801                        event.data = handleObj.data;
5802
5803                        ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
5804                            handleObj.handler ).apply( matched.elem, args );
5805
5806                        if ( ret !== undefined ) {
5807                            if ( ( event.result = ret ) === false ) {
5808                                event.preventDefault();
5809                                event.stopPropagation();
5810                            }
5811                        }
5812                    }
5813                }
5814            }
5815
5816            // Call the postDispatch hook for the mapped type
5817            if ( special.postDispatch ) {
5818                special.postDispatch.call( this, event );
5819            }
5820
5821            return event.result;
5822        },
5823
5824        handlers: function( event, handlers ) {
5825            var i, handleObj, sel, matchedHandlers, matchedSelectors,
5826                handlerQueue = [],
5827                delegateCount = handlers.delegateCount,
5828                cur = event.target;
5829
5830            // Find delegate handlers
5831            if ( delegateCount &&
5832
5833                // Support: IE <=9
5834                // Black-hole SVG <use> instance trees (trac-13180)
5835                cur.nodeType &&
5836
5837                // Support: Firefox <=42
5838                // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861)
5839                // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click
5840                // Support: IE 11 only
5841                // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343)
5842                !( event.type === "click" && event.button >= 1 ) ) {
5843
5844                for ( ; cur !== this; cur = cur.parentNode || this ) {
5845
5846                    // Don't check non-elements (#13208)
5847                    // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
5848                    if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) {
5849                        matchedHandlers = [];
5850                        matchedSelectors = {};
5851                        for ( i = 0; i < delegateCount; i++ ) {
5852                            handleObj = handlers[ i ];
5853
5854                            // Don't conflict with Object.prototype properties (#13203)
5855                            sel = handleObj.selector + " ";
5856
5857                            if ( matchedSelectors[ sel ] === undefined ) {
5858                                matchedSelectors[ sel ] = handleObj.needsContext ?
5859                                    jQuery( sel, this ).index( cur ) > -1 :
5860                                    jQuery.find( sel, this, null, [ cur ] ).length;
5861                            }
5862                            if ( matchedSelectors[ sel ] ) {
5863                                matchedHandlers.push( handleObj );
5864                            }
5865                        }
5866                        if ( matchedHandlers.length ) {
5867                            handlerQueue.push( { elem: cur, handlers: matchedHandlers } );
5868                        }
5869                    }
5870                }
5871            }
5872
5873            // Add the remaining (directly-bound) handlers
5874            cur = this;
5875            if ( delegateCount < handlers.length ) {
5876                handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } );
5877            }
5878
5879            return handlerQueue;
5880        },
5881
5882        addProp: function( name, hook ) {
5883            Object.defineProperty( jQuery.Event.prototype, name, {
5884                enumerable: true,
5885                configurable: true,
5886
5887                get: isFunction( hook ) ?
5888                    function() {
5889                        if ( this.originalEvent ) {
5890                            return hook( this.originalEvent );
5891                        }
5892                    } :
5893                    function() {
5894                        if ( this.originalEvent ) {
5895                            return this.originalEvent[ name ];
5896                        }
5897                    },
5898
5899                set: function( value ) {
5900                    Object.defineProperty( this, name, {
5901                        enumerable: true,
5902                        configurable: true,
5903                        writable: true,
5904                        value: value
5905                    } );
5906                }
5907            } );
5908        },
5909
5910        fix: function( originalEvent ) {
5911            return originalEvent[ jQuery.expando ] ?
5912                originalEvent :
5913                new jQuery.Event( originalEvent );
5914        },
5915
5916        special: {
5917            load: {
5918
5919                // Prevent triggered image.load events from bubbling to window.load
5920                noBubble: true
5921            },
5922            click: {
5923
5924                // Utilize native event to ensure correct state for checkable inputs
5925                setup: function( data ) {
5926
5927                    // For mutual compressibility with _default, replace `this` access with a local var.
5928                    // `|| data` is dead code meant only to preserve the variable through minification.
5929                    var el = this || data;
5930
5931                    // Claim the first handler
5932                    if ( rcheckableType.test( el.type ) &&
5933                        el.click && nodeName( el, "input" ) ) {
5934
5935                        // dataPriv.set( el, "click", ... )
5936                        leverageNative( el, "click", returnTrue );
5937                    }
5938
5939                    // Return false to allow normal processing in the caller
5940                    return false;
5941                },
5942                trigger: function( data ) {
5943
5944                    // For mutual compressibility with _default, replace `this` access with a local var.
5945                    // `|| data` is dead code meant only to preserve the variable through minification.
5946                    var el = this || data;
5947
5948                    // Force setup before triggering a click
5949                    if ( rcheckableType.test( el.type ) &&
5950                        el.click && nodeName( el, "input" ) ) {
5951
5952                        leverageNative( el, "click" );
5953                    }
5954
5955                    // Return non-false to allow normal event-path propagation
5956                    return true;
5957                },
5958
5959                // For cross-browser consistency, suppress native .click() on links
5960                // Also prevent it if we're currently inside a leveraged native-event stack
5961                _default: function( event ) {
5962                    var target = event.target;
5963                    return rcheckableType.test( target.type ) &&
5964                        target.click && nodeName( target, "input" ) &&
5965                        dataPriv.get( target, "click" ) ||
5966                        nodeName( target, "a" );
5967                }
5968            },
5969
5970            beforeunload: {
5971                postDispatch: function( event ) {
5972
5973                    // Support: Firefox 20+
5974                    // Firefox doesn't alert if the returnValue field is not set.
5975                    if ( event.result !== undefined && event.originalEvent ) {
5976                        event.originalEvent.returnValue = event.result;
5977                    }
5978                }
5979            }
5980        }
5981    };
5982
5983// Ensure the presence of an event listener that handles manually-triggered
5984// synthetic events by interrupting progress until reinvoked in response to
5985// *native* events that it fires directly, ensuring that state changes have
5986// already occurred before other listeners are invoked.
5987    function leverageNative( el, type, expectSync ) {
5988
5989        // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add
5990        if ( !expectSync ) {
5991            if ( dataPriv.get( el, type ) === undefined ) {
5992                jQuery.event.add( el, type, returnTrue );
5993            }
5994            return;
5995        }
5996
5997        // Register the controller as a special universal handler for all event namespaces
5998        dataPriv.set( el, type, false );
5999        jQuery.event.add( el, type, {
6000            namespace: false,
6001            handler: function( event ) {
6002                var notAsync, result,
6003                    saved = dataPriv.get( this, type );
6004
6005                if ( ( event.isTrigger & 1 ) && this[ type ] ) {
6006
6007                    // Interrupt processing of the outer synthetic .trigger()ed event
6008                    // Saved data should be false in such cases, but might be a leftover capture object
6009                    // from an async native handler (gh-4350)
6010                    if ( !saved.length ) {
6011
6012                        // Store arguments for use when handling the inner native event
6013                        // There will always be at least one argument (an event object), so this array
6014                        // will not be confused with a leftover capture object.
6015                        saved = slice.call( arguments );
6016                        dataPriv.set( this, type, saved );
6017
6018                        // Trigger the native event and capture its result
6019                        // Support: IE <=9 - 11+
6020                        // focus() and blur() are asynchronous
6021                        notAsync = expectSync( this, type );
6022                        this[ type ]();
6023                        result = dataPriv.get( this, type );
6024                        if ( saved !== result || notAsync ) {
6025                            dataPriv.set( this, type, false );
6026                        } else {
6027                            result = {};
6028                        }
6029                        if ( saved !== result ) {
6030
6031                            // Cancel the outer synthetic event
6032                            event.stopImmediatePropagation();
6033                            event.preventDefault();
6034
6035                            // Support: Chrome 86+
6036                            // In Chrome, if an element having a focusout handler is blurred by
6037                            // clicking outside of it, it invokes the handler synchronously. If
6038                            // that handler calls `.remove()` on the element, the data is cleared,
6039                            // leaving `result` undefined. We need to guard against this.
6040                            return result && result.value;
6041                        }
6042
6043                        // If this is an inner synthetic event for an event with a bubbling surrogate
6044                        // (focus or blur), assume that the surrogate already propagated from triggering the
6045                        // native event and prevent that from happening again here.
6046                        // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the
6047                        // bubbling surrogate propagates *after* the non-bubbling base), but that seems
6048                        // less bad than duplication.
6049                    } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) {
6050                        event.stopPropagation();
6051                    }
6052
6053                    // If this is a native event triggered above, everything is now in order
6054                    // Fire an inner synthetic event with the original arguments
6055                } else if ( saved.length ) {
6056
6057                    // ...and capture the result
6058                    dataPriv.set( this, type, {
6059                        value: jQuery.event.trigger(
6060
6061                            // Support: IE <=9 - 11+
6062                            // Extend with the prototype to reset the above stopImmediatePropagation()
6063                            jQuery.extend( saved[ 0 ], jQuery.Event.prototype ),
6064                            saved.slice( 1 ),
6065                            this
6066                        )
6067                    } );
6068
6069                    // Abort handling of the native event
6070                    event.stopImmediatePropagation();
6071                }
6072            }
6073        } );
6074    }
6075
6076    jQuery.removeEvent = function( elem, type, handle ) {
6077
6078        // This "if" is needed for plain objects
6079        if ( elem.removeEventListener ) {
6080            elem.removeEventListener( type, handle );
6081        }
6082    };
6083
6084    jQuery.Event = function( src, props ) {
6085
6086        // Allow instantiation without the 'new' keyword
6087        if ( !( this instanceof jQuery.Event ) ) {
6088            return new jQuery.Event( src, props );
6089        }
6090
6091        // Event object
6092        if ( src && src.type ) {
6093            this.originalEvent = src;
6094            this.type = src.type;
6095
6096            // Events bubbling up the document may have been marked as prevented
6097            // by a handler lower down the tree; reflect the correct value.
6098            this.isDefaultPrevented = src.defaultPrevented ||
6099            src.defaultPrevented === undefined &&
6100
6101            // Support: Android <=2.3 only
6102            src.returnValue === false ?
6103                returnTrue :
6104                returnFalse;
6105
6106            // Create target properties
6107            // Support: Safari <=6 - 7 only
6108            // Target should not be a text node (#504, #13143)
6109            this.target = ( src.target && src.target.nodeType === 3 ) ?
6110                src.target.parentNode :
6111                src.target;
6112
6113            this.currentTarget = src.currentTarget;
6114            this.relatedTarget = src.relatedTarget;
6115
6116            // Event type
6117        } else {
6118            this.type = src;
6119        }
6120
6121        // Put explicitly provided properties onto the event object
6122        if ( props ) {
6123            jQuery.extend( this, props );
6124        }
6125
6126        // Create a timestamp if incoming event doesn't have one
6127        this.timeStamp = src && src.timeStamp || Date.now();
6128
6129        // Mark it as fixed
6130        this[ jQuery.expando ] = true;
6131    };
6132
6133// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
6134// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
6135    jQuery.Event.prototype = {
6136        constructor: jQuery.Event,
6137        isDefaultPrevented: returnFalse,
6138        isPropagationStopped: returnFalse,
6139        isImmediatePropagationStopped: returnFalse,
6140        isSimulated: false,
6141
6142        preventDefault: function() {
6143            var e = this.originalEvent;
6144
6145            this.isDefaultPrevented = returnTrue;
6146
6147            if ( e && !this.isSimulated ) {
6148                e.preventDefault();
6149            }
6150        },
6151        stopPropagation: function() {
6152            var e = this.originalEvent;
6153
6154            this.isPropagationStopped = returnTrue;
6155
6156            if ( e && !this.isSimulated ) {
6157                e.stopPropagation();
6158            }
6159        },
6160        stopImmediatePropagation: function() {
6161            var e = this.originalEvent;
6162
6163            this.isImmediatePropagationStopped = returnTrue;
6164
6165            if ( e && !this.isSimulated ) {
6166                e.stopImmediatePropagation();
6167            }
6168
6169            this.stopPropagation();
6170        }
6171    };
6172
6173// Includes all common event props including KeyEvent and MouseEvent specific props
6174    jQuery.each( {
6175        altKey: true,
6176        bubbles: true,
6177        cancelable: true,
6178        changedTouches: true,
6179        ctrlKey: true,
6180        detail: true,
6181        eventPhase: true,
6182        metaKey: true,
6183        pageX: true,
6184        pageY: true,
vendor: 4,565 bytes, lines 6185-6325
6185        shiftKey: true,
6186        view: true,
6187        "char": true,
6188        code: true,
6189        charCode: true,
6190        key: true,
6191        keyCode: true,
6192        button: true,
6193        buttons: true,
6194        clientX: true,
6195        clientY: true,
6196        offsetX: true,
6197        offsetY: true,
6198        pointerId: true,
6199        pointerType: true,
6200        screenX: true,
6201        screenY: true,
6202        targetTouches: true,
6203        toElement: true,
6204        touches: true,
6205        which: true
6206    }, jQuery.event.addProp );
6207
6208    jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) {
6209        jQuery.event.special[ type ] = {
6210
6211            // Utilize native event if possible so blur/focus sequence is correct
6212            setup: function() {
6213
6214                // Claim the first handler
6215                // dataPriv.set( this, "focus", ... )
6216                // dataPriv.set( this, "blur", ... )
6217                leverageNative( this, type, expectSync );
6218
6219                // Return false to allow normal processing in the caller
6220                return false;
6221            },
6222            trigger: function() {
6223
6224                // Force setup before trigger
6225                leverageNative( this, type );
6226
6227                // Return non-false to allow normal event-path propagation
6228                return true;
6229            },
6230
6231            // Suppress native focus or blur as it's already being fired
6232            // in leverageNative.
6233            _default: function() {
6234                return true;
6235            },
6236
6237            delegateType: delegateType
6238        };
6239    } );
6240
6241// Create mouseenter/leave events using mouseover/out and event-time checks
6242// so that event delegation works in jQuery.
6243// Do the same for pointerenter/pointerleave and pointerover/pointerout
6244//
6245// Support: Safari 7 only
6246// Safari sends mouseenter too often; see:
6247// https://bugs.chromium.org/p/chromium/issues/detail?id=470258
6248// for the description of the bug (it existed in older Chrome versions as well).
6249    jQuery.each( {
6250        mouseenter: "mouseover",
6251        mouseleave: "mouseout",
6252        pointerenter: "pointerover",
6253        pointerleave: "pointerout"
6254    }, function( orig, fix ) {
6255        jQuery.event.special[ orig ] = {
6256            delegateType: fix,
6257            bindType: fix,
6258
6259            handle: function( event ) {
6260                var ret,
6261                    target = this,
6262                    related = event.relatedTarget,
6263                    handleObj = event.handleObj;
6264
6265                // For mouseenter/leave call the handler if related is outside the target.
6266                // NB: No relatedTarget if the mouse left/entered the browser window
6267                if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) {
6268                    event.type = handleObj.origType;
6269                    ret = handleObj.handler.apply( this, arguments );
6270                    event.type = fix;
6271                }
6272                return ret;
6273            }
6274        };
6275    } );
6276
6277    jQuery.fn.extend( {
6278
6279        on: function( types, selector, data, fn ) {
6280            return on( this, types, selector, data, fn );
6281        },
6282        one: function( types, selector, data, fn ) {
6283            return on( this, types, selector, data, fn, 1 );
6284        },
6285        off: function( types, selector, fn ) {
6286            var handleObj, type;
6287            if ( types && types.preventDefault && types.handleObj ) {
6288
6289                // ( event )  dispatched jQuery.Event
6290                handleObj = types.handleObj;
6291                jQuery( types.delegateTarget ).off(
6292                    handleObj.namespace ?
6293                        handleObj.origType + "." + handleObj.namespace :
6294                        handleObj.origType,
6295                    handleObj.selector,
6296                    handleObj.handler
6297                );
6298                return this;
6299            }
6300            if ( typeof types === "object" ) {
6301
6302                // ( types-object [, selector] )
6303                for ( type in types ) {
6304                    this.off( type, selector, types[ type ] );
6305                }
6306                return this;
6307            }
6308            if ( selector === false || typeof selector === "function" ) {
6309
6310                // ( types [, fn] )
6311                fn = selector;
6312                selector = undefined;
6313            }
6314            if ( fn === false ) {
6315                fn = returnFalse;
6316            }
6317            return this.each( function() {
6318                jQuery.event.remove( this, types, fn, selector );
6319            } );
6320        }
6321    } );
6322
6323
6324    var
6325
vendor: 9,664 bytes, lines 6326-6586
6326        // Support: IE <=10 - 11, Edge 12 - 13 only
6327        // In IE/Edge using regex groups here causes severe slowdowns.
6328        // See https://connect.microsoft.com/IE/feedback/details/1736512/
6329        rnoInnerhtml = /<script|<style|<link/i,
6330
6331        // checked="checked" or checked
6332        rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
6333        rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;
6334
6335// Prefer a tbody over its parent table for containing new rows
6336    function manipulationTarget( elem, content ) {
6337        if ( nodeName( elem, "table" ) &&
6338            nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) {
6339
6340            return jQuery( elem ).children( "tbody" )[ 0 ] || elem;
6341        }
6342
6343        return elem;
6344    }
6345
6346// Replace/restore the type attribute of script elements for safe DOM manipulation
6347    function disableScript( elem ) {
6348        elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type;
6349        return elem;
6350    }
6351    function restoreScript( elem ) {
6352        if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) {
6353            elem.type = elem.type.slice( 5 );
6354        } else {
6355            elem.removeAttribute( "type" );
6356        }
6357
6358        return elem;
6359    }
6360
6361    function cloneCopyEvent( src, dest ) {
6362        var i, l, type, pdataOld, udataOld, udataCur, events;
6363
6364        if ( dest.nodeType !== 1 ) {
6365            return;
6366        }
6367
6368        // 1. Copy private data: events, handlers, etc.
6369        if ( dataPriv.hasData( src ) ) {
6370            pdataOld = dataPriv.get( src );
6371            events = pdataOld.events;
6372
6373            if ( events ) {
6374                dataPriv.remove( dest, "handle events" );
6375
6376                for ( type in events ) {
6377                    for ( i = 0, l = events[ type ].length; i < l; i++ ) {
6378                        jQuery.event.add( dest, type, events[ type ][ i ] );
6379                    }
6380                }
6381            }
6382        }
6383
6384        // 2. Copy user data
6385        if ( dataUser.hasData( src ) ) {
6386            udataOld = dataUser.access( src );
6387            udataCur = jQuery.extend( {}, udataOld );
6388
6389            dataUser.set( dest, udataCur );
6390        }
6391    }
6392
6393// Fix IE bugs, see support tests
6394    function fixInput( src, dest ) {
6395        var nodeName = dest.nodeName.toLowerCase();
6396
6397        // Fails to persist the checked state of a cloned checkbox or radio button.
6398        if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
6399            dest.checked = src.checked;
6400
6401            // Fails to return the selected option to the default selected state when cloning options
6402        } else if ( nodeName === "input" || nodeName === "textarea" ) {
6403            dest.defaultValue = src.defaultValue;
6404        }
6405    }
6406
6407    function domManip( collection, args, callback, ignored ) {
6408
6409        // Flatten any nested arrays
6410        args = flat( args );
6411
6412        var fragment, first, scripts, hasScripts, node, doc,
6413            i = 0,
6414            l = collection.length,
6415            iNoClone = l - 1,
6416            value = args[ 0 ],
6417            valueIsFunction = isFunction( value );
6418
6419        // We can't cloneNode fragments that contain checked, in WebKit
6420        if ( valueIsFunction ||
6421            ( l > 1 && typeof value === "string" &&
6422                !support.checkClone && rchecked.test( value ) ) ) {
6423            return collection.each( function( index ) {
6424                var self = collection.eq( index );
6425                if ( valueIsFunction ) {
6426                    args[ 0 ] = value.call( this, index, self.html() );
6427                }
6428                domManip( self, args, callback, ignored );
6429            } );
6430        }
6431
6432        if ( l ) {
6433            fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored );
6434            first = fragment.firstChild;
6435
6436            if ( fragment.childNodes.length === 1 ) {
6437                fragment = first;
6438            }
6439
6440            // Require either new content or an interest in ignored elements to invoke the callback
6441            if ( first || ignored ) {
6442                scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
6443                hasScripts = scripts.length;
6444
6445                // Use the original fragment for the last item
6446                // instead of the first because it can end up
6447                // being emptied incorrectly in certain situations (#8070).
6448                for ( ; i < l; i++ ) {
6449                    node = fragment;
6450
6451                    if ( i !== iNoClone ) {
6452                        node = jQuery.clone( node, true, true );
6453
6454                        // Keep references to cloned scripts for later restoration
6455                        if ( hasScripts ) {
6456
6457                            // Support: Android <=4.0 only, PhantomJS 1 only
6458                            // push.apply(_, arraylike) throws on ancient WebKit
6459                            jQuery.merge( scripts, getAll( node, "script" ) );
6460                        }
6461                    }
6462
6463                    callback.call( collection[ i ], node, i );
6464                }
6465
6466                if ( hasScripts ) {
6467                    doc = scripts[ scripts.length - 1 ].ownerDocument;
6468
6469                    // Reenable scripts
6470                    jQuery.map( scripts, restoreScript );
6471
6472                    // Evaluate executable scripts on first document insertion
6473                    for ( i = 0; i < hasScripts; i++ ) {
6474                        node = scripts[ i ];
6475                        if ( rscriptType.test( node.type || "" ) &&
6476                            !dataPriv.access( node, "globalEval" ) &&
6477                            jQuery.contains( doc, node ) ) {
6478
6479                            if ( node.src && ( node.type || "" ).toLowerCase()  !== "module" ) {
6480
6481                                // Optional AJAX dependency, but won't run scripts if not present
6482                                if ( jQuery._evalUrl && !node.noModule ) {
6483                                    jQuery._evalUrl( node.src, {
6484                                        nonce: node.nonce || node.getAttribute( "nonce" )
6485                                    }, doc );
6486                                }
6487                            } else {
6488                                DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc );
6489                            }
6490                        }
6491                    }
6492                }
6493            }
6494        }
6495
6496        return collection;
6497    }
6498
6499    function remove( elem, selector, keepData ) {
6500        var node,
6501            nodes = selector ? jQuery.filter( selector, elem ) : elem,
6502            i = 0;
6503
6504        for ( ; ( node = nodes[ i ] ) != null; i++ ) {
6505            if ( !keepData && node.nodeType === 1 ) {
6506                jQuery.cleanData( getAll( node ) );
6507            }
6508
6509            if ( node.parentNode ) {
6510                if ( keepData && isAttached( node ) ) {
6511                    setGlobalEval( getAll( node, "script" ) );
6512                }
6513                node.parentNode.removeChild( node );
6514            }
6515        }
6516
6517        return elem;
6518    }
6519
6520    jQuery.extend( {
6521        htmlPrefilter: function( html ) {
6522            return html;
6523        },
6524
6525        clone: function( elem, dataAndEvents, deepDataAndEvents ) {
6526            var i, l, srcElements, destElements,
6527                clone = elem.cloneNode( true ),
6528                inPage = isAttached( elem );
6529
6530            // Fix IE cloning issues
6531            if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
6532                !jQuery.isXMLDoc( elem ) ) {
6533
6534                // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2
6535                destElements = getAll( clone );
6536                srcElements = getAll( elem );
6537
6538                for ( i = 0, l = srcElements.length; i < l; i++ ) {
6539                    fixInput( srcElements[ i ], destElements[ i ] );
6540                }
6541            }
6542
6543            // Copy the events from the original to the clone
6544            if ( dataAndEvents ) {
6545                if ( deepDataAndEvents ) {
6546                    srcElements = srcElements || getAll( elem );
6547                    destElements = destElements || getAll( clone );
6548
6549                    for ( i = 0, l = srcElements.length; i < l; i++ ) {
6550                        cloneCopyEvent( srcElements[ i ], destElements[ i ] );
6551                    }
6552                } else {
6553                    cloneCopyEvent( elem, clone );
6554                }
6555            }
6556
6557            // Preserve script evaluation history
6558            destElements = getAll( clone, "script" );
6559            if ( destElements.length > 0 ) {
6560                setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
6561            }
6562
6563            // Return the cloned set
6564            return clone;
6565        },
6566
6567        cleanData: function( elems ) {
6568            var data, elem, type,
6569                special = jQuery.event.special,
6570                i = 0;
6571
6572            for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) {
6573                if ( acceptData( elem ) ) {
6574                    if ( ( data = elem[ dataPriv.expando ] ) ) {
6575                        if ( data.events ) {
6576                            for ( type in data.events ) {
6577                                if ( special[ type ] ) {
6578                                    jQuery.event.remove( elem, type );
6579
6580                                    // This is a shortcut to avoid jQuery.event.remove's overhead
6581                                } else {
6582                                    jQuery.removeEvent( elem, type, data.handle );
6583                                }
6584                            }
6585                        }
6586
vendor: 5,407 bytes, lines 6587-6743
6587                        // Support: Chrome <=35 - 45+
6588                        // Assign undefined instead of using delete, see Data#remove
6589                        elem[ dataPriv.expando ] = undefined;
6590                    }
6591                    if ( elem[ dataUser.expando ] ) {
6592
6593                        // Support: Chrome <=35 - 45+
6594                        // Assign undefined instead of using delete, see Data#remove
6595                        elem[ dataUser.expando ] = undefined;
6596                    }
6597                }
6598            }
6599        }
6600    } );
6601
6602    jQuery.fn.extend( {
6603        detach: function( selector ) {
6604            return remove( this, selector, true );
6605        },
6606
6607        remove: function( selector ) {
6608            return remove( this, selector );
6609        },
6610
6611        text: function( value ) {
6612            return access( this, function( value ) {
6613                return value === undefined ?
6614                    jQuery.text( this ) :
6615                    this.empty().each( function() {
6616                        if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
6617                            this.textContent = value;
6618                        }
6619                    } );
6620            }, null, value, arguments.length );
6621        },
6622
6623        append: function() {
6624            return domManip( this, arguments, function( elem ) {
6625                if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
6626                    var target = manipulationTarget( this, elem );
6627                    target.appendChild( elem );
6628                }
6629            } );
6630        },
6631
6632        prepend: function() {
6633            return domManip( this, arguments, function( elem ) {
6634                if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
6635                    var target = manipulationTarget( this, elem );
6636                    target.insertBefore( elem, target.firstChild );
6637                }
6638            } );
6639        },
6640
6641        before: function() {
6642            return domManip( this, arguments, function( elem ) {
6643                if ( this.parentNode ) {
6644                    this.parentNode.insertBefore( elem, this );
6645                }
6646            } );
6647        },
6648
6649        after: function() {
6650            return domManip( this, arguments, function( elem ) {
6651                if ( this.parentNode ) {
6652                    this.parentNode.insertBefore( elem, this.nextSibling );
6653                }
6654            } );
6655        },
6656
6657        empty: function() {
6658            var elem,
6659                i = 0;
6660
6661            for ( ; ( elem = this[ i ] ) != null; i++ ) {
6662                if ( elem.nodeType === 1 ) {
6663
6664                    // Prevent memory leaks
6665                    jQuery.cleanData( getAll( elem, false ) );
6666
6667                    // Remove any remaining nodes
6668                    elem.textContent = "";
6669                }
6670            }
6671
6672            return this;
6673        },
6674
6675        clone: function( dataAndEvents, deepDataAndEvents ) {
6676            dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
6677            deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
6678
6679            return this.map( function() {
6680                return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
6681            } );
6682        },
6683
6684        html: function( value ) {
6685            return access( this, function( value ) {
6686                var elem = this[ 0 ] || {},
6687                    i = 0,
6688                    l = this.length;
6689
6690                if ( value === undefined && elem.nodeType === 1 ) {
6691                    return elem.innerHTML;
6692                }
6693
6694                // See if we can take a shortcut and just use innerHTML
6695                if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
6696                    !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
6697
6698                    value = jQuery.htmlPrefilter( value );
6699
6700                    try {
6701                        for ( ; i < l; i++ ) {
6702                            elem = this[ i ] || {};
6703
6704                            // Remove element nodes and prevent memory leaks
6705                            if ( elem.nodeType === 1 ) {
6706                                jQuery.cleanData( getAll( elem, false ) );
6707                                elem.innerHTML = value;
6708                            }
6709                        }
6710
6711                        elem = 0;
6712
6713                        // If using innerHTML throws an exception, use the fallback method
6714                    } catch ( e ) {}
6715                }
6716
6717                if ( elem ) {
6718                    this.empty().append( value );
6719                }
6720            }, null, value, arguments.length );
6721        },
6722
6723        replaceWith: function() {
6724            var ignored = [];
6725
6726            // Make the changes, replacing each non-ignored context element with the new content
6727            return domManip( this, arguments, function( elem ) {
6728                var parent = this.parentNode;
6729
6730                if ( jQuery.inArray( this, ignored ) < 0 ) {
6731                    jQuery.cleanData( getAll( this ) );
6732                    if ( parent ) {
6733                        parent.replaceChild( elem, this );
6734                    }
6735                }
6736
6737                // Force callback invocation
6738            }, ignored );
6739        }
6740    } );
6741
6742    jQuery.each( {
6743        appendTo: "append",
vendor: 15,461 bytes, lines 6744-7163
6744        prependTo: "prepend",
6745        insertBefore: "before",
6746        insertAfter: "after",
6747        replaceAll: "replaceWith"
6748    }, function( name, original ) {
6749        jQuery.fn[ name ] = function( selector ) {
6750            var elems,
6751                ret = [],
6752                insert = jQuery( selector ),
6753                last = insert.length - 1,
6754                i = 0;
6755
6756            for ( ; i <= last; i++ ) {
6757                elems = i === last ? this : this.clone( true );
6758                jQuery( insert[ i ] )[ original ]( elems );
6759
6760                // Support: Android <=4.0 only, PhantomJS 1 only
6761                // .get() because push.apply(_, arraylike) throws on ancient WebKit
6762                push.apply( ret, elems.get() );
6763            }
6764
6765            return this.pushStack( ret );
6766        };
6767    } );
6768    var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
6769
6770    var getStyles = function( elem ) {
6771
6772        // Support: IE <=11 only, Firefox <=30 (#15098, #14150)
6773        // IE throws on elements created in popups
6774        // FF meanwhile throws on frame elements through "defaultView.getComputedStyle"
6775        var view = elem.ownerDocument.defaultView;
6776
6777        if ( !view || !view.opener ) {
6778            view = window;
6779        }
6780
6781        return view.getComputedStyle( elem );
6782    };
6783
6784    var swap = function( elem, options, callback ) {
6785        var ret, name,
6786            old = {};
6787
6788        // Remember the old values, and insert the new ones
6789        for ( name in options ) {
6790            old[ name ] = elem.style[ name ];
6791            elem.style[ name ] = options[ name ];
6792        }
6793
6794        ret = callback.call( elem );
6795
6796        // Revert the old values
6797        for ( name in options ) {
6798            elem.style[ name ] = old[ name ];
6799        }
6800
6801        return ret;
6802    };
6803
6804
6805    var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" );
6806
6807
6808
6809    ( function() {
6810
6811        // Executing both pixelPosition & boxSizingReliable tests require only one layout
6812        // so they're executed at the same time to save the second computation.
6813        function computeStyleTests() {
6814
6815            // This is a singleton, we need to execute it only once
6816            if ( !div ) {
6817                return;
6818            }
6819
6820            container.style.cssText = "position:absolute;left:-11111px;width:60px;" +
6821                "margin-top:1px;padding:0;border:0";
6822            div.style.cssText =
6823                "position:relative;display:block;box-sizing:border-box;overflow:scroll;" +
6824                "margin:auto;border:1px;padding:1px;" +
6825                "width:60%;top:1%";
6826            documentElement.appendChild( container ).appendChild( div );
6827
6828            var divStyle = window.getComputedStyle( div );
6829            pixelPositionVal = divStyle.top !== "1%";
6830
6831            // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44
6832            reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12;
6833
6834            // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3
6835            // Some styles come back with percentage values, even though they shouldn't
6836            div.style.right = "60%";
6837            pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36;
6838
6839            // Support: IE 9 - 11 only
6840            // Detect misreporting of content dimensions for box-sizing:border-box elements
6841            boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36;
6842
6843            // Support: IE 9 only
6844            // Detect overflow:scroll screwiness (gh-3699)
6845            // Support: Chrome <=64
6846            // Don't get tricked when zoom affects offsetWidth (gh-4029)
6847            div.style.position = "absolute";
6848            scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12;
6849
6850            documentElement.removeChild( container );
6851
6852            // Nullify the div so it wouldn't be stored in the memory and
6853            // it will also be a sign that checks already performed
6854            div = null;
6855        }
6856
6857        function roundPixelMeasures( measure ) {
6858            return Math.round( parseFloat( measure ) );
6859        }
6860
6861        var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal,
6862            reliableTrDimensionsVal, reliableMarginLeftVal,
6863            container = document.createElement( "div" ),
6864            div = document.createElement( "div" );
6865
6866        // Finish early in limited (non-browser) environments
6867        if ( !div.style ) {
6868            return;
6869        }
6870
6871        // Support: IE <=9 - 11 only
6872        // Style of cloned element affects source element cloned (#8908)
6873        div.style.backgroundClip = "content-box";
6874        div.cloneNode( true ).style.backgroundClip = "";
6875        support.clearCloneStyle = div.style.backgroundClip === "content-box";
6876
6877        jQuery.extend( support, {
6878            boxSizingReliable: function() {
6879                computeStyleTests();
6880                return boxSizingReliableVal;
6881            },
6882            pixelBoxStyles: function() {
6883                computeStyleTests();
6884                return pixelBoxStylesVal;
6885            },
6886            pixelPosition: function() {
6887                computeStyleTests();
6888                return pixelPositionVal;
6889            },
6890            reliableMarginLeft: function() {
6891                computeStyleTests();
6892                return reliableMarginLeftVal;
6893            },
6894            scrollboxSize: function() {
6895                computeStyleTests();
6896                return scrollboxSizeVal;
6897            },
6898
6899            // Support: IE 9 - 11+, Edge 15 - 18+
6900            // IE/Edge misreport `getComputedStyle` of table rows with width/height
6901            // set in CSS while `offset*` properties report correct values.
6902            // Behavior in IE 9 is more subtle than in newer versions & it passes
6903            // some versions of this test; make sure not to make it pass there!
6904            //
6905            // Support: Firefox 70+
6906            // Only Firefox includes border widths
6907            // in computed dimensions. (gh-4529)
6908            reliableTrDimensions: function() {
6909                var table, tr, trChild, trStyle;
6910                if ( reliableTrDimensionsVal == null ) {
6911                    table = document.createElement( "table" );
6912                    tr = document.createElement( "tr" );
6913                    trChild = document.createElement( "div" );
6914
6915                    table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate";
6916                    tr.style.cssText = "border:1px solid";
6917
6918                    // Support: Chrome 86+
6919                    // Height set through cssText does not get applied.
6920                    // Computed height then comes back as 0.
6921                    tr.style.height = "1px";
6922                    trChild.style.height = "9px";
6923
6924                    // Support: Android 8 Chrome 86+
6925                    // In our bodyBackground.html iframe,
6926                    // display for all div elements is set to "inline",
6927                    // which causes a problem only in Android 8 Chrome 86.
6928                    // Ensuring the div is display: block
6929                    // gets around this issue.
6930                    trChild.style.display = "block";
6931
6932                    documentElement
6933                        .appendChild( table )
6934                        .appendChild( tr )
6935                        .appendChild( trChild );
6936
6937                    trStyle = window.getComputedStyle( tr );
6938                    reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) +
6939                        parseInt( trStyle.borderTopWidth, 10 ) +
6940                        parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight;
6941
6942                    documentElement.removeChild( table );
6943                }
6944                return reliableTrDimensionsVal;
6945            }
6946        } );
6947    } )();
6948
6949
6950    function curCSS( elem, name, computed ) {
6951        var width, minWidth, maxWidth, ret,
6952
6953            // Support: Firefox 51+
6954            // Retrieving style before computed somehow
6955            // fixes an issue with getting wrong values
6956            // on detached elements
6957            style = elem.style;
6958
6959        computed = computed || getStyles( elem );
6960
6961        // getPropertyValue is needed for:
6962        //   .css('filter') (IE 9 only, #12537)
6963        //   .css('--customProperty) (#3144)
6964        if ( computed ) {
6965            ret = computed.getPropertyValue( name ) || computed[ name ];
6966
6967            if ( ret === "" && !isAttached( elem ) ) {
6968                ret = jQuery.style( elem, name );
6969            }
6970
6971            // A tribute to the "awesome hack by Dean Edwards"
6972            // Android Browser returns percentage for some values,
6973            // but width seems to be reliably pixels.
6974            // This is against the CSSOM draft spec:
6975            // https://drafts.csswg.org/cssom/#resolved-values
6976            if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) {
6977
6978                // Remember the original values
6979                width = style.width;
6980                minWidth = style.minWidth;
6981                maxWidth = style.maxWidth;
6982
6983                // Put in the new values to get a computed value out
6984                style.minWidth = style.maxWidth = style.width = ret;
6985                ret = computed.width;
6986
6987                // Revert the changed values
6988                style.width = width;
6989                style.minWidth = minWidth;
6990                style.maxWidth = maxWidth;
6991            }
6992        }
6993
6994        return ret !== undefined ?
6995
6996            // Support: IE <=9 - 11 only
6997            // IE returns zIndex value as an integer.
6998            ret + "" :
6999            ret;
7000    }
7001
7002
7003    function addGetHookIf( conditionFn, hookFn ) {
7004
7005        // Define the hook, we'll check on the first run if it's really needed.
7006        return {
7007            get: function() {
7008                if ( conditionFn() ) {
7009
7010                    // Hook not needed (or it's not possible to use it due
7011                    // to missing dependency), remove it.
7012                    delete this.get;
7013                    return;
7014                }
7015
7016                // Hook needed; redefine it so that the support test is not executed again.
7017                return ( this.get = hookFn ).apply( this, arguments );
7018            }
7019        };
7020    }
7021
7022
7023    var cssPrefixes = [ "Webkit", "Moz", "ms" ],
7024        emptyStyle = document.createElement( "div" ).style,
7025        vendorProps = {};
7026
7027// Return a vendor-prefixed property or undefined
7028    function vendorPropName( name ) {
7029
7030        // Check for vendor prefixed names
7031        var capName = name[ 0 ].toUpperCase() + name.slice( 1 ),
7032            i = cssPrefixes.length;
7033
7034        while ( i-- ) {
7035            name = cssPrefixes[ i ] + capName;
7036            if ( name in emptyStyle ) {
7037                return name;
7038            }
7039        }
7040    }
7041
7042// Return a potentially-mapped jQuery.cssProps or vendor prefixed property
7043    function finalPropName( name ) {
7044        var final = jQuery.cssProps[ name ] || vendorProps[ name ];
7045
7046        if ( final ) {
7047            return final;
7048        }
7049        if ( name in emptyStyle ) {
7050            return name;
7051        }
7052        return vendorProps[ name ] = vendorPropName( name ) || name;
7053    }
7054
7055
7056    var
7057
7058        // Swappable if display is none or starts with table
7059        // except "table", "table-cell", or "table-caption"
7060        // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
7061        rdisplayswap = /^(none|table(?!-c[ea]).+)/,
7062        rcustomProp = /^--/,
7063        cssShow = { position: "absolute", visibility: "hidden", display: "block" },
7064        cssNormalTransform = {
7065            letterSpacing: "0",
7066            fontWeight: "400"
7067        };
7068
7069    function setPositiveNumber( _elem, value, subtract ) {
7070
7071        // Any relative (+/-) values have already been
7072        // normalized at this point
7073        var matches = rcssNum.exec( value );
7074        return matches ?
7075
7076            // Guard against undefined "subtract", e.g., when used as in cssHooks
7077            Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) :
7078            value;
7079    }
7080
7081    function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) {
7082        var i = dimension === "width" ? 1 : 0,
7083            extra = 0,
7084            delta = 0;
7085
7086        // Adjustment may not be necessary
7087        if ( box === ( isBorderBox ? "border" : "content" ) ) {
7088            return 0;
7089        }
7090
7091        for ( ; i < 4; i += 2 ) {
7092
7093            // Both box models exclude margin
7094            if ( box === "margin" ) {
7095                delta += jQuery.css( elem, box + cssExpand[ i ], true, styles );
7096            }
7097
7098            // If we get here with a content-box, we're seeking "padding" or "border" or "margin"
7099            if ( !isBorderBox ) {
7100
7101                // Add padding
7102                delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
7103
7104                // For "border" or "margin", add border
7105                if ( box !== "padding" ) {
7106                    delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
7107
7108                    // But still keep track of it otherwise
7109                } else {
7110                    extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
7111                }
7112
7113                // If we get here with a border-box (content + padding + border), we're seeking "content" or
7114                // "padding" or "margin"
7115            } else {
7116
7117                // For "content", subtract padding
7118                if ( box === "content" ) {
7119                    delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
7120                }
7121
7122                // For "content" or "padding", subtract border
7123                if ( box !== "margin" ) {
7124                    delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
7125                }
7126            }
7127        }
7128
7129        // Account for positive content-box scroll gutter when requested by providing computedVal
7130        if ( !isBorderBox && computedVal >= 0 ) {
7131
7132            // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border
7133            // Assuming integer scroll gutter, subtract the rest and round down
7134            delta += Math.max( 0, Math.ceil(
7135                elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
7136                computedVal -
7137                delta -
7138                extra -
7139                0.5
7140
7141                // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter
7142                // Use an explicit zero to avoid NaN (gh-3964)
7143            ) ) || 0;
7144        }
7145
7146        return delta;
7147    }
7148
7149    function getWidthOrHeight( elem, dimension, extra ) {
7150
7151        // Start with computed style
7152        var styles = getStyles( elem ),
7153
7154            // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322).
7155            // Fake content-box until we know it's needed to know the true value.
7156            boxSizingNeeded = !support.boxSizingReliable() || extra,
7157            isBorderBox = boxSizingNeeded &&
7158                jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
7159            valueIsBorderBox = isBorderBox,
7160
7161            val = curCSS( elem, dimension, styles ),
7162            offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 );
7163
vendor: 6,163 bytes, lines 7164-7323
7164        // Support: Firefox <=54
7165        // Return a confounding non-pixel value or feign ignorance, as appropriate.
7166        if ( rnumnonpx.test( val ) ) {
7167            if ( !extra ) {
7168                return val;
7169            }
7170            val = "auto";
7171        }
7172
7173
7174        // Support: IE 9 - 11 only
7175        // Use offsetWidth/offsetHeight for when box sizing is unreliable.
7176        // In those cases, the computed value can be trusted to be border-box.
7177        if ( ( !support.boxSizingReliable() && isBorderBox ||
7178
7179            // Support: IE 10 - 11+, Edge 15 - 18+
7180            // IE/Edge misreport `getComputedStyle` of table rows with width/height
7181            // set in CSS while `offset*` properties report correct values.
7182            // Interestingly, in some cases IE 9 doesn't suffer from this issue.
7183            !support.reliableTrDimensions() && nodeName( elem, "tr" ) ||
7184
7185            // Fall back to offsetWidth/offsetHeight when value is "auto"
7186            // This happens for inline elements with no explicit setting (gh-3571)
7187            val === "auto" ||
7188
7189            // Support: Android <=4.1 - 4.3 only
7190            // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602)
7191            !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) &&
7192
7193            // Make sure the element is visible & connected
7194            elem.getClientRects().length ) {
7195
7196            isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
7197
7198            // Where available, offsetWidth/offsetHeight approximate border box dimensions.
7199            // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the
7200            // retrieved value as a content box dimension.
7201            valueIsBorderBox = offsetProp in elem;
7202            if ( valueIsBorderBox ) {
7203                val = elem[ offsetProp ];
7204            }
7205        }
7206
7207        // Normalize "" and auto
7208        val = parseFloat( val ) || 0;
7209
7210        // Adjust for the element's box model
7211        return ( val +
7212            boxModelAdjustment(
7213                elem,
7214                dimension,
7215                extra || ( isBorderBox ? "border" : "content" ),
7216                valueIsBorderBox,
7217                styles,
7218
7219                // Provide the current computed size to request scroll gutter calculation (gh-3589)
7220                val
7221            )
7222        ) + "px";
7223    }
7224
7225    jQuery.extend( {
7226
7227        // Add in style property hooks for overriding the default
7228        // behavior of getting and setting a style property
7229        cssHooks: {
7230            opacity: {
7231                get: function( elem, computed ) {
7232                    if ( computed ) {
7233
7234                        // We should always get a number back from opacity
7235                        var ret = curCSS( elem, "opacity" );
7236                        return ret === "" ? "1" : ret;
7237                    }
7238                }
7239            }
7240        },
7241
7242        // Don't automatically add "px" to these possibly-unitless properties
7243        cssNumber: {
7244            "animationIterationCount": true,
7245            "columnCount": true,
7246            "fillOpacity": true,
7247            "flexGrow": true,
7248            "flexShrink": true,
7249            "fontWeight": true,
7250            "gridArea": true,
7251            "gridColumn": true,
7252            "gridColumnEnd": true,
7253            "gridColumnStart": true,
7254            "gridRow": true,
7255            "gridRowEnd": true,
7256            "gridRowStart": true,
7257            "lineHeight": true,
7258            "opacity": true,
7259            "order": true,
7260            "orphans": true,
7261            "widows": true,
7262            "zIndex": true,
7263            "zoom": true
7264        },
7265
7266        // Add in properties whose names you wish to fix before
7267        // setting or getting the value
7268        cssProps: {},
7269
7270        // Get and set the style property on a DOM Node
7271        style: function( elem, name, value, extra ) {
7272
7273            // Don't set styles on text and comment nodes
7274            if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
7275                return;
7276            }
7277
7278            // Make sure that we're working with the right name
7279            var ret, type, hooks,
7280                origName = camelCase( name ),
7281                isCustomProp = rcustomProp.test( name ),
7282                style = elem.style;
7283
7284            // Make sure that we're working with the right name. We don't
7285            // want to query the value if it is a CSS custom property
7286            // since they are user-defined.
7287            if ( !isCustomProp ) {
7288                name = finalPropName( origName );
7289            }
7290
7291            // Gets hook for the prefixed version, then unprefixed version
7292            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
7293
7294            // Check if we're setting a value
7295            if ( value !== undefined ) {
7296                type = typeof value;
7297
7298                // Convert "+=" or "-=" to relative numbers (#7345)
7299                if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) {
7300                    value = adjustCSS( elem, name, ret );
7301
7302                    // Fixes bug #9237
7303                    type = "number";
7304                }
7305
7306                // Make sure that null and NaN values aren't set (#7116)
7307                if ( value == null || value !== value ) {
7308                    return;
7309                }
7310
7311                // If a number was passed in, add the unit (except for certain CSS properties)
7312                // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append
7313                // "px" to a few hardcoded values.
7314                if ( type === "number" && !isCustomProp ) {
7315                    value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" );
7316                }
7317
7318                // background-* props affect original clone's values
7319                if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
7320                    style[ name ] = "inherit";
7321                }
7322
7323                // If a hook was provided, use that value, otherwise just set the specified value
vendor: 15,960 bytes, lines 7324-7768
7324                if ( !hooks || !( "set" in hooks ) ||
7325                    ( value = hooks.set( elem, value, extra ) ) !== undefined ) {
7326
7327                    if ( isCustomProp ) {
7328                        style.setProperty( name, value );
7329                    } else {
7330                        style[ name ] = value;
7331                    }
7332                }
7333
7334            } else {
7335
7336                // If a hook was provided get the non-computed value from there
7337                if ( hooks && "get" in hooks &&
7338                    ( ret = hooks.get( elem, false, extra ) ) !== undefined ) {
7339
7340                    return ret;
7341                }
7342
7343                // Otherwise just get the value from the style object
7344                return style[ name ];
7345            }
7346        },
7347
7348        css: function( elem, name, extra, styles ) {
7349            var val, num, hooks,
7350                origName = camelCase( name ),
7351                isCustomProp = rcustomProp.test( name );
7352
7353            // Make sure that we're working with the right name. We don't
7354            // want to modify the value if it is a CSS custom property
7355            // since they are user-defined.
7356            if ( !isCustomProp ) {
7357                name = finalPropName( origName );
7358            }
7359
7360            // Try prefixed name followed by the unprefixed name
7361            hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
7362
7363            // If a hook was provided get the computed value from there
7364            if ( hooks && "get" in hooks ) {
7365                val = hooks.get( elem, true, extra );
7366            }
7367
7368            // Otherwise, if a way to get the computed value exists, use that
7369            if ( val === undefined ) {
7370                val = curCSS( elem, name, styles );
7371            }
7372
7373            // Convert "normal" to computed value
7374            if ( val === "normal" && name in cssNormalTransform ) {
7375                val = cssNormalTransform[ name ];
7376            }
7377
7378            // Make numeric if forced or a qualifier was provided and val looks numeric
7379            if ( extra === "" || extra ) {
7380                num = parseFloat( val );
7381                return extra === true || isFinite( num ) ? num || 0 : val;
7382            }
7383
7384            return val;
7385        }
7386    } );
7387
7388    jQuery.each( [ "height", "width" ], function( _i, dimension ) {
7389        jQuery.cssHooks[ dimension ] = {
7390            get: function( elem, computed, extra ) {
7391                if ( computed ) {
7392
7393                    // Certain elements can have dimension info if we invisibly show them
7394                    // but it must have a current display style that would benefit
7395                    return rdisplayswap.test( jQuery.css( elem, "display" ) ) &&
7396
7397                    // Support: Safari 8+
7398                    // Table columns in Safari have non-zero offsetWidth & zero
7399                    // getBoundingClientRect().width unless display is changed.
7400                    // Support: IE <=11 only
7401                    // Running getBoundingClientRect on a disconnected node
7402                    // in IE throws an error.
7403                    ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ?
7404                        swap( elem, cssShow, function() {
7405                            return getWidthOrHeight( elem, dimension, extra );
7406                        } ) :
7407                        getWidthOrHeight( elem, dimension, extra );
7408                }
7409            },
7410
7411            set: function( elem, value, extra ) {
7412                var matches,
7413                    styles = getStyles( elem ),
7414
7415                    // Only read styles.position if the test has a chance to fail
7416                    // to avoid forcing a reflow.
7417                    scrollboxSizeBuggy = !support.scrollboxSize() &&
7418                        styles.position === "absolute",
7419
7420                    // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991)
7421                    boxSizingNeeded = scrollboxSizeBuggy || extra,
7422                    isBorderBox = boxSizingNeeded &&
7423                        jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
7424                    subtract = extra ?
7425                        boxModelAdjustment(
7426                            elem,
7427                            dimension,
7428                            extra,
7429                            isBorderBox,
7430                            styles
7431                        ) :
7432                        0;
7433
7434                // Account for unreliable border-box dimensions by comparing offset* to computed and
7435                // faking a content-box to get border and padding (gh-3699)
7436                if ( isBorderBox && scrollboxSizeBuggy ) {
7437                    subtract -= Math.ceil(
7438                        elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] -
7439                        parseFloat( styles[ dimension ] ) -
7440                        boxModelAdjustment( elem, dimension, "border", false, styles ) -
7441                        0.5
7442                    );
7443                }
7444
7445                // Convert to pixels if value adjustment is needed
7446                if ( subtract && ( matches = rcssNum.exec( value ) ) &&
7447                    ( matches[ 3 ] || "px" ) !== "px" ) {
7448
7449                    elem.style[ dimension ] = value;
7450                    value = jQuery.css( elem, dimension );
7451                }
7452
7453                return setPositiveNumber( elem, value, subtract );
7454            }
7455        };
7456    } );
7457
7458    jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft,
7459        function( elem, computed ) {
7460            if ( computed ) {
7461                return ( parseFloat( curCSS( elem, "marginLeft" ) ) ||
7462                    elem.getBoundingClientRect().left -
7463                    swap( elem, { marginLeft: 0 }, function() {
7464                        return elem.getBoundingClientRect().left;
7465                    } )
7466                ) + "px";
7467            }
7468        }
7469    );
7470
7471// These hooks are used by animate to expand properties
7472    jQuery.each( {
7473        margin: "",
7474        padding: "",
7475        border: "Width"
7476    }, function( prefix, suffix ) {
7477        jQuery.cssHooks[ prefix + suffix ] = {
7478            expand: function( value ) {
7479                var i = 0,
7480                    expanded = {},
7481
7482                    // Assumes a single number if not a string
7483                    parts = typeof value === "string" ? value.split( " " ) : [ value ];
7484
7485                for ( ; i < 4; i++ ) {
7486                    expanded[ prefix + cssExpand[ i ] + suffix ] =
7487                        parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
7488                }
7489
7490                return expanded;
7491            }
7492        };
7493
7494        if ( prefix !== "margin" ) {
7495            jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
7496        }
7497    } );
7498
7499    jQuery.fn.extend( {
7500        css: function( name, value ) {
7501            return access( this, function( elem, name, value ) {
7502                var styles, len,
7503                    map = {},
7504                    i = 0;
7505
7506                if ( Array.isArray( name ) ) {
7507                    styles = getStyles( elem );
7508                    len = name.length;
7509
7510                    for ( ; i < len; i++ ) {
7511                        map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
7512                    }
7513
7514                    return map;
7515                }
7516
7517                return value !== undefined ?
7518                    jQuery.style( elem, name, value ) :
7519                    jQuery.css( elem, name );
7520            }, name, value, arguments.length > 1 );
7521        }
7522    } );
7523
7524
7525    function Tween( elem, options, prop, end, easing ) {
7526        return new Tween.prototype.init( elem, options, prop, end, easing );
7527    }
7528    jQuery.Tween = Tween;
7529
7530    Tween.prototype = {
7531        constructor: Tween,
7532        init: function( elem, options, prop, end, easing, unit ) {
7533            this.elem = elem;
7534            this.prop = prop;
7535            this.easing = easing || jQuery.easing._default;
7536            this.options = options;
7537            this.start = this.now = this.cur();
7538            this.end = end;
7539            this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
7540        },
7541        cur: function() {
7542            var hooks = Tween.propHooks[ this.prop ];
7543
7544            return hooks && hooks.get ?
7545                hooks.get( this ) :
7546                Tween.propHooks._default.get( this );
7547        },
7548        run: function( percent ) {
7549            var eased,
7550                hooks = Tween.propHooks[ this.prop ];
7551
7552            if ( this.options.duration ) {
7553                this.pos = eased = jQuery.easing[ this.easing ](
7554                    percent, this.options.duration * percent, 0, 1, this.options.duration
7555                );
7556            } else {
7557                this.pos = eased = percent;
7558            }
7559            this.now = ( this.end - this.start ) * eased + this.start;
7560
7561            if ( this.options.step ) {
7562                this.options.step.call( this.elem, this.now, this );
7563            }
7564
7565            if ( hooks && hooks.set ) {
7566                hooks.set( this );
7567            } else {
7568                Tween.propHooks._default.set( this );
7569            }
7570            return this;
7571        }
7572    };
7573
7574    Tween.prototype.init.prototype = Tween.prototype;
7575
7576    Tween.propHooks = {
7577        _default: {
7578            get: function( tween ) {
7579                var result;
7580
7581                // Use a property on the element directly when it is not a DOM element,
7582                // or when there is no matching style property that exists.
7583                if ( tween.elem.nodeType !== 1 ||
7584                    tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) {
7585                    return tween.elem[ tween.prop ];
7586                }
7587
7588                // Passing an empty string as a 3rd parameter to .css will automatically
7589                // attempt a parseFloat and fallback to a string if the parse fails.
7590                // Simple values such as "10px" are parsed to Float;
7591                // complex values such as "rotate(1rad)" are returned as-is.
7592                result = jQuery.css( tween.elem, tween.prop, "" );
7593
7594                // Empty strings, null, undefined and "auto" are converted to 0.
7595                return !result || result === "auto" ? 0 : result;
7596            },
7597            set: function( tween ) {
7598
7599                // Use step hook for back compat.
7600                // Use cssHook if its there.
7601                // Use .style if available and use plain properties where available.
7602                if ( jQuery.fx.step[ tween.prop ] ) {
7603                    jQuery.fx.step[ tween.prop ]( tween );
7604                } else if ( tween.elem.nodeType === 1 && (
7605                    jQuery.cssHooks[ tween.prop ] ||
7606                    tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) {
7607                    jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
7608                } else {
7609                    tween.elem[ tween.prop ] = tween.now;
7610                }
7611            }
7612        }
7613    };
7614
7615// Support: IE <=9 only
7616// Panic based approach to setting things on disconnected nodes
7617    Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
7618        set: function( tween ) {
7619            if ( tween.elem.nodeType && tween.elem.parentNode ) {
7620                tween.elem[ tween.prop ] = tween.now;
7621            }
7622        }
7623    };
7624
7625    jQuery.easing = {
7626        linear: function( p ) {
7627            return p;
7628        },
7629        swing: function( p ) {
7630            return 0.5 - Math.cos( p * Math.PI ) / 2;
7631        },
7632        _default: "swing"
7633    };
7634
7635    jQuery.fx = Tween.prototype.init;
7636
7637// Back compat <1.8 extension point
7638    jQuery.fx.step = {};
7639
7640
7641
7642
7643    var
7644        fxNow, inProgress,
7645        rfxtypes = /^(?:toggle|show|hide)$/,
7646        rrun = /queueHooks$/;
7647
7648    function schedule() {
7649        if ( inProgress ) {
7650            if ( document.hidden === false && window.requestAnimationFrame ) {
7651                window.requestAnimationFrame( schedule );
7652            } else {
7653                window.setTimeout( schedule, jQuery.fx.interval );
7654            }
7655
7656            jQuery.fx.tick();
7657        }
7658    }
7659
7660// Animations created synchronously will run synchronously
7661    function createFxNow() {
7662        window.setTimeout( function() {
7663            fxNow = undefined;
7664        } );
7665        return ( fxNow = Date.now() );
7666    }
7667
7668// Generate parameters to create a standard animation
7669    function genFx( type, includeWidth ) {
7670        var which,
7671            i = 0,
7672            attrs = { height: type };
7673
7674        // If we include width, step value is 1 to do all cssExpand values,
7675        // otherwise step value is 2 to skip over Left and Right
7676        includeWidth = includeWidth ? 1 : 0;
7677        for ( ; i < 4; i += 2 - includeWidth ) {
7678            which = cssExpand[ i ];
7679            attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
7680        }
7681
7682        if ( includeWidth ) {
7683            attrs.opacity = attrs.width = type;
7684        }
7685
7686        return attrs;
7687    }
7688
7689    function createTween( value, prop, animation ) {
7690        var tween,
7691            collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ),
7692            index = 0,
7693            length = collection.length;
7694        for ( ; index < length; index++ ) {
7695            if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) {
7696
7697                // We're done with this property
7698                return tween;
7699            }
7700        }
7701    }
7702
7703    function defaultPrefilter( elem, props, opts ) {
7704        var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display,
7705            isBox = "width" in props || "height" in props,
7706            anim = this,
7707            orig = {},
7708            style = elem.style,
7709            hidden = elem.nodeType && isHiddenWithinTree( elem ),
7710            dataShow = dataPriv.get( elem, "fxshow" );
7711
7712        // Queue-skipping animations hijack the fx hooks
7713        if ( !opts.queue ) {
7714            hooks = jQuery._queueHooks( elem, "fx" );
7715            if ( hooks.unqueued == null ) {
7716                hooks.unqueued = 0;
7717                oldfire = hooks.empty.fire;
7718                hooks.empty.fire = function() {
7719                    if ( !hooks.unqueued ) {
7720                        oldfire();
7721                    }
7722                };
7723            }
7724            hooks.unqueued++;
7725
7726            anim.always( function() {
7727
7728                // Ensure the complete handler is called before this completes
7729                anim.always( function() {
7730                    hooks.unqueued--;
7731                    if ( !jQuery.queue( elem, "fx" ).length ) {
7732                        hooks.empty.fire();
7733                    }
7734                } );
7735            } );
7736        }
7737
7738        // Detect show/hide animations
7739        for ( prop in props ) {
7740            value = props[ prop ];
7741            if ( rfxtypes.test( value ) ) {
7742                delete props[ prop ];
7743                toggle = toggle || value === "toggle";
7744                if ( value === ( hidden ? "hide" : "show" ) ) {
7745
7746                    // Pretend to be hidden if this is a "show" and
7747                    // there is still data from a stopped show/hide
7748                    if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
7749                        hidden = true;
7750
7751                        // Ignore all other no-op show/hide data
7752                    } else {
7753                        continue;
7754                    }
7755                }
7756                orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
7757            }
7758        }
7759
7760        // Bail out if this is a no-op like .hide().hide()
7761        propTween = !jQuery.isEmptyObject( props );
7762        if ( !propTween && jQuery.isEmptyObject( orig ) ) {
7763            return;
7764        }
7765
7766        // Restrict "overflow" and "display" styles during box animations
7767        if ( isBox && elem.nodeType === 1 ) {
7768
vendor: 5,766 bytes, lines 7769-7924
7769            // Support: IE <=9 - 11, Edge 12 - 15
7770            // Record all 3 overflow attributes because IE does not infer the shorthand
7771            // from identically-valued overflowX and overflowY and Edge just mirrors
7772            // the overflowX value there.
7773            opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
7774
7775            // Identify a display type, preferring old show/hide data over the CSS cascade
7776            restoreDisplay = dataShow && dataShow.display;
7777            if ( restoreDisplay == null ) {
7778                restoreDisplay = dataPriv.get( elem, "display" );
7779            }
7780            display = jQuery.css( elem, "display" );
7781            if ( display === "none" ) {
7782                if ( restoreDisplay ) {
7783                    display = restoreDisplay;
7784                } else {
7785
7786                    // Get nonempty value(s) by temporarily forcing visibility
7787                    showHide( [ elem ], true );
7788                    restoreDisplay = elem.style.display || restoreDisplay;
7789                    display = jQuery.css( elem, "display" );
7790                    showHide( [ elem ] );
7791                }
7792            }
7793
7794            // Animate inline elements as inline-block
7795            if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) {
7796                if ( jQuery.css( elem, "float" ) === "none" ) {
7797
7798                    // Restore the original display value at the end of pure show/hide animations
7799                    if ( !propTween ) {
7800                        anim.done( function() {
7801                            style.display = restoreDisplay;
7802                        } );
7803                        if ( restoreDisplay == null ) {
7804                            display = style.display;
7805                            restoreDisplay = display === "none" ? "" : display;
7806                        }
7807                    }
7808                    style.display = "inline-block";
7809                }
7810            }
7811        }
7812
7813        if ( opts.overflow ) {
7814            style.overflow = "hidden";
7815            anim.always( function() {
7816                style.overflow = opts.overflow[ 0 ];
7817                style.overflowX = opts.overflow[ 1 ];
7818                style.overflowY = opts.overflow[ 2 ];
7819            } );
7820        }
7821
7822        // Implement show/hide animations
7823        propTween = false;
7824        for ( prop in orig ) {
7825
7826            // General show/hide setup for this element animation
7827            if ( !propTween ) {
7828                if ( dataShow ) {
7829                    if ( "hidden" in dataShow ) {
7830                        hidden = dataShow.hidden;
7831                    }
7832                } else {
7833                    dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } );
7834                }
7835
7836                // Store hidden/visible for toggle so `.stop().toggle()` "reverses"
7837                if ( toggle ) {
7838                    dataShow.hidden = !hidden;
7839                }
7840
7841                // Show elements before animating them
7842                if ( hidden ) {
7843                    showHide( [ elem ], true );
7844                }
7845
7846                /* eslint-disable no-loop-func */
7847
7848                anim.done( function() {
7849
7850                    /* eslint-enable no-loop-func */
7851
7852                    // The final step of a "hide" animation is actually hiding the element
7853                    if ( !hidden ) {
7854                        showHide( [ elem ] );
7855                    }
7856                    dataPriv.remove( elem, "fxshow" );
7857                    for ( prop in orig ) {
7858                        jQuery.style( elem, prop, orig[ prop ] );
7859                    }
7860                } );
7861            }
7862
7863            // Per-property setup
7864            propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
7865            if ( !( prop in dataShow ) ) {
7866                dataShow[ prop ] = propTween.start;
7867                if ( hidden ) {
7868                    propTween.end = propTween.start;
7869                    propTween.start = 0;
7870                }
7871            }
7872        }
7873    }
7874
7875    function propFilter( props, specialEasing ) {
7876        var index, name, easing, value, hooks;
7877
7878        // camelCase, specialEasing and expand cssHook pass
7879        for ( index in props ) {
7880            name = camelCase( index );
7881            easing = specialEasing[ name ];
7882            value = props[ index ];
7883            if ( Array.isArray( value ) ) {
7884                easing = value[ 1 ];
7885                value = props[ index ] = value[ 0 ];
7886            }
7887
7888            if ( index !== name ) {
7889                props[ name ] = value;
7890                delete props[ index ];
7891            }
7892
7893            hooks = jQuery.cssHooks[ name ];
7894            if ( hooks && "expand" in hooks ) {
7895                value = hooks.expand( value );
7896                delete props[ name ];
7897
7898                // Not quite $.extend, this won't overwrite existing keys.
7899                // Reusing 'index' because we have the correct "name"
7900                for ( index in value ) {
7901                    if ( !( index in props ) ) {
7902                        props[ index ] = value[ index ];
7903                        specialEasing[ index ] = easing;
7904                    }
7905                }
7906            } else {
7907                specialEasing[ name ] = easing;
7908            }
7909        }
7910    }
7911
7912    function Animation( elem, properties, options ) {
7913        var result,
7914            stopped,
7915            index = 0,
7916            length = Animation.prefilters.length,
7917            deferred = jQuery.Deferred().always( function() {
7918
7919                // Don't match elem in the :animated selector
7920                delete tick.elem;
7921            } ),
7922            tick = function() {
7923                if ( stopped ) {
7924                    return false;
vendor: 20,456 bytes, lines 7925-8541
7925                }
7926                var currentTime = fxNow || createFxNow(),
7927                    remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
7928
7929                    // Support: Android 2.3 only
7930                    // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497)
7931                    temp = remaining / animation.duration || 0,
7932                    percent = 1 - temp,
7933                    index = 0,
7934                    length = animation.tweens.length;
7935
7936                for ( ; index < length; index++ ) {
7937                    animation.tweens[ index ].run( percent );
7938                }
7939
7940                deferred.notifyWith( elem, [ animation, percent, remaining ] );
7941
7942                // If there's more to do, yield
7943                if ( percent < 1 && length ) {
7944                    return remaining;
7945                }
7946
7947                // If this was an empty animation, synthesize a final progress notification
7948                if ( !length ) {
7949                    deferred.notifyWith( elem, [ animation, 1, 0 ] );
7950                }
7951
7952                // Resolve the animation and report its conclusion
7953                deferred.resolveWith( elem, [ animation ] );
7954                return false;
7955            },
7956            animation = deferred.promise( {
7957                elem: elem,
7958                props: jQuery.extend( {}, properties ),
7959                opts: jQuery.extend( true, {
7960                    specialEasing: {},
7961                    easing: jQuery.easing._default
7962                }, options ),
7963                originalProperties: properties,
7964                originalOptions: options,
7965                startTime: fxNow || createFxNow(),
7966                duration: options.duration,
7967                tweens: [],
7968                createTween: function( prop, end ) {
7969                    var tween = jQuery.Tween( elem, animation.opts, prop, end,
7970                        animation.opts.specialEasing[ prop ] || animation.opts.easing );
7971                    animation.tweens.push( tween );
7972                    return tween;
7973                },
7974                stop: function( gotoEnd ) {
7975                    var index = 0,
7976
7977                        // If we are going to the end, we want to run all the tweens
7978                        // otherwise we skip this part
7979                        length = gotoEnd ? animation.tweens.length : 0;
7980                    if ( stopped ) {
7981                        return this;
7982                    }
7983                    stopped = true;
7984                    for ( ; index < length; index++ ) {
7985                        animation.tweens[ index ].run( 1 );
7986                    }
7987
7988                    // Resolve when we played the last frame; otherwise, reject
7989                    if ( gotoEnd ) {
7990                        deferred.notifyWith( elem, [ animation, 1, 0 ] );
7991                        deferred.resolveWith( elem, [ animation, gotoEnd ] );
7992                    } else {
7993                        deferred.rejectWith( elem, [ animation, gotoEnd ] );
7994                    }
7995                    return this;
7996                }
7997            } ),
7998            props = animation.props;
7999
8000        propFilter( props, animation.opts.specialEasing );
8001
8002        for ( ; index < length; index++ ) {
8003            result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts );
8004            if ( result ) {
8005                if ( isFunction( result.stop ) ) {
8006                    jQuery._queueHooks( animation.elem, animation.opts.queue ).stop =
8007                        result.stop.bind( result );
8008                }
8009                return result;
8010            }
8011        }
8012
8013        jQuery.map( props, createTween, animation );
8014
8015        if ( isFunction( animation.opts.start ) ) {
8016            animation.opts.start.call( elem, animation );
8017        }
8018
8019        // Attach callbacks from options
8020        animation
8021            .progress( animation.opts.progress )
8022            .done( animation.opts.done, animation.opts.complete )
8023            .fail( animation.opts.fail )
8024            .always( animation.opts.always );
8025
8026        jQuery.fx.timer(
8027            jQuery.extend( tick, {
8028                elem: elem,
8029                anim: animation,
8030                queue: animation.opts.queue
8031            } )
8032        );
8033
8034        return animation;
8035    }
8036
8037    jQuery.Animation = jQuery.extend( Animation, {
8038
8039        tweeners: {
8040            "*": [ function( prop, value ) {
8041                var tween = this.createTween( prop, value );
8042                adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween );
8043                return tween;
8044            } ]
8045        },
8046
8047        tweener: function( props, callback ) {
8048            if ( isFunction( props ) ) {
8049                callback = props;
8050                props = [ "*" ];
8051            } else {
8052                props = props.match( rnothtmlwhite );
8053            }
8054
8055            var prop,
8056                index = 0,
8057                length = props.length;
8058
8059            for ( ; index < length; index++ ) {
8060                prop = props[ index ];
8061                Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || [];
8062                Animation.tweeners[ prop ].unshift( callback );
8063            }
8064        },
8065
8066        prefilters: [ defaultPrefilter ],
8067
8068        prefilter: function( callback, prepend ) {
8069            if ( prepend ) {
8070                Animation.prefilters.unshift( callback );
8071            } else {
8072                Animation.prefilters.push( callback );
8073            }
8074        }
8075    } );
8076
8077    jQuery.speed = function( speed, easing, fn ) {
8078        var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
8079            complete: fn || !fn && easing ||
8080                isFunction( speed ) && speed,
8081            duration: speed,
8082            easing: fn && easing || easing && !isFunction( easing ) && easing
8083        };
8084
8085        // Go to the end state if fx are off
8086        if ( jQuery.fx.off ) {
8087            opt.duration = 0;
8088
8089        } else {
8090            if ( typeof opt.duration !== "number" ) {
8091                if ( opt.duration in jQuery.fx.speeds ) {
8092                    opt.duration = jQuery.fx.speeds[ opt.duration ];
8093
8094                } else {
8095                    opt.duration = jQuery.fx.speeds._default;
8096                }
8097            }
8098        }
8099
8100        // Normalize opt.queue - true/undefined/null -> "fx"
8101        if ( opt.queue == null || opt.queue === true ) {
8102            opt.queue = "fx";
8103        }
8104
8105        // Queueing
8106        opt.old = opt.complete;
8107
8108        opt.complete = function() {
8109            if ( isFunction( opt.old ) ) {
8110                opt.old.call( this );
8111            }
8112
8113            if ( opt.queue ) {
8114                jQuery.dequeue( this, opt.queue );
8115            }
8116        };
8117
8118        return opt;
8119    };
8120
8121    jQuery.fn.extend( {
8122        fadeTo: function( speed, to, easing, callback ) {
8123
8124            // Show any hidden elements after setting opacity to 0
8125            return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show()
8126
8127            // Animate to the value specified
8128                .end().animate( { opacity: to }, speed, easing, callback );
8129        },
8130        animate: function( prop, speed, easing, callback ) {
8131            var empty = jQuery.isEmptyObject( prop ),
8132                optall = jQuery.speed( speed, easing, callback ),
8133                doAnimation = function() {
8134
8135                    // Operate on a copy of prop so per-property easing won't be lost
8136                    var anim = Animation( this, jQuery.extend( {}, prop ), optall );
8137
8138                    // Empty animations, or finishing resolves immediately
8139                    if ( empty || dataPriv.get( this, "finish" ) ) {
8140                        anim.stop( true );
8141                    }
8142                };
8143
8144            doAnimation.finish = doAnimation;
8145
8146            return empty || optall.queue === false ?
8147                this.each( doAnimation ) :
8148                this.queue( optall.queue, doAnimation );
8149        },
8150        stop: function( type, clearQueue, gotoEnd ) {
8151            var stopQueue = function( hooks ) {
8152                var stop = hooks.stop;
8153                delete hooks.stop;
8154                stop( gotoEnd );
8155            };
8156
8157            if ( typeof type !== "string" ) {
8158                gotoEnd = clearQueue;
8159                clearQueue = type;
8160                type = undefined;
8161            }
8162            if ( clearQueue ) {
8163                this.queue( type || "fx", [] );
8164            }
8165
8166            return this.each( function() {
8167                var dequeue = true,
8168                    index = type != null && type + "queueHooks",
8169                    timers = jQuery.timers,
8170                    data = dataPriv.get( this );
8171
8172                if ( index ) {
8173                    if ( data[ index ] && data[ index ].stop ) {
8174                        stopQueue( data[ index ] );
8175                    }
8176                } else {
8177                    for ( index in data ) {
8178                        if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
8179                            stopQueue( data[ index ] );
8180                        }
8181                    }
8182                }
8183
8184                for ( index = timers.length; index--; ) {
8185                    if ( timers[ index ].elem === this &&
8186                        ( type == null || timers[ index ].queue === type ) ) {
8187
8188                        timers[ index ].anim.stop( gotoEnd );
8189                        dequeue = false;
8190                        timers.splice( index, 1 );
8191                    }
8192                }
8193
8194                // Start the next in the queue if the last step wasn't forced.
8195                // Timers currently will call their complete callbacks, which
8196                // will dequeue but only if they were gotoEnd.
8197                if ( dequeue || !gotoEnd ) {
8198                    jQuery.dequeue( this, type );
8199                }
8200            } );
8201        },
8202        finish: function( type ) {
8203            if ( type !== false ) {
8204                type = type || "fx";
8205            }
8206            return this.each( function() {
8207                var index,
8208                    data = dataPriv.get( this ),
8209                    queue = data[ type + "queue" ],
8210                    hooks = data[ type + "queueHooks" ],
8211                    timers = jQuery.timers,
8212                    length = queue ? queue.length : 0;
8213
8214                // Enable finishing flag on private data
8215                data.finish = true;
8216
8217                // Empty the queue first
8218                jQuery.queue( this, type, [] );
8219
8220                if ( hooks && hooks.stop ) {
8221                    hooks.stop.call( this, true );
8222                }
8223
8224                // Look for any active animations, and finish them
8225                for ( index = timers.length; index--; ) {
8226                    if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
8227                        timers[ index ].anim.stop( true );
8228                        timers.splice( index, 1 );
8229                    }
8230                }
8231
8232                // Look for any animations in the old queue and finish them
8233                for ( index = 0; index < length; index++ ) {
8234                    if ( queue[ index ] && queue[ index ].finish ) {
8235                        queue[ index ].finish.call( this );
8236                    }
8237                }
8238
8239                // Turn off finishing flag
8240                delete data.finish;
8241            } );
8242        }
8243    } );
8244
8245    jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) {
8246        var cssFn = jQuery.fn[ name ];
8247        jQuery.fn[ name ] = function( speed, easing, callback ) {
8248            return speed == null || typeof speed === "boolean" ?
8249                cssFn.apply( this, arguments ) :
8250                this.animate( genFx( name, true ), speed, easing, callback );
8251        };
8252    } );
8253
8254// Generate shortcuts for custom animations
8255    jQuery.each( {
8256        slideDown: genFx( "show" ),
8257        slideUp: genFx( "hide" ),
8258        slideToggle: genFx( "toggle" ),
8259        fadeIn: { opacity: "show" },
8260        fadeOut: { opacity: "hide" },
8261        fadeToggle: { opacity: "toggle" }
8262    }, function( name, props ) {
8263        jQuery.fn[ name ] = function( speed, easing, callback ) {
8264            return this.animate( props, speed, easing, callback );
8265        };
8266    } );
8267
8268    jQuery.timers = [];
8269    jQuery.fx.tick = function() {
8270        var timer,
8271            i = 0,
8272            timers = jQuery.timers;
8273
8274        fxNow = Date.now();
8275
8276        for ( ; i < timers.length; i++ ) {
8277            timer = timers[ i ];
8278
8279            // Run the timer and safely remove it when done (allowing for external removal)
8280            if ( !timer() && timers[ i ] === timer ) {
8281                timers.splice( i--, 1 );
8282            }
8283        }
8284
8285        if ( !timers.length ) {
8286            jQuery.fx.stop();
8287        }
8288        fxNow = undefined;
8289    };
8290
8291    jQuery.fx.timer = function( timer ) {
8292        jQuery.timers.push( timer );
8293        jQuery.fx.start();
8294    };
8295
8296    jQuery.fx.interval = 13;
8297    jQuery.fx.start = function() {
8298        if ( inProgress ) {
8299            return;
8300        }
8301
8302        inProgress = true;
8303        schedule();
8304    };
8305
8306    jQuery.fx.stop = function() {
8307        inProgress = null;
8308    };
8309
8310    jQuery.fx.speeds = {
8311        slow: 600,
8312        fast: 200,
8313
8314        // Default speed
8315        _default: 400
8316    };
8317
8318
8319// Based off of the plugin by Clint Helfers, with permission.
8320// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/
8321    jQuery.fn.delay = function( time, type ) {
8322        time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
8323        type = type || "fx";
8324
8325        return this.queue( type, function( next, hooks ) {
8326            var timeout = window.setTimeout( next, time );
8327            hooks.stop = function() {
8328                window.clearTimeout( timeout );
8329            };
8330        } );
8331    };
8332
8333
8334    ( function() {
8335        var input = document.createElement( "input" ),
8336            select = document.createElement( "select" ),
8337            opt = select.appendChild( document.createElement( "option" ) );
8338
8339        input.type = "checkbox";
8340
8341        // Support: Android <=4.3 only
8342        // Default value for a checkbox should be "on"
8343        support.checkOn = input.value !== "";
8344
8345        // Support: IE <=11 only
8346        // Must access selectedIndex to make default options select
8347        support.optSelected = opt.selected;
8348
8349        // Support: IE <=11 only
8350        // An input loses its value after becoming a radio
8351        input = document.createElement( "input" );
8352        input.value = "t";
8353        input.type = "radio";
8354        support.radioValue = input.value === "t";
8355    } )();
8356
8357
8358    var boolHook,
8359        attrHandle = jQuery.expr.attrHandle;
8360
8361    jQuery.fn.extend( {
8362        attr: function( name, value ) {
8363            return access( this, jQuery.attr, name, value, arguments.length > 1 );
8364        },
8365
8366        removeAttr: function( name ) {
8367            return this.each( function() {
8368                jQuery.removeAttr( this, name );
8369            } );
8370        }
8371    } );
8372
8373    jQuery.extend( {
8374        attr: function( elem, name, value ) {
8375            var ret, hooks,
8376                nType = elem.nodeType;
8377
8378            // Don't get/set attributes on text, comment and attribute nodes
8379            if ( nType === 3 || nType === 8 || nType === 2 ) {
8380                return;
8381            }
8382
8383            // Fallback to prop when attributes are not supported
8384            if ( typeof elem.getAttribute === "undefined" ) {
8385                return jQuery.prop( elem, name, value );
8386            }
8387
8388            // Attribute hooks are determined by the lowercase version
8389            // Grab necessary hook if one is defined
8390            if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
8391                hooks = jQuery.attrHooks[ name.toLowerCase() ] ||
8392                    ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined );
8393            }
8394
8395            if ( value !== undefined ) {
8396                if ( value === null ) {
8397                    jQuery.removeAttr( elem, name );
8398                    return;
8399                }
8400
8401                if ( hooks && "set" in hooks &&
8402                    ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
8403                    return ret;
8404                }
8405
8406                elem.setAttribute( name, value + "" );
8407                return value;
8408            }
8409
8410            if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
8411                return ret;
8412            }
8413
8414            ret = jQuery.find.attr( elem, name );
8415
8416            // Non-existent attributes return null, we normalize to undefined
8417            return ret == null ? undefined : ret;
8418        },
8419
8420        attrHooks: {
8421            type: {
8422                set: function( elem, value ) {
8423                    if ( !support.radioValue && value === "radio" &&
8424                        nodeName( elem, "input" ) ) {
8425                        var val = elem.value;
8426                        elem.setAttribute( "type", value );
8427                        if ( val ) {
8428                            elem.value = val;
8429                        }
8430                        return value;
8431                    }
8432                }
8433            }
8434        },
8435
8436        removeAttr: function( elem, value ) {
8437            var name,
8438                i = 0,
8439
8440                // Attribute names can contain non-HTML whitespace characters
8441                // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2
8442                attrNames = value && value.match( rnothtmlwhite );
8443
8444            if ( attrNames && elem.nodeType === 1 ) {
8445                while ( ( name = attrNames[ i++ ] ) ) {
8446                    elem.removeAttribute( name );
8447                }
8448            }
8449        }
8450    } );
8451
8452// Hooks for boolean attributes
8453    boolHook = {
8454        set: function( elem, value, name ) {
8455            if ( value === false ) {
8456
8457                // Remove boolean attributes when set to false
8458                jQuery.removeAttr( elem, name );
8459            } else {
8460                elem.setAttribute( name, name );
8461            }
8462            return name;
8463        }
8464    };
8465
8466    jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) {
8467        var getter = attrHandle[ name ] || jQuery.find.attr;
8468
8469        attrHandle[ name ] = function( elem, name, isXML ) {
8470            var ret, handle,
8471                lowercaseName = name.toLowerCase();
8472
8473            if ( !isXML ) {
8474
8475                // Avoid an infinite loop by temporarily removing this function from the getter
8476                handle = attrHandle[ lowercaseName ];
8477                attrHandle[ lowercaseName ] = ret;
8478                ret = getter( elem, name, isXML ) != null ?
8479                    lowercaseName :
8480                    null;
8481                attrHandle[ lowercaseName ] = handle;
8482            }
8483            return ret;
8484        };
8485    } );
8486
8487
8488
8489
8490    var rfocusable = /^(?:input|select|textarea|button)$/i,
8491        rclickable = /^(?:a|area)$/i;
8492
8493    jQuery.fn.extend( {
8494        prop: function( name, value ) {
8495            return access( this, jQuery.prop, name, value, arguments.length > 1 );
8496        },
8497
8498        removeProp: function( name ) {
8499            return this.each( function() {
8500                delete this[ jQuery.propFix[ name ] || name ];
8501            } );
8502        }
8503    } );
8504
8505    jQuery.extend( {
8506        prop: function( elem, name, value ) {
8507            var ret, hooks,
8508                nType = elem.nodeType;
8509
8510            // Don't get/set properties on text, comment and attribute nodes
8511            if ( nType === 3 || nType === 8 || nType === 2 ) {
8512                return;
8513            }
8514
8515            if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
8516
8517                // Fix name and attach hooks
8518                name = jQuery.propFix[ name ] || name;
8519                hooks = jQuery.propHooks[ name ];
8520            }
8521
8522            if ( value !== undefined ) {
8523                if ( hooks && "set" in hooks &&
8524                    ( ret = hooks.set( elem, value, name ) ) !== undefined ) {
8525                    return ret;
8526                }
8527
8528                return ( elem[ name ] = value );
8529            }
8530
8531            if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) {
8532                return ret;
8533            }
8534
8535            return elem[ name ];
8536        },
8537
8538        propHooks: {
8539            tabIndex: {
8540                get: function( elem ) {
8541
vendor: 16,418 bytes, lines 8542-9030
8542                    // Support: IE <=9 - 11 only
8543                    // elem.tabIndex doesn't always return the
8544                    // correct value when it hasn't been explicitly set
8545                    // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
8546                    // Use proper attribute retrieval(#12072)
8547                    var tabindex = jQuery.find.attr( elem, "tabindex" );
8548
8549                    if ( tabindex ) {
8550                        return parseInt( tabindex, 10 );
8551                    }
8552
8553                    if (
8554                        rfocusable.test( elem.nodeName ) ||
8555                        rclickable.test( elem.nodeName ) &&
8556                        elem.href
8557                    ) {
8558                        return 0;
8559                    }
8560
8561                    return -1;
8562                }
8563            }
8564        },
8565
8566        propFix: {
8567            "for": "htmlFor",
8568            "class": "className"
8569        }
8570    } );
8571
8572// Support: IE <=11 only
8573// Accessing the selectedIndex property
8574// forces the browser to respect setting selected
8575// on the option
8576// The getter ensures a default option is selected
8577// when in an optgroup
8578// eslint rule "no-unused-expressions" is disabled for this code
8579// since it considers such accessions noop
8580    if ( !support.optSelected ) {
8581        jQuery.propHooks.selected = {
8582            get: function( elem ) {
8583
8584                /* eslint no-unused-expressions: "off" */
8585
8586                var parent = elem.parentNode;
8587                if ( parent && parent.parentNode ) {
8588                    parent.parentNode.selectedIndex;
8589                }
8590                return null;
8591            },
8592            set: function( elem ) {
8593
8594                /* eslint no-unused-expressions: "off" */
8595
8596                var parent = elem.parentNode;
8597                if ( parent ) {
8598                    parent.selectedIndex;
8599
8600                    if ( parent.parentNode ) {
8601                        parent.parentNode.selectedIndex;
8602                    }
8603                }
8604            }
8605        };
8606    }
8607
8608    jQuery.each( [
8609        "tabIndex",
8610        "readOnly",
8611        "maxLength",
8612        "cellSpacing",
8613        "cellPadding",
8614        "rowSpan",
8615        "colSpan",
8616        "useMap",
8617        "frameBorder",
8618        "contentEditable"
8619    ], function() {
8620        jQuery.propFix[ this.toLowerCase() ] = this;
8621    } );
8622
8623
8624
8625
8626    // Strip and collapse whitespace according to HTML spec
8627    // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace
8628    function stripAndCollapse( value ) {
8629        var tokens = value.match( rnothtmlwhite ) || [];
8630        return tokens.join( " " );
8631    }
8632
8633
8634    function getClass( elem ) {
8635        return elem.getAttribute && elem.getAttribute( "class" ) || "";
8636    }
8637
8638    function classesToArray( value ) {
8639        if ( Array.isArray( value ) ) {
8640            return value;
8641        }
8642        if ( typeof value === "string" ) {
8643            return value.match( rnothtmlwhite ) || [];
8644        }
8645        return [];
8646    }
8647
8648    jQuery.fn.extend( {
8649        addClass: function( value ) {
8650            var classes, elem, cur, curValue, clazz, j, finalValue,
8651                i = 0;
8652
8653            if ( isFunction( value ) ) {
8654                return this.each( function( j ) {
8655                    jQuery( this ).addClass( value.call( this, j, getClass( this ) ) );
8656                } );
8657            }
8658
8659            classes = classesToArray( value );
8660
8661            if ( classes.length ) {
8662                while ( ( elem = this[ i++ ] ) ) {
8663                    curValue = getClass( elem );
8664                    cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
8665
8666                    if ( cur ) {
8667                        j = 0;
8668                        while ( ( clazz = classes[ j++ ] ) ) {
8669                            if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
8670                                cur += clazz + " ";
8671                            }
8672                        }
8673
8674                        // Only assign if different to avoid unneeded rendering.
8675                        finalValue = stripAndCollapse( cur );
8676                        if ( curValue !== finalValue ) {
8677                            elem.setAttribute( "class", finalValue );
8678                        }
8679                    }
8680                }
8681            }
8682
8683            return this;
8684        },
8685
8686        removeClass: function( value ) {
8687            var classes, elem, cur, curValue, clazz, j, finalValue,
8688                i = 0;
8689
8690            if ( isFunction( value ) ) {
8691                return this.each( function( j ) {
8692                    jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) );
8693                } );
8694            }
8695
8696            if ( !arguments.length ) {
8697                return this.attr( "class", "" );
8698            }
8699
8700            classes = classesToArray( value );
8701
8702            if ( classes.length ) {
8703                while ( ( elem = this[ i++ ] ) ) {
8704                    curValue = getClass( elem );
8705
8706                    // This expression is here for better compressibility (see addClass)
8707                    cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " );
8708
8709                    if ( cur ) {
8710                        j = 0;
8711                        while ( ( clazz = classes[ j++ ] ) ) {
8712
8713                            // Remove *all* instances
8714                            while ( cur.indexOf( " " + clazz + " " ) > -1 ) {
8715                                cur = cur.replace( " " + clazz + " ", " " );
8716                            }
8717                        }
8718
8719                        // Only assign if different to avoid unneeded rendering.
8720                        finalValue = stripAndCollapse( cur );
8721                        if ( curValue !== finalValue ) {
8722                            elem.setAttribute( "class", finalValue );
8723                        }
8724                    }
8725                }
8726            }
8727
8728            return this;
8729        },
8730
8731        toggleClass: function( value, stateVal ) {
8732            var type = typeof value,
8733                isValidValue = type === "string" || Array.isArray( value );
8734
8735            if ( typeof stateVal === "boolean" && isValidValue ) {
8736                return stateVal ? this.addClass( value ) : this.removeClass( value );
8737            }
8738
8739            if ( isFunction( value ) ) {
8740                return this.each( function( i ) {
8741                    jQuery( this ).toggleClass(
8742                        value.call( this, i, getClass( this ), stateVal ),
8743                        stateVal
8744                    );
8745                } );
8746            }
8747
8748            return this.each( function() {
8749                var className, i, self, classNames;
8750
8751                if ( isValidValue ) {
8752
8753                    // Toggle individual class names
8754                    i = 0;
8755                    self = jQuery( this );
8756                    classNames = classesToArray( value );
8757
8758                    while ( ( className = classNames[ i++ ] ) ) {
8759
8760                        // Check each className given, space separated list
8761                        if ( self.hasClass( className ) ) {
8762                            self.removeClass( className );
8763                        } else {
8764                            self.addClass( className );
8765                        }
8766                    }
8767
8768                    // Toggle whole class name
8769                } else if ( value === undefined || type === "boolean" ) {
8770                    className = getClass( this );
8771                    if ( className ) {
8772
8773                        // Store className if set
8774                        dataPriv.set( this, "__className__", className );
8775                    }
8776
8777                    // If the element has a class name or if we're passed `false`,
8778                    // then remove the whole classname (if there was one, the above saved it).
8779                    // Otherwise bring back whatever was previously saved (if anything),
8780                    // falling back to the empty string if nothing was stored.
8781                    if ( this.setAttribute ) {
8782                        this.setAttribute( "class",
8783                            className || value === false ?
8784                                "" :
8785                                dataPriv.get( this, "__className__" ) || ""
8786                        );
8787                    }
8788                }
8789            } );
8790        },
8791
8792        hasClass: function( selector ) {
8793            var className, elem,
8794                i = 0;
8795
8796            className = " " + selector + " ";
8797            while ( ( elem = this[ i++ ] ) ) {
8798                if ( elem.nodeType === 1 &&
8799                    ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) {
8800                    return true;
8801                }
8802            }
8803
8804            return false;
8805        }
8806    } );
8807
8808
8809
8810
8811    var rreturn = /\r/g;
8812
8813    jQuery.fn.extend( {
8814        val: function( value ) {
8815            var hooks, ret, valueIsFunction,
8816                elem = this[ 0 ];
8817
8818            if ( !arguments.length ) {
8819                if ( elem ) {
8820                    hooks = jQuery.valHooks[ elem.type ] ||
8821                        jQuery.valHooks[ elem.nodeName.toLowerCase() ];
8822
8823                    if ( hooks &&
8824                        "get" in hooks &&
8825                        ( ret = hooks.get( elem, "value" ) ) !== undefined
8826                    ) {
8827                        return ret;
8828                    }
8829
8830                    ret = elem.value;
8831
8832                    // Handle most common string cases
8833                    if ( typeof ret === "string" ) {
8834                        return ret.replace( rreturn, "" );
8835                    }
8836
8837                    // Handle cases where value is null/undef or number
8838                    return ret == null ? "" : ret;
8839                }
8840
8841                return;
8842            }
8843
8844            valueIsFunction = isFunction( value );
8845
8846            return this.each( function( i ) {
8847                var val;
8848
8849                if ( this.nodeType !== 1 ) {
8850                    return;
8851                }
8852
8853                if ( valueIsFunction ) {
8854                    val = value.call( this, i, jQuery( this ).val() );
8855                } else {
8856                    val = value;
8857                }
8858
8859                // Treat null/undefined as ""; convert numbers to string
8860                if ( val == null ) {
8861                    val = "";
8862
8863                } else if ( typeof val === "number" ) {
8864                    val += "";
8865
8866                } else if ( Array.isArray( val ) ) {
8867                    val = jQuery.map( val, function( value ) {
8868                        return value == null ? "" : value + "";
8869                    } );
8870                }
8871
8872                hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
8873
8874                // If set returns undefined, fall back to normal setting
8875                if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
8876                    this.value = val;
8877                }
8878            } );
8879        }
8880    } );
8881
8882    jQuery.extend( {
8883        valHooks: {
8884            option: {
8885                get: function( elem ) {
8886
8887                    var val = jQuery.find.attr( elem, "value" );
8888                    return val != null ?
8889                        val :
8890
8891                        // Support: IE <=10 - 11 only
8892                        // option.text throws exceptions (#14686, #14858)
8893                        // Strip and collapse whitespace
8894                        // https://html.spec.whatwg.org/#strip-and-collapse-whitespace
8895                        stripAndCollapse( jQuery.text( elem ) );
8896                }
8897            },
8898            select: {
8899                get: function( elem ) {
8900                    var value, option, i,
8901                        options = elem.options,
8902                        index = elem.selectedIndex,
8903                        one = elem.type === "select-one",
8904                        values = one ? null : [],
8905                        max = one ? index + 1 : options.length;
8906
8907                    if ( index < 0 ) {
8908                        i = max;
8909
8910                    } else {
8911                        i = one ? index : 0;
8912                    }
8913
8914                    // Loop through all the selected options
8915                    for ( ; i < max; i++ ) {
8916                        option = options[ i ];
8917
8918                        // Support: IE <=9 only
8919                        // IE8-9 doesn't update selected after form reset (#2551)
8920                        if ( ( option.selected || i === index ) &&
8921
8922                            // Don't return options that are disabled or in a disabled optgroup
8923                            !option.disabled &&
8924                            ( !option.parentNode.disabled ||
8925                                !nodeName( option.parentNode, "optgroup" ) ) ) {
8926
8927                            // Get the specific value for the option
8928                            value = jQuery( option ).val();
8929
8930                            // We don't need an array for one selects
8931                            if ( one ) {
8932                                return value;
8933                            }
8934
8935                            // Multi-Selects return an array
8936                            values.push( value );
8937                        }
8938                    }
8939
8940                    return values;
8941                },
8942
8943                set: function( elem, value ) {
8944                    var optionSet, option,
8945                        options = elem.options,
8946                        values = jQuery.makeArray( value ),
8947                        i = options.length;
8948
8949                    while ( i-- ) {
8950                        option = options[ i ];
8951
8952                        /* eslint-disable no-cond-assign */
8953
8954                        if ( option.selected =
8955                            jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1
8956                        ) {
8957                            optionSet = true;
8958                        }
8959
8960                        /* eslint-enable no-cond-assign */
8961                    }
8962
8963                    // Force browsers to behave consistently when non-matching value is set
8964                    if ( !optionSet ) {
8965                        elem.selectedIndex = -1;
8966                    }
8967                    return values;
8968                }
8969            }
8970        }
8971    } );
8972
8973// Radios and checkboxes getter/setter
8974    jQuery.each( [ "radio", "checkbox" ], function() {
8975        jQuery.valHooks[ this ] = {
8976            set: function( elem, value ) {
8977                if ( Array.isArray( value ) ) {
8978                    return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 );
8979                }
8980            }
8981        };
8982        if ( !support.checkOn ) {
8983            jQuery.valHooks[ this ].get = function( elem ) {
8984                return elem.getAttribute( "value" ) === null ? "on" : elem.value;
8985            };
8986        }
8987    } );
8988
8989
8990
8991
8992// Return jQuery for attributes-only inclusion
8993
8994
8995    support.focusin = "onfocusin" in window;
8996
8997
8998    var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
8999        stopPropagationCallback = function( e ) {
9000            e.stopPropagation();
9001        };
9002
9003    jQuery.extend( jQuery.event, {
9004
9005        trigger: function( event, data, elem, onlyHandlers ) {
9006
9007            var i, cur, tmp, bubbleType, ontype, handle, special, lastElement,
9008                eventPath = [ elem || document ],
9009                type = hasOwn.call( event, "type" ) ? event.type : event,
9010                namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
9011
9012            cur = lastElement = tmp = elem = elem || document;
9013
9014            // Don't do events on text and comment nodes
9015            if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
9016                return;
9017            }
9018
9019            // focus/blur morphs to focusin/out; ensure we're not firing them right now
9020            if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
9021                return;
9022            }
9023
9024            if ( type.indexOf( "." ) > -1 ) {
9025
9026                // Namespaced trigger; create a regexp to match event type in handle()
9027                namespaces = type.split( "." );
9028                type = namespaces.shift();
9029                namespaces.sort();
9030            }
vendor: 5,789 bytes, lines 9031-9184
9031            ontype = type.indexOf( ":" ) < 0 && "on" + type;
9032
9033            // Caller can pass in a jQuery.Event object, Object, or just an event type string
9034            event = event[ jQuery.expando ] ?
9035                event :
9036                new jQuery.Event( type, typeof event === "object" && event );
9037
9038            // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
9039            event.isTrigger = onlyHandlers ? 2 : 3;
9040            event.namespace = namespaces.join( "." );
9041            event.rnamespace = event.namespace ?
9042                new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
9043                null;
9044
9045            // Clean up the event in case it is being reused
9046            event.result = undefined;
9047            if ( !event.target ) {
9048                event.target = elem;
9049            }
9050
9051            // Clone any incoming data and prepend the event, creating the handler arg list
9052            data = data == null ?
9053                [ event ] :
9054                jQuery.makeArray( data, [ event ] );
9055
9056            // Allow special events to draw outside the lines
9057            special = jQuery.event.special[ type ] || {};
9058            if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
9059                return;
9060            }
9061
9062            // Determine event propagation path in advance, per W3C events spec (#9951)
9063            // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
9064            if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) {
9065
9066                bubbleType = special.delegateType || type;
9067                if ( !rfocusMorph.test( bubbleType + type ) ) {
9068                    cur = cur.parentNode;
9069                }
9070                for ( ; cur; cur = cur.parentNode ) {
9071                    eventPath.push( cur );
9072                    tmp = cur;
9073                }
9074
9075                // Only add window if we got to document (e.g., not plain obj or detached DOM)
9076                if ( tmp === ( elem.ownerDocument || document ) ) {
9077                    eventPath.push( tmp.defaultView || tmp.parentWindow || window );
9078                }
9079            }
9080
9081            // Fire handlers on the event path
9082            i = 0;
9083            while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
9084                lastElement = cur;
9085                event.type = i > 1 ?
9086                    bubbleType :
9087                    special.bindType || type;
9088
9089                // jQuery handler
9090                handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] &&
9091                    dataPriv.get( cur, "handle" );
9092                if ( handle ) {
9093                    handle.apply( cur, data );
9094                }
9095
9096                // Native handler
9097                handle = ontype && cur[ ontype ];
9098                if ( handle && handle.apply && acceptData( cur ) ) {
9099                    event.result = handle.apply( cur, data );
9100                    if ( event.result === false ) {
9101                        event.preventDefault();
9102                    }
9103                }
9104            }
9105            event.type = type;
9106
9107            // If nobody prevented the default action, do it now
9108            if ( !onlyHandlers && !event.isDefaultPrevented() ) {
9109
9110                if ( ( !special._default ||
9111                    special._default.apply( eventPath.pop(), data ) === false ) &&
9112                    acceptData( elem ) ) {
9113
9114                    // Call a native DOM method on the target with the same name as the event.
9115                    // Don't do default actions on window, that's where global variables be (#6170)
9116                    if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) {
9117
9118                        // Don't re-trigger an onFOO event when we call its FOO() method
9119                        tmp = elem[ ontype ];
9120
9121                        if ( tmp ) {
9122                            elem[ ontype ] = null;
9123                        }
9124
9125                        // Prevent re-triggering of the same event, since we already bubbled it above
9126                        jQuery.event.triggered = type;
9127
9128                        if ( event.isPropagationStopped() ) {
9129                            lastElement.addEventListener( type, stopPropagationCallback );
9130                        }
9131
9132                        elem[ type ]();
9133
9134                        if ( event.isPropagationStopped() ) {
9135                            lastElement.removeEventListener( type, stopPropagationCallback );
9136                        }
9137
9138                        jQuery.event.triggered = undefined;
9139
9140                        if ( tmp ) {
9141                            elem[ ontype ] = tmp;
9142                        }
9143                    }
9144                }
9145            }
9146
9147            return event.result;
9148        },
9149
9150        // Piggyback on a donor event to simulate a different one
9151        // Used only for `focus(in | out)` events
9152        simulate: function( type, elem, event ) {
9153            var e = jQuery.extend(
9154                new jQuery.Event(),
9155                event,
9156                {
9157                    type: type,
9158                    isSimulated: true
9159                }
9160            );
9161
9162            jQuery.event.trigger( e, null, elem );
9163        }
9164
9165    } );
9166
9167    jQuery.fn.extend( {
9168
9169        trigger: function( type, data ) {
9170            return this.each( function() {
9171                jQuery.event.trigger( type, data, this );
9172            } );
9173        },
9174        triggerHandler: function( type, data ) {
9175            var elem = this[ 0 ];
9176            if ( elem ) {
9177                return jQuery.event.trigger( type, data, elem, true );
9178            }
9179        }
9180    } );
9181
9182
9183// Support: Firefox <=44
9184// Firefox doesn't have focus(in | out) events
vendor: 5,999 bytes, lines 9185-9360
9185// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787
9186//
9187// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1
9188// focus(in | out) events fire after focus & blur events,
9189// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order
9190// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857
9191    if ( !support.focusin ) {
9192        jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) {
9193
9194            // Attach a single capturing handler on the document while someone wants focusin/focusout
9195            var handler = function( event ) {
9196                jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) );
9197            };
9198
9199            jQuery.event.special[ fix ] = {
9200                setup: function() {
9201
9202                    // Handle: regular nodes (via `this.ownerDocument`), window
9203                    // (via `this.document`) & document (via `this`).
9204                    var doc = this.ownerDocument || this.document || this,
9205                        attaches = dataPriv.access( doc, fix );
9206
9207                    if ( !attaches ) {
9208                        doc.addEventListener( orig, handler, true );
9209                    }
9210                    dataPriv.access( doc, fix, ( attaches || 0 ) + 1 );
9211                },
9212                teardown: function() {
9213                    var doc = this.ownerDocument || this.document || this,
9214                        attaches = dataPriv.access( doc, fix ) - 1;
9215
9216                    if ( !attaches ) {
9217                        doc.removeEventListener( orig, handler, true );
9218                        dataPriv.remove( doc, fix );
9219
9220                    } else {
9221                        dataPriv.access( doc, fix, attaches );
9222                    }
9223                }
9224            };
9225        } );
9226    }
9227    var location = window.location;
9228
9229    var nonce = { guid: Date.now() };
9230
9231    var rquery = ( /\?/ );
9232
9233
9234
9235// Cross-browser xml parsing
9236    jQuery.parseXML = function( data ) {
9237        var xml, parserErrorElem;
9238        if ( !data || typeof data !== "string" ) {
9239            return null;
9240        }
9241
9242        // Support: IE 9 - 11 only
9243        // IE throws on parseFromString with invalid input.
9244        try {
9245            xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" );
9246        } catch ( e ) {}
9247
9248        parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ];
9249        if ( !xml || parserErrorElem ) {
9250            jQuery.error( "Invalid XML: " + (
9251                parserErrorElem ?
9252                    jQuery.map( parserErrorElem.childNodes, function( el ) {
9253                        return el.textContent;
9254                    } ).join( "\n" ) :
9255                    data
9256            ) );
9257        }
9258        return xml;
9259    };
9260
9261
9262    var
9263        rbracket = /\[\]$/,
9264        rCRLF = /\r?\n/g,
9265        rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
9266        rsubmittable = /^(?:input|select|textarea|keygen)/i;
9267
9268    function buildParams( prefix, obj, traditional, add ) {
9269        var name;
9270
9271        if ( Array.isArray( obj ) ) {
9272
9273            // Serialize array item.
9274            jQuery.each( obj, function( i, v ) {
9275                if ( traditional || rbracket.test( prefix ) ) {
9276
9277                    // Treat each array item as a scalar.
9278                    add( prefix, v );
9279
9280                } else {
9281
9282                    // Item is non-scalar (array or object), encode its numeric index.
9283                    buildParams(
9284                        prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]",
9285                        v,
9286                        traditional,
9287                        add
9288                    );
9289                }
9290            } );
9291
9292        } else if ( !traditional && toType( obj ) === "object" ) {
9293
9294            // Serialize object item.
9295            for ( name in obj ) {
9296                buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
9297            }
9298
9299        } else {
9300
9301            // Serialize scalar item.
9302            add( prefix, obj );
9303        }
9304    }
9305
9306// Serialize an array of form elements or a set of
9307// key/values into a query string
9308    jQuery.param = function( a, traditional ) {
9309        var prefix,
9310            s = [],
9311            add = function( key, valueOrFunction ) {
9312
9313                // If value is a function, invoke it and use its return value
9314                var value = isFunction( valueOrFunction ) ?
9315                    valueOrFunction() :
9316                    valueOrFunction;
9317
9318                s[ s.length ] = encodeURIComponent( key ) + "=" +
9319                    encodeURIComponent( value == null ? "" : value );
9320            };
9321
9322        if ( a == null ) {
9323            return "";
9324        }
9325
9326        // If an array was passed in, assume that it is an array of form elements.
9327        if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
9328
9329            // Serialize the form elements
9330            jQuery.each( a, function() {
9331                add( this.name, this.value );
9332            } );
9333
9334        } else {
9335
9336            // If traditional, encode the "old" way (the way 1.3.2 or older
9337            // did it), otherwise encode params recursively.
9338            for ( prefix in a ) {
9339                buildParams( prefix, a[ prefix ], traditional, add );
9340            }
9341        }
9342
9343        // Return the resulting serialization
9344        return s.join( "&" );
9345    };
9346
9347    jQuery.fn.extend( {
9348        serialize: function() {
9349            return jQuery.param( this.serializeArray() );
9350        },
9351        serializeArray: function() {
9352            return this.map( function() {
9353
9354                // Can add propHook for "elements" to filter or add form elements
9355                var elements = jQuery.prop( this, "elements" );
9356                return elements ? jQuery.makeArray( elements ) : this;
9357            } ).filter( function() {
9358                var type = this.type;
9359
9360                // Use .is( ":disabled" ) so that fieldset[disabled] w
vendor: 4,128 bytes, lines 9360-9470
9360orks
9361                return this.name && !jQuery( this ).is( ":disabled" ) &&
9362                    rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
9363                    ( this.checked || !rcheckableType.test( type ) );
9364            } ).map( function( _i, elem ) {
9365                var val = jQuery( this ).val();
9366
9367                if ( val == null ) {
9368                    return null;
9369                }
9370
9371                if ( Array.isArray( val ) ) {
9372                    return jQuery.map( val, function( val ) {
9373                        return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
9374                    } );
9375                }
9376
9377                return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
9378            } ).get();
9379        }
9380    } );
9381
9382
9383    var
9384        r20 = /%20/g,
9385        rhash = /#.*$/,
9386        rantiCache = /([?&])_=[^&]*/,
9387        rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
9388
9389        // #7653, #8125, #8152: local protocol detection
9390        rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
9391        rnoContent = /^(?:GET|HEAD)$/,
9392        rprotocol = /^\/\//,
9393
9394        /* Prefilters
9395	 * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
9396	 * 2) These are called:
9397	 *    - BEFORE asking for a transport
9398	 *    - AFTER param serialization (s.data is a string if s.processData is true)
9399	 * 3) key is the dataType
9400	 * 4) the catchall symbol "*" can be used
9401	 * 5) execution will start with transport dataType and THEN continue down to "*" if needed
9402	 */
9403        prefilters = {},
9404
9405        /* Transports bindings
9406	 * 1) key is the dataType
9407	 * 2) the catchall symbol "*" can be used
9408	 * 3) selection will start with transport dataType and THEN go to "*" if needed
9409	 */
9410        transports = {},
9411
9412        // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
9413        allTypes = "*/".concat( "*" ),
9414
9415        // Anchor tag for parsing the document origin
9416        originAnchor = document.createElement( "a" );
9417
9418    originAnchor.href = location.href;
9419
9420// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
9421    function addToPrefiltersOrTransports( structure ) {
9422
9423        // dataTypeExpression is optional and defaults to "*"
9424        return function( dataTypeExpression, func ) {
9425
9426            if ( typeof dataTypeExpression !== "string" ) {
9427                func = dataTypeExpression;
9428                dataTypeExpression = "*";
9429            }
9430
9431            var dataType,
9432                i = 0,
9433                dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || [];
9434
9435            if ( isFunction( func ) ) {
9436
9437                // For each dataType in the dataTypeExpression
9438                while ( ( dataType = dataTypes[ i++ ] ) ) {
9439
9440                    // Prepend if requested
9441                    if ( dataType[ 0 ] === "+" ) {
9442                        dataType = dataType.slice( 1 ) || "*";
9443                        ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func );
9444
9445                        // Otherwise append
9446                    } else {
9447                        ( structure[ dataType ] = structure[ dataType ] || [] ).push( func );
9448                    }
9449                }
9450            }
9451        };
9452    }
9453
9454// Base inspection function for prefilters and transports
9455    function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
9456
9457        var inspected = {},
9458            seekingTransport = ( structure === transports );
9459
9460        function inspect( dataType ) {
9461            var selected;
9462            inspected[ dataType ] = true;
9463            jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
9464                var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
9465                if ( typeof dataTypeOrTransport === "string" &&
9466                    !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
9467
9468                    options.dataTypes.unshift( dataTypeOrTransport );
9469                    inspect( dataTypeOrTransport );
9470                    return false;
vendor: 15,305 bytes, lines 9471-9908
9471                } else if ( seekingTransport ) {
9472                    return !( selected = dataTypeOrTransport );
9473                }
9474            } );
9475            return selected;
9476        }
9477
9478        return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
9479    }
9480
9481// A special extend for ajax options
9482// that takes "flat" options (not to be deep extended)
9483// Fixes #9887
9484    function ajaxExtend( target, src ) {
9485        var key, deep,
9486            flatOptions = jQuery.ajaxSettings.flatOptions || {};
9487
9488        for ( key in src ) {
9489            if ( src[ key ] !== undefined ) {
9490                ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
9491            }
9492        }
9493        if ( deep ) {
9494            jQuery.extend( true, target, deep );
9495        }
9496
9497        return target;
9498    }
9499
9500    /* Handles responses to an ajax request:
9501 * - finds the right dataType (mediates between content-type and expected dataType)
9502 * - returns the corresponding response
9503 */
9504    function ajaxHandleResponses( s, jqXHR, responses ) {
9505
9506        var ct, type, finalDataType, firstDataType,
9507            contents = s.contents,
9508            dataTypes = s.dataTypes;
9509
9510        // Remove auto dataType and get content-type in the process
9511        while ( dataTypes[ 0 ] === "*" ) {
9512            dataTypes.shift();
9513            if ( ct === undefined ) {
9514                ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" );
9515            }
9516        }
9517
9518        // Check if we're dealing with a known content-type
9519        if ( ct ) {
9520            for ( type in contents ) {
9521                if ( contents[ type ] && contents[ type ].test( ct ) ) {
9522                    dataTypes.unshift( type );
9523                    break;
9524                }
9525            }
9526        }
9527
9528        // Check to see if we have a response for the expected dataType
9529        if ( dataTypes[ 0 ] in responses ) {
9530            finalDataType = dataTypes[ 0 ];
9531        } else {
9532
9533            // Try convertible dataTypes
9534            for ( type in responses ) {
9535                if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) {
9536                    finalDataType = type;
9537                    break;
9538                }
9539                if ( !firstDataType ) {
9540                    firstDataType = type;
9541                }
9542            }
9543
9544            // Or just use first one
9545            finalDataType = finalDataType || firstDataType;
9546        }
9547
9548        // If we found a dataType
9549        // We add the dataType to the list if needed
9550        // and return the corresponding response
9551        if ( finalDataType ) {
9552            if ( finalDataType !== dataTypes[ 0 ] ) {
9553                dataTypes.unshift( finalDataType );
9554            }
9555            return responses[ finalDataType ];
9556        }
9557    }
9558
9559    /* Chain conversions given the request and the original response
9560 * Also sets the responseXXX fields on the jqXHR instance
9561 */
9562    function ajaxConvert( s, response, jqXHR, isSuccess ) {
9563        var conv2, current, conv, tmp, prev,
9564            converters = {},
9565
9566            // Work with a copy of dataTypes in case we need to modify it for conversion
9567            dataTypes = s.dataTypes.slice();
9568
9569        // Create converters map with lowercased keys
9570        if ( dataTypes[ 1 ] ) {
9571            for ( conv in s.converters ) {
9572                converters[ conv.toLowerCase() ] = s.converters[ conv ];
9573            }
9574        }
9575
9576        current = dataTypes.shift();
9577
9578        // Convert to each sequential dataType
9579        while ( current ) {
9580
9581            if ( s.responseFields[ current ] ) {
9582                jqXHR[ s.responseFields[ current ] ] = response;
9583            }
9584
9585            // Apply the dataFilter if provided
9586            if ( !prev && isSuccess && s.dataFilter ) {
9587                response = s.dataFilter( response, s.dataType );
9588            }
9589
9590            prev = current;
9591            current = dataTypes.shift();
9592
9593            if ( current ) {
9594
9595                // There's only work to do if current dataType is non-auto
9596                if ( current === "*" ) {
9597
9598                    current = prev;
9599
9600                    // Convert response if prev dataType is non-auto and differs from current
9601                } else if ( prev !== "*" && prev !== current ) {
9602
9603                    // Seek a direct converter
9604                    conv = converters[ prev + " " + current ] || converters[ "* " + current ];
9605
9606                    // If none found, seek a pair
9607                    if ( !conv ) {
9608                        for ( conv2 in converters ) {
9609
9610                            // If conv2 outputs current
9611                            tmp = conv2.split( " " );
9612                            if ( tmp[ 1 ] === current ) {
9613
9614                                // If prev can be converted to accepted input
9615                                conv = converters[ prev + " " + tmp[ 0 ] ] ||
9616                                    converters[ "* " + tmp[ 0 ] ];
9617                                if ( conv ) {
9618
9619                                    // Condense equivalence converters
9620                                    if ( conv === true ) {
9621                                        conv = converters[ conv2 ];
9622
9623                                        // Otherwise, insert the intermediate dataType
9624                                    } else if ( converters[ conv2 ] !== true ) {
9625                                        current = tmp[ 0 ];
9626                                        dataTypes.unshift( tmp[ 1 ] );
9627                                    }
9628                                    break;
9629                                }
9630                            }
9631                        }
9632                    }
9633
9634                    // Apply converter (if not an equivalence)
9635                    if ( conv !== true ) {
9636
9637                        // Unless errors are allowed to bubble, catch and return them
9638                        if ( conv && s.throws ) {
9639                            response = conv( response );
9640                        } else {
9641                            try {
9642                                response = conv( response );
9643                            } catch ( e ) {
9644                                return {
9645                                    state: "parsererror",
9646                                    error: conv ? e : "No conversion from " + prev + " to " + current
9647                                };
9648                            }
9649                        }
9650                    }
9651                }
9652            }
9653        }
9654
9655        return { state: "success", data: response };
9656    }
9657
9658    jQuery.extend( {
9659
9660        // Counter for holding the number of active queries
9661        active: 0,
9662
9663        // Last-Modified header cache for next request
9664        lastModified: {},
9665        etag: {},
9666
9667        ajaxSettings: {
9668            url: location.href,
9669            type: "GET",
9670            isLocal: rlocalProtocol.test( location.protocol ),
9671            global: true,
9672            processData: true,
9673            async: true,
9674            contentType: "application/x-www-form-urlencoded; charset=UTF-8",
9675
9676            /*
9677		timeout: 0,
9678		data: null,
9679		dataType: null,
9680		username: null,
9681		password: null,
9682		cache: null,
9683		throws: false,
9684		traditional: false,
9685		headers: {},
9686		*/
9687
9688            accepts: {
9689                "*": allTypes,
9690                text: "text/plain",
9691                html: "text/html",
9692                xml: "application/xml, text/xml",
9693                json: "application/json, text/javascript"
9694            },
9695
9696            contents: {
9697                xml: /\bxml\b/,
9698                html: /\bhtml/,
9699                json: /\bjson\b/
9700            },
9701
9702            responseFields: {
9703                xml: "responseXML",
9704                text: "responseText",
9705                json: "responseJSON"
9706            },
9707
9708            // Data converters
9709            // Keys separate source (or catchall "*") and destination types with a single space
9710            converters: {
9711
9712                // Convert anything to text
9713                "* text": String,
9714
9715                // Text to html (true = no transformation)
9716                "text html": true,
9717
9718                // Evaluate text as a json expression
9719                "text json": JSON.parse,
9720
9721                // Parse text as xml
9722                "text xml": jQuery.parseXML
9723            },
9724
9725            // For options that shouldn't be deep extended:
9726            // you can add your own custom options here if
9727            // and when you create one that shouldn't be
9728            // deep extended (see ajaxExtend)
9729            flatOptions: {
9730                url: true,
9731                context: true
9732            }
9733        },
9734
9735        // Creates a full fledged settings object into target
9736        // with both ajaxSettings and settings fields.
9737        // If target is omitted, writes into ajaxSettings.
9738        ajaxSetup: function( target, settings ) {
9739            return settings ?
9740
9741                // Building a settings object
9742                ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
9743
9744                // Extending ajaxSettings
9745                ajaxExtend( jQuery.ajaxSettings, target );
9746        },
9747
9748        ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
9749        ajaxTransport: addToPrefiltersOrTransports( transports ),
9750
9751        // Main method
9752        ajax: function( url, options ) {
9753
9754            // If url is an object, simulate pre-1.5 signature
9755            if ( typeof url === "object" ) {
9756                options = url;
9757                url = undefined;
9758            }
9759
9760            // Force options to be an object
9761            options = options || {};
9762
9763            var transport,
9764
9765                // URL without anti-cache param
9766                cacheURL,
9767
9768                // Response headers
9769                responseHeadersString,
9770                responseHeaders,
9771
9772                // timeout handle
9773                timeoutTimer,
9774
9775                // Url cleanup var
9776                urlAnchor,
9777
9778                // Request state (becomes false upon send and true upon completion)
9779                completed,
9780
9781                // To know if global events are to be dispatched
9782                fireGlobals,
9783
9784                // Loop variable
9785                i,
9786
9787                // uncached part of the url
9788                uncached,
9789
9790                // Create the final options object
9791                s = jQuery.ajaxSetup( {}, options ),
9792
9793                // Callbacks context
9794                callbackContext = s.context || s,
9795
9796                // Context for global events is callbackContext if it is a DOM node or jQuery collection
9797                globalEventContext = s.context &&
9798                ( callbackContext.nodeType || callbackContext.jquery ) ?
9799                    jQuery( callbackContext ) :
9800                    jQuery.event,
9801
9802                // Deferreds
9803                deferred = jQuery.Deferred(),
9804                completeDeferred = jQuery.Callbacks( "once memory" ),
9805
9806                // Status-dependent callbacks
9807                statusCode = s.statusCode || {},
9808
9809                // Headers (they are sent all at once)
9810                requestHeaders = {},
9811                requestHeadersNames = {},
9812
9813                // Default abort message
9814                strAbort = "canceled",
9815
9816                // Fake xhr
9817                jqXHR = {
9818                    readyState: 0,
9819
9820                    // Builds headers hashtable if needed
9821                    getResponseHeader: function( key ) {
9822                        var match;
9823                        if ( completed ) {
9824                            if ( !responseHeaders ) {
9825                                responseHeaders = {};
9826                                while ( ( match = rheaders.exec( responseHeadersString ) ) ) {
9827                                    responseHeaders[ match[ 1 ].toLowerCase() + " " ] =
9828                                        ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] )
9829                                            .concat( match[ 2 ] );
9830                                }
9831                            }
9832                            match = responseHeaders[ key.toLowerCase() + " " ];
9833                        }
9834                        return match == null ? null : match.join( ", " );
9835                    },
9836
9837                    // Raw string
9838                    getAllResponseHeaders: function() {
9839                        return completed ? responseHeadersString : null;
9840                    },
9841
9842                    // Caches the header
9843                    setRequestHeader: function( name, value ) {
9844                        if ( completed == null ) {
9845                            name = requestHeadersNames[ name.toLowerCase() ] =
9846                                requestHeadersNames[ name.toLowerCase() ] || name;
9847                            requestHeaders[ name ] = value;
9848                        }
9849                        return this;
9850                    },
9851
9852                    // Overrides response content-type header
9853                    overrideMimeType: function( type ) {
9854                        if ( completed == null ) {
9855                            s.mimeType = type;
9856                        }
9857                        return this;
9858                    },
9859
9860                    // Status-dependent callbacks
9861                    statusCode: function( map ) {
9862                        var code;
9863                        if ( map ) {
9864                            if ( completed ) {
9865
9866                                // Execute the appropriate callbacks
9867                                jqXHR.always( map[ jqXHR.status ] );
9868                            } else {
9869
9870                                // Lazy-add the new callbacks in a way that preserves old ones
9871                                for ( code in map ) {
9872                                    statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
9873                                }
9874                            }
9875                        }
9876                        return this;
9877                    },
9878
9879                    // Cancel the request
9880                    abort: function( statusText ) {
9881                        var finalText = statusText || strAbort;
9882                        if ( transport ) {
9883                            transport.abort( finalText );
9884                        }
9885                        done( 0, finalText );
9886                        return this;
9887                    }
9888                };
9889
9890            // Attach deferreds
9891            deferred.promise( jqXHR );
9892
9893            // Add protocol if not provided (prefilters might expect it)
9894            // Handle falsy url in the settings object (#10093: consistency with old signature)
9895            // We also use the url parameter if available
9896            s.url = ( ( url || s.url || location.href ) + "" )
9897                .replace( rprotocol, location.protocol + "//" );
9898
9899            // Alias method option to type as per ticket #12004
9900            s.type = options.method || options.type || s.method || s.type;
9901
9902            // Extract dataTypes list
9903            s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ];
9904
9905            // A cross-domain request is in order when the origin doesn't match the current origin.
9906            if ( s.crossDomain == null ) {
9907                urlAnchor = document.createElement( "a" );
9908
vendor: 41,672 bytes, lines 9909-11038
9909                // Support: IE <=8 - 11, Edge 12 - 15
9910                // IE throws exception on accessing the href property if url is malformed,
9911                // e.g. http://example.com:80x/
9912                try {
9913                    urlAnchor.href = s.url;
9914
9915                    // Support: IE <=8 - 11 only
9916                    // Anchor's host property isn't correctly set when s.url is relative
9917                    urlAnchor.href = urlAnchor.href;
9918                    s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !==
9919                        urlAnchor.protocol + "//" + urlAnchor.host;
9920                } catch ( e ) {
9921
9922                    // If there is an error parsing the URL, assume it is crossDomain,
9923                    // it can be rejected by the transport if it is invalid
9924                    s.crossDomain = true;
9925                }
9926            }
9927
9928            // Convert data if not already a string
9929            if ( s.data && s.processData && typeof s.data !== "string" ) {
9930                s.data = jQuery.param( s.data, s.traditional );
9931            }
9932
9933            // Apply prefilters
9934            inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
9935
9936            // If request was aborted inside a prefilter, stop there
9937            if ( completed ) {
9938                return jqXHR;
9939            }
9940
9941            // We can fire global events as of now if asked to
9942            // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118)
9943            fireGlobals = jQuery.event && s.global;
9944
9945            // Watch for a new set of requests
9946            if ( fireGlobals && jQuery.active++ === 0 ) {
9947                jQuery.event.trigger( "ajaxStart" );
9948            }
9949
9950            // Uppercase the type
9951            s.type = s.type.toUpperCase();
9952
9953            // Determine if request has content
9954            s.hasContent = !rnoContent.test( s.type );
9955
9956            // Save the URL in case we're toying with the If-Modified-Since
9957            // and/or If-None-Match header later on
9958            // Remove hash to simplify url manipulation
9959            cacheURL = s.url.replace( rhash, "" );
9960
9961            // More options handling for requests with no content
9962            if ( !s.hasContent ) {
9963
9964                // Remember the hash so we can put it back
9965                uncached = s.url.slice( cacheURL.length );
9966
9967                // If data is available and should be processed, append data to url
9968                if ( s.data && ( s.processData || typeof s.data === "string" ) ) {
9969                    cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data;
9970
9971                    // #9682: remove data so that it's not used in an eventual retry
9972                    delete s.data;
9973                }
9974
9975                // Add or update anti-cache param if needed
9976                if ( s.cache === false ) {
9977                    cacheURL = cacheURL.replace( rantiCache, "$1" );
9978                    uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) +
9979                        uncached;
9980                }
9981
9982                // Put hash and anti-cache on the URL that will be requested (gh-1732)
9983                s.url = cacheURL + uncached;
9984
9985                // Change '%20' to '+' if this is encoded form body content (gh-2658)
9986            } else if ( s.data && s.processData &&
9987                ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) {
9988                s.data = s.data.replace( r20, "+" );
9989            }
9990
9991            // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
9992            if ( s.ifModified ) {
9993                if ( jQuery.lastModified[ cacheURL ] ) {
9994                    jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
9995                }
9996                if ( jQuery.etag[ cacheURL ] ) {
9997                    jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
9998                }
9999            }
10000
10001            // Set the correct header, if data is being sent
10002            if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
10003                jqXHR.setRequestHeader( "Content-Type", s.contentType );
10004            }
10005
10006            // Set the Accepts header for the server, depending on the dataType
10007            jqXHR.setRequestHeader(
10008                "Accept",
10009                s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ?
10010                    s.accepts[ s.dataTypes[ 0 ] ] +
10011                    ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
10012                    s.accepts[ "*" ]
10013            );
10014
10015            // Check for headers option
10016            for ( i in s.headers ) {
10017                jqXHR.setRequestHeader( i, s.headers[ i ] );
10018            }
10019
10020            // Allow custom headers/mimetypes and early abort
10021            if ( s.beforeSend &&
10022                ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) {
10023
10024                // Abort if not done already and return
10025                return jqXHR.abort();
10026            }
10027
10028            // Aborting is no longer a cancellation
10029            strAbort = "abort";
10030
10031            // Install callbacks on deferreds
10032            completeDeferred.add( s.complete );
10033            jqXHR.done( s.success );
10034            jqXHR.fail( s.error );
10035
10036            // Get transport
10037            transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
10038
10039            // If no transport, we auto-abort
10040            if ( !transport ) {
10041                done( -1, "No Transport" );
10042            } else {
10043                jqXHR.readyState = 1;
10044
10045                // Send global event
10046                if ( fireGlobals ) {
10047                    globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
10048                }
10049
10050                // If request was aborted inside ajaxSend, stop there
10051                if ( completed ) {
10052                    return jqXHR;
10053                }
10054
10055                // Timeout
10056                if ( s.async && s.timeout > 0 ) {
10057                    timeoutTimer = window.setTimeout( function() {
10058                        jqXHR.abort( "timeout" );
10059                    }, s.timeout );
10060                }
10061
10062                try {
10063                    completed = false;
10064                    transport.send( requestHeaders, done );
10065                } catch ( e ) {
10066
10067                    // Rethrow post-completion exceptions
10068                    if ( completed ) {
10069                        throw e;
10070                    }
10071
10072                    // Propagate others as results
10073                    done( -1, e );
10074                }
10075            }
10076
10077            // Callback for when everything is done
10078            function done( status, nativeStatusText, responses, headers ) {
10079                var isSuccess, success, error, response, modified,
10080                    statusText = nativeStatusText;
10081
10082                // Ignore repeat invocations
10083                if ( completed ) {
10084                    return;
10085                }
10086
10087                completed = true;
10088
10089                // Clear timeout if it exists
10090                if ( timeoutTimer ) {
10091                    window.clearTimeout( timeoutTimer );
10092                }
10093
10094                // Dereference transport for early garbage collection
10095                // (no matter how long the jqXHR object will be used)
10096                transport = undefined;
10097
10098                // Cache response headers
10099                responseHeadersString = headers || "";
10100
10101                // Set readyState
10102                jqXHR.readyState = status > 0 ? 4 : 0;
10103
10104                // Determine if successful
10105                isSuccess = status >= 200 && status < 300 || status === 304;
10106
10107                // Get response data
10108                if ( responses ) {
10109                    response = ajaxHandleResponses( s, jqXHR, responses );
10110                }
10111
10112                // Use a noop converter for missing script but not if jsonp
10113                if ( !isSuccess &&
10114                    jQuery.inArray( "script", s.dataTypes ) > -1 &&
10115                    jQuery.inArray( "json", s.dataTypes ) < 0 ) {
10116                    s.converters[ "text script" ] = function() {};
10117                }
10118
10119                // Convert no matter what (that way responseXXX fields are always set)
10120                response = ajaxConvert( s, response, jqXHR, isSuccess );
10121
10122                // If successful, handle type chaining
10123                if ( isSuccess ) {
10124
10125                    // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
10126                    if ( s.ifModified ) {
10127                        modified = jqXHR.getResponseHeader( "Last-Modified" );
10128                        if ( modified ) {
10129                            jQuery.lastModified[ cacheURL ] = modified;
10130                        }
10131                        modified = jqXHR.getResponseHeader( "etag" );
10132                        if ( modified ) {
10133                            jQuery.etag[ cacheURL ] = modified;
10134                        }
10135                    }
10136
10137                    // if no content
10138                    if ( status === 204 || s.type === "HEAD" ) {
10139                        statusText = "nocontent";
10140
10141                        // if not modified
10142                    } else if ( status === 304 ) {
10143                        statusText = "notmodified";
10144
10145                        // If we have data, let's convert it
10146                    } else {
10147                        statusText = response.state;
10148                        success = response.data;
10149                        error = response.error;
10150                        isSuccess = !error;
10151                    }
10152                } else {
10153
10154                    // Extract error from statusText and normalize for non-aborts
10155                    error = statusText;
10156                    if ( status || !statusText ) {
10157                        statusText = "error";
10158                        if ( status < 0 ) {
10159                            status = 0;
10160                        }
10161                    }
10162                }
10163
10164                // Set data for the fake xhr object
10165                jqXHR.status = status;
10166                jqXHR.statusText = ( nativeStatusText || statusText ) + "";
10167
10168                // Success/Error
10169                if ( isSuccess ) {
10170                    deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
10171                } else {
10172                    deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
10173                }
10174
10175                // Status-dependent callbacks
10176                jqXHR.statusCode( statusCode );
10177                statusCode = undefined;
10178
10179                if ( fireGlobals ) {
10180                    globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
10181                        [ jqXHR, s, isSuccess ? success : error ] );
10182                }
10183
10184                // Complete
10185                completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
10186
10187                if ( fireGlobals ) {
10188                    globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
10189
10190                    // Handle the global AJAX counter
10191                    if ( !( --jQuery.active ) ) {
10192                        jQuery.event.trigger( "ajaxStop" );
10193                    }
10194                }
10195            }
10196
10197            return jqXHR;
10198        },
10199
10200        getJSON: function( url, data, callback ) {
10201            return jQuery.get( url, data, callback, "json" );
10202        },
10203
10204        getScript: function( url, callback ) {
10205            return jQuery.get( url, undefined, callback, "script" );
10206        }
10207    } );
10208
10209    jQuery.each( [ "get", "post" ], function( _i, method ) {
10210        jQuery[ method ] = function( url, data, callback, type ) {
10211
10212            // Shift arguments if data argument was omitted
10213            if ( isFunction( data ) ) {
10214                type = type || callback;
10215                callback = data;
10216                data = undefined;
10217            }
10218
10219            // The url can be an options object (which then must have .url)
10220            return jQuery.ajax( jQuery.extend( {
10221                url: url,
10222                type: method,
10223                dataType: type,
10224                data: data,
10225                success: callback
10226            }, jQuery.isPlainObject( url ) && url ) );
10227        };
10228    } );
10229
10230    jQuery.ajaxPrefilter( function( s ) {
10231        var i;
10232        for ( i in s.headers ) {
10233            if ( i.toLowerCase() === "content-type" ) {
10234                s.contentType = s.headers[ i ] || "";
10235            }
10236        }
10237    } );
10238
10239
10240    jQuery._evalUrl = function( url, options, doc ) {
10241        return jQuery.ajax( {
10242            url: url,
10243
10244            // Make this explicit, since user can override this through ajaxSetup (#11264)
10245            type: "GET",
10246            dataType: "script",
10247            cache: true,
10248            async: false,
10249            global: false,
10250
10251            // Only evaluate the response if it is successful (gh-4126)
10252            // dataFilter is not invoked for failure responses, so using it instead
10253            // of the default converter is kludgy but it works.
10254            converters: {
10255                "text script": function() {}
10256            },
10257            dataFilter: function( response ) {
10258                jQuery.globalEval( response, options, doc );
10259            }
10260        } );
10261    };
10262
10263
10264    jQuery.fn.extend( {
10265        wrapAll: function( html ) {
10266            var wrap;
10267
10268            if ( this[ 0 ] ) {
10269                if ( isFunction( html ) ) {
10270                    html = html.call( this[ 0 ] );
10271                }
10272
10273                // The elements to wrap the target around
10274                wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
10275
10276                if ( this[ 0 ].parentNode ) {
10277                    wrap.insertBefore( this[ 0 ] );
10278                }
10279
10280                wrap.map( function() {
10281                    var elem = this;
10282
10283                    while ( elem.firstElementChild ) {
10284                        elem = elem.firstElementChild;
10285                    }
10286
10287                    return elem;
10288                } ).append( this );
10289            }
10290
10291            return this;
10292        },
10293
10294        wrapInner: function( html ) {
10295            if ( isFunction( html ) ) {
10296                return this.each( function( i ) {
10297                    jQuery( this ).wrapInner( html.call( this, i ) );
10298                } );
10299            }
10300
10301            return this.each( function() {
10302                var self = jQuery( this ),
10303                    contents = self.contents();
10304
10305                if ( contents.length ) {
10306                    contents.wrapAll( html );
10307
10308                } else {
10309                    self.append( html );
10310                }
10311            } );
10312        },
10313
10314        wrap: function( html ) {
10315            var htmlIsFunction = isFunction( html );
10316
10317            return this.each( function( i ) {
10318                jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html );
10319            } );
10320        },
10321
10322        unwrap: function( selector ) {
10323            this.parent( selector ).not( "body" ).each( function() {
10324                jQuery( this ).replaceWith( this.childNodes );
10325            } );
10326            return this;
10327        }
10328    } );
10329
10330
10331    jQuery.expr.pseudos.hidden = function( elem ) {
10332        return !jQuery.expr.pseudos.visible( elem );
10333    };
10334    jQuery.expr.pseudos.visible = function( elem ) {
10335        return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
10336    };
10337
10338
10339
10340
10341    jQuery.ajaxSettings.xhr = function() {
10342        try {
10343            return new window.XMLHttpRequest();
10344        } catch ( e ) {}
10345    };
10346
10347    var xhrSuccessStatus = {
10348
10349            // File protocol always yields status code 0, assume 200
10350            0: 200,
10351
10352            // Support: IE <=9 only
10353            // #1450: sometimes IE returns 1223 when it should be 204
10354            1223: 204
10355        },
10356        xhrSupported = jQuery.ajaxSettings.xhr();
10357
10358    support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
10359    support.ajax = xhrSupported = !!xhrSupported;
10360
10361    jQuery.ajaxTransport( function( options ) {
10362        var callback, errorCallback;
10363
10364        // Cross domain only allowed if supported through XMLHttpRequest
10365        if ( support.cors || xhrSupported && !options.crossDomain ) {
10366            return {
10367                send: function( headers, complete ) {
10368                    var i,
10369                        xhr = options.xhr();
10370
10371                    xhr.open(
10372                        options.type,
10373                        options.url,
10374                        options.async,
10375                        options.username,
10376                        options.password
10377                    );
10378
10379                    // Apply custom fields if provided
10380                    if ( options.xhrFields ) {
10381                        for ( i in options.xhrFields ) {
10382                            xhr[ i ] = options.xhrFields[ i ];
10383                        }
10384                    }
10385
10386                    // Override mime type if needed
10387                    if ( options.mimeType && xhr.overrideMimeType ) {
10388                        xhr.overrideMimeType( options.mimeType );
10389                    }
10390
10391                    // X-Requested-With header
10392                    // For cross-domain requests, seeing as conditions for a preflight are
10393                    // akin to a jigsaw puzzle, we simply never set it to be sure.
10394                    // (it can always be set on a per-request basis or even using ajaxSetup)
10395                    // For same-domain requests, won't change header if already provided.
10396                    if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) {
10397                        headers[ "X-Requested-With" ] = "XMLHttpRequest";
10398                    }
10399
10400                    // Set headers
10401                    for ( i in headers ) {
10402                        xhr.setRequestHeader( i, headers[ i ] );
10403                    }
10404
10405                    // Callback
10406                    callback = function( type ) {
10407                        return function() {
10408                            if ( callback ) {
10409                                callback = errorCallback = xhr.onload =
10410                                    xhr.onerror = xhr.onabort = xhr.ontimeout =
10411                                        xhr.onreadystatechange = null;
10412
10413                                if ( type === "abort" ) {
10414                                    xhr.abort();
10415                                } else if ( type === "error" ) {
10416
10417                                    // Support: IE <=9 only
10418                                    // On a manual native abort, IE9 throws
10419                                    // errors on any property access that is not readyState
10420                                    if ( typeof xhr.status !== "number" ) {
10421                                        complete( 0, "error" );
10422                                    } else {
10423                                        complete(
10424
10425                                            // File: protocol always yields status 0; see #8605, #14207
10426                                            xhr.status,
10427                                            xhr.statusText
10428                                        );
10429                                    }
10430                                } else {
10431                                    complete(
10432                                        xhrSuccessStatus[ xhr.status ] || xhr.status,
10433                                        xhr.statusText,
10434
10435                                        // Support: IE <=9 only
10436                                        // IE9 has no XHR2 but throws on binary (trac-11426)
10437                                        // For XHR2 non-text, let the caller handle it (gh-2498)
10438                                        ( xhr.responseType || "text" ) !== "text"  ||
10439                                        typeof xhr.responseText !== "string" ?
10440                                            { binary: xhr.response } :
10441                                            { text: xhr.responseText },
10442                                        xhr.getAllResponseHeaders()
10443                                    );
10444                                }
10445                            }
10446                        };
10447                    };
10448
10449                    // Listen to events
10450                    xhr.onload = callback();
10451                    errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" );
10452
10453                    // Support: IE 9 only
10454                    // Use onreadystatechange to replace onabort
10455                    // to handle uncaught aborts
10456                    if ( xhr.onabort !== undefined ) {
10457                        xhr.onabort = errorCallback;
10458                    } else {
10459                        xhr.onreadystatechange = function() {
10460
10461                            // Check readyState before timeout as it changes
10462                            if ( xhr.readyState === 4 ) {
10463
10464                                // Allow onerror to be called first,
10465                                // but that will not handle a native abort
10466                                // Also, save errorCallback to a variable
10467                                // as xhr.onerror cannot be accessed
10468                                window.setTimeout( function() {
10469                                    if ( callback ) {
10470                                        errorCallback();
10471                                    }
10472                                } );
10473                            }
10474                        };
10475                    }
10476
10477                    // Create the abort callback
10478                    callback = callback( "abort" );
10479
10480                    try {
10481
10482                        // Do send the request (this may raise an exception)
10483                        xhr.send( options.hasContent && options.data || null );
10484                    } catch ( e ) {
10485
10486                        // #14683: Only rethrow if this hasn't been notified as an error yet
10487                        if ( callback ) {
10488                            throw e;
10489                        }
10490                    }
10491                },
10492
10493                abort: function() {
10494                    if ( callback ) {
10495                        callback();
10496                    }
10497                }
10498            };
10499        }
10500    } );
10501
10502
10503
10504
10505// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432)
10506    jQuery.ajaxPrefilter( function( s ) {
10507        if ( s.crossDomain ) {
10508            s.contents.script = false;
10509        }
10510    } );
10511
10512// Install script dataType
10513    jQuery.ajaxSetup( {
10514        accepts: {
10515            script: "text/javascript, application/javascript, " +
10516                "application/ecmascript, application/x-ecmascript"
10517        },
10518        contents: {
10519            script: /\b(?:java|ecma)script\b/
10520        },
10521        converters: {
10522            "text script": function( text ) {
10523                jQuery.globalEval( text );
10524                return text;
10525            }
10526        }
10527    } );
10528
10529// Handle cache's special case and crossDomain
10530    jQuery.ajaxPrefilter( "script", function( s ) {
10531        if ( s.cache === undefined ) {
10532            s.cache = false;
10533        }
10534        if ( s.crossDomain ) {
10535            s.type = "GET";
10536        }
10537    } );
10538
10539// Bind script tag hack transport
10540    jQuery.ajaxTransport( "script", function( s ) {
10541
10542        // This transport only deals with cross domain or forced-by-attrs requests
10543        if ( s.crossDomain || s.scriptAttrs ) {
10544            var script, callback;
10545            return {
10546                send: function( _, complete ) {
10547                    script = jQuery( "<script>" )
10548                        .attr( s.scriptAttrs || {} )
10549                        .prop( { charset: s.scriptCharset, src: s.url } )
10550                        .on( "load error", callback = function( evt ) {
10551                            script.remove();
10552                            callback = null;
10553                            if ( evt ) {
10554                                complete( evt.type === "error" ? 404 : 200, evt.type );
10555                            }
10556                        } );
10557
10558                    // Use native DOM manipulation to avoid our domManip AJAX trickery
10559                    document.head.appendChild( script[ 0 ] );
10560                },
10561                abort: function() {
10562                    if ( callback ) {
10563                        callback();
10564                    }
10565                }
10566            };
10567        }
10568    } );
10569
10570
10571
10572
10573    var oldCallbacks = [],
10574        rjsonp = /(=)\?(?=&|$)|\?\?/;
10575
10576// Default jsonp settings
10577    jQuery.ajaxSetup( {
10578        jsonp: "callback",
10579        jsonpCallback: function() {
10580            var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) );
10581            this[ callback ] = true;
10582            return callback;
10583        }
10584    } );
10585
10586// Detect, normalize options and install callbacks for jsonp requests
10587    jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
10588
10589        var callbackName, overwritten, responseContainer,
10590            jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
10591                    "url" :
10592                    typeof s.data === "string" &&
10593                    ( s.contentType || "" )
10594                        .indexOf( "application/x-www-form-urlencoded" ) === 0 &&
10595                    rjsonp.test( s.data ) && "data"
10596            );
10597
10598        // Handle iff the expected data type is "jsonp" or we have a parameter to set
10599        if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
10600
10601            // Get callback name, remembering preexisting value associated with it
10602            callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ?
10603                s.jsonpCallback() :
10604                s.jsonpCallback;
10605
10606            // Insert callback into url or form data
10607            if ( jsonProp ) {
10608                s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
10609            } else if ( s.jsonp !== false ) {
10610                s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
10611            }
10612
10613            // Use data converter to retrieve json after script execution
10614            s.converters[ "script json" ] = function() {
10615                if ( !responseContainer ) {
10616                    jQuery.error( callbackName + " was not called" );
10617                }
10618                return responseContainer[ 0 ];
10619            };
10620
10621            // Force json dataType
10622            s.dataTypes[ 0 ] = "json";
10623
10624            // Install callback
10625            overwritten = window[ callbackName ];
10626            window[ callbackName ] = function() {
10627                responseContainer = arguments;
10628            };
10629
10630            // Clean-up function (fires after converters)
10631            jqXHR.always( function() {
10632
10633                // If previous value didn't exist - remove it
10634                if ( overwritten === undefined ) {
10635                    jQuery( window ).removeProp( callbackName );
10636
10637                    // Otherwise restore preexisting value
10638                } else {
10639                    window[ callbackName ] = overwritten;
10640                }
10641
10642                // Save back as free
10643                if ( s[ callbackName ] ) {
10644
10645                    // Make sure that re-using the options doesn't screw things around
10646                    s.jsonpCallback = originalSettings.jsonpCallback;
10647
10648                    // Save the callback name for future use
10649                    oldCallbacks.push( callbackName );
10650                }
10651
10652                // Call if it was a function and we have a response
10653                if ( responseContainer && isFunction( overwritten ) ) {
10654                    overwritten( responseContainer[ 0 ] );
10655                }
10656
10657                responseContainer = overwritten = undefined;
10658            } );
10659
10660            // Delegate to script
10661            return "script";
10662        }
10663    } );
10664
10665
10666
10667
10668// Support: Safari 8 only
10669// In Safari 8 documents created via document.implementation.createHTMLDocument
10670// collapse sibling forms: the second one becomes a child of the first one.
10671// Because of that, this security measure has to be disabled in Safari 8.
10672// https://bugs.webkit.org/show_bug.cgi?id=137337
10673    support.createHTMLDocument = ( function() {
10674        var body = document.implementation.createHTMLDocument( "" ).body;
10675        body.innerHTML = "<form></form><form></form>";
10676        return body.childNodes.length === 2;
10677    } )();
10678
10679
10680// Argument "data" should be string of html
10681// context (optional): If specified, the fragment will be created in this context,
10682// defaults to document
10683// keepScripts (optional): If true, will include scripts passed in the html string
10684    jQuery.parseHTML = function( data, context, keepScripts ) {
10685        if ( typeof data !== "string" ) {
10686            return [];
10687        }
10688        if ( typeof context === "boolean" ) {
10689            keepScripts = context;
10690            context = false;
10691        }
10692
10693        var base, parsed, scripts;
10694
10695        if ( !context ) {
10696
10697            // Stop scripts or inline event handlers from being executed immediately
10698            // by using document.implementation
10699            if ( support.createHTMLDocument ) {
10700                context = document.implementation.createHTMLDocument( "" );
10701
10702                // Set the base href for the created document
10703                // so any parsed elements with URLs
10704                // are based on the document's URL (gh-2965)
10705                base = context.createElement( "base" );
10706                base.href = document.location.href;
10707                context.head.appendChild( base );
10708            } else {
10709                context = document;
10710            }
10711        }
10712
10713        parsed = rsingleTag.exec( data );
10714        scripts = !keepScripts && [];
10715
10716        // Single tag
10717        if ( parsed ) {
10718            return [ context.createElement( parsed[ 1 ] ) ];
10719        }
10720
10721        parsed = buildFragment( [ data ], context, scripts );
10722
10723        if ( scripts && scripts.length ) {
10724            jQuery( scripts ).remove();
10725        }
10726
10727        return jQuery.merge( [], parsed.childNodes );
10728    };
10729
10730
10731    /**
10732     * Load a url into a page
10733     */
10734    jQuery.fn.load = function( url, params, callback ) {
10735        var selector, type, response,
10736            self = this,
10737            off = url.indexOf( " " );
10738
10739        if ( off > -1 ) {
10740            selector = stripAndCollapse( url.slice( off ) );
10741            url = url.slice( 0, off );
10742        }
10743
10744        // If it's a function
10745        if ( isFunction( params ) ) {
10746
10747            // We assume that it's the callback
10748            callback = params;
10749            params = undefined;
10750
10751            // Otherwise, build a param string
10752        } else if ( params && typeof params === "object" ) {
10753            type = "POST";
10754        }
10755
10756        // If we have elements to modify, make the request
10757        if ( self.length > 0 ) {
10758            jQuery.ajax( {
10759                url: url,
10760
10761                // If "type" variable is undefined, then "GET" method will be used.
10762                // Make value of this field explicit since
10763                // user can override it through ajaxSetup method
10764                type: type || "GET",
10765                dataType: "html",
10766                data: params
10767            } ).done( function( responseText ) {
10768
10769                // Save response for use in complete callback
10770                response = arguments;
10771
10772                self.html( selector ?
10773
10774                    // If a selector was specified, locate the right elements in a dummy div
10775                    // Exclude scripts to avoid IE 'Permission Denied' errors
10776                    jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) :
10777
10778                    // Otherwise use the full result
10779                    responseText );
10780
10781                // If the request succeeds, this function gets "data", "status", "jqXHR"
10782                // but they are ignored because response was set above.
10783                // If it fails, this function gets "jqXHR", "status", "error"
10784            } ).always( callback && function( jqXHR, status ) {
10785                self.each( function() {
10786                    callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] );
10787                } );
10788            } );
10789        }
10790
10791        return this;
10792    };
10793
10794
10795
10796
10797    jQuery.expr.pseudos.animated = function( elem ) {
10798        return jQuery.grep( jQuery.timers, function( fn ) {
10799            return elem === fn.elem;
10800        } ).length;
10801    };
10802
10803
10804
10805
10806    jQuery.offset = {
10807        setOffset: function( elem, options, i ) {
10808            var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
10809                position = jQuery.css( elem, "position" ),
10810                curElem = jQuery( elem ),
10811                props = {};
10812
10813            // Set position first, in-case top/left are set even on static elem
10814            if ( position === "static" ) {
10815                elem.style.position = "relative";
10816            }
10817
10818            curOffset = curElem.offset();
10819            curCSSTop = jQuery.css( elem, "top" );
10820            curCSSLeft = jQuery.css( elem, "left" );
10821            calculatePosition = ( position === "absolute" || position === "fixed" ) &&
10822                ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1;
10823
10824            // Need to be able to calculate position if either
10825            // top or left is auto and position is either absolute or fixed
10826            if ( calculatePosition ) {
10827                curPosition = curElem.position();
10828                curTop = curPosition.top;
10829                curLeft = curPosition.left;
10830
10831            } else {
10832                curTop = parseFloat( curCSSTop ) || 0;
10833                curLeft = parseFloat( curCSSLeft ) || 0;
10834            }
10835
10836            if ( isFunction( options ) ) {
10837
10838                // Use jQuery.extend here to allow modification of coordinates argument (gh-1848)
10839                options = options.call( elem, i, jQuery.extend( {}, curOffset ) );
10840            }
10841
10842            if ( options.top != null ) {
10843                props.top = ( options.top - curOffset.top ) + curTop;
10844            }
10845            if ( options.left != null ) {
10846                props.left = ( options.left - curOffset.left ) + curLeft;
10847            }
10848
10849            if ( "using" in options ) {
10850                options.using.call( elem, props );
10851
10852            } else {
10853                curElem.css( props );
10854            }
10855        }
10856    };
10857
10858    jQuery.fn.extend( {
10859
10860        // offset() relates an element's border box to the document origin
10861        offset: function( options ) {
10862
10863            // Preserve chaining for setter
10864            if ( arguments.length ) {
10865                return options === undefined ?
10866                    this :
10867                    this.each( function( i ) {
10868                        jQuery.offset.setOffset( this, options, i );
10869                    } );
10870            }
10871
10872            var rect, win,
10873                elem = this[ 0 ];
10874
10875            if ( !elem ) {
10876                return;
10877            }
10878
10879            // Return zeros for disconnected and hidden (display: none) elements (gh-2310)
10880            // Support: IE <=11 only
10881            // Running getBoundingClientRect on a
10882            // disconnected node in IE throws an error
10883            if ( !elem.getClientRects().length ) {
10884                return { top: 0, left: 0 };
10885            }
10886
10887            // Get document-relative position by adding viewport scroll to viewport-relative gBCR
10888            rect = elem.getBoundingClientRect();
10889            win = elem.ownerDocument.defaultView;
10890            return {
10891                top: rect.top + win.pageYOffset,
10892                left: rect.left + win.pageXOffset
10893            };
10894        },
10895
10896        // position() relates an element's margin box to its offset parent's padding box
10897        // This corresponds to the behavior of CSS absolute positioning
10898        position: function() {
10899            if ( !this[ 0 ] ) {
10900                return;
10901            }
10902
10903            var offsetParent, offset, doc,
10904                elem = this[ 0 ],
10905                parentOffset = { top: 0, left: 0 };
10906
10907            // position:fixed elements are offset from the viewport, which itself always has zero offset
10908            if ( jQuery.css( elem, "position" ) === "fixed" ) {
10909
10910                // Assume position:fixed implies availability of getBoundingClientRect
10911                offset = elem.getBoundingClientRect();
10912
10913            } else {
10914                offset = this.offset();
10915
10916                // Account for the *real* offset parent, which can be the document or its root element
10917                // when a statically positioned element is identified
10918                doc = elem.ownerDocument;
10919                offsetParent = elem.offsetParent || doc.documentElement;
10920                while ( offsetParent &&
10921                ( offsetParent === doc.body || offsetParent === doc.documentElement ) &&
10922                jQuery.css( offsetParent, "position" ) === "static" ) {
10923
10924                    offsetParent = offsetParent.parentNode;
10925                }
10926                if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) {
10927
10928                    // Incorporate borders into its offset, since they are outside its content origin
10929                    parentOffset = jQuery( offsetParent ).offset();
10930                    parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true );
10931                    parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true );
10932                }
10933            }
10934
10935            // Subtract parent offsets and element margins
10936            return {
10937                top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
10938                left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
10939            };
10940        },
10941
10942        // This method will return documentElement in the following cases:
10943        // 1) For the element inside the iframe without offsetParent, this method will return
10944        //    documentElement of the parent window
10945        // 2) For the hidden or detached element
10946        // 3) For body or html element, i.e. in case of the html node - it will return itself
10947        //
10948        // but those exceptions were never presented as a real life use-cases
10949        // and might be considered as more preferable results.
10950        //
10951        // This logic, however, is not guaranteed and can change at any point in the future
10952        offsetParent: function() {
10953            return this.map( function() {
10954                var offsetParent = this.offsetParent;
10955
10956                while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) {
10957                    offsetParent = offsetParent.offsetParent;
10958                }
10959
10960                return offsetParent || documentElement;
10961            } );
10962        }
10963    } );
10964
10965// Create scrollLeft and scrollTop methods
10966    jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
10967        var top = "pageYOffset" === prop;
10968
10969        jQuery.fn[ method ] = function( val ) {
10970            return access( this, function( elem, method, val ) {
10971
10972                // Coalesce documents and windows
10973                var win;
10974                if ( isWindow( elem ) ) {
10975                    win = elem;
10976                } else if ( elem.nodeType === 9 ) {
10977                    win = elem.defaultView;
10978                }
10979
10980                if ( val === undefined ) {
10981                    return win ? win[ prop ] : elem[ method ];
10982                }
10983
10984                if ( win ) {
10985                    win.scrollTo(
10986                        !top ? val : win.pageXOffset,
10987                        top ? val : win.pageYOffset
10988                    );
10989
10990                } else {
10991                    elem[ method ] = val;
10992                }
10993            }, method, val, arguments.length );
10994        };
10995    } );
10996
10997// Support: Safari <=7 - 9.1, Chrome <=37 - 49
10998// Add the top/left cssHooks using jQuery.fn.position
10999// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
11000// Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347
11001// getComputedStyle returns percent when specified for top/left/bottom/right;
11002// rather than make the css module depend on the offset module, just check for it here
11003    jQuery.each( [ "top", "left" ], function( _i, prop ) {
11004        jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
11005            function( elem, computed ) {
11006                if ( computed ) {
11007                    computed = curCSS( elem, prop );
11008
11009                    // If curCSS returns percentage, fallback to offset
11010                    return rnumnonpx.test( computed ) ?
11011                        jQuery( elem ).position()[ prop ] + "px" :
11012                        computed;
11013                }
11014            }
11015        );
11016    } );
11017
11018
11019// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
11020    jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
11021        jQuery.each( {
11022            padding: "inner" + name,
11023            content: type,
11024            "": "outer" + name
11025        }, function( defaultExtra, funcName ) {
11026
11027            // Margin is only for outerHeight, outerWidth
11028            jQuery.fn[ funcName ] = function( margin, value ) {
11029                var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
11030                    extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
11031
11032                return access( this, function( elem, type, value ) {
11033                    var doc;
11034
11035                    if ( isWindow( elem ) ) {
11036
11037                        // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729)
11038                        return funcName.indexOf( "outer" ) === 0 ?
vendor: 5,067 bytes, lines 11039-11196
11039                            elem[ "inner" + name ] :
11040                            elem.document.documentElement[ "client" + name ];
11041                    }
11042
11043                    // Get document width or height
11044                    if ( elem.nodeType === 9 ) {
11045                        doc = elem.documentElement;
11046
11047                        // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
11048                        // whichever is greatest
11049                        return Math.max(
11050                            elem.body[ "scroll" + name ], doc[ "scroll" + name ],
11051                            elem.body[ "offset" + name ], doc[ "offset" + name ],
11052                            doc[ "client" + name ]
11053                        );
11054                    }
11055
11056                    return value === undefined ?
11057
11058                        // Get width or height on the element, requesting but not forcing parseFloat
11059                        jQuery.css( elem, type, extra ) :
11060
11061                        // Set width or height on the element
11062                        jQuery.style( elem, type, value, extra );
11063                }, type, chainable ? margin : undefined, chainable );
11064            };
11065        } );
11066    } );
11067
11068
11069    jQuery.each( [
11070        "ajaxStart",
11071        "ajaxStop",
11072        "ajaxComplete",
11073        "ajaxError",
11074        "ajaxSuccess",
11075        "ajaxSend"
11076    ], function( _i, type ) {
11077        jQuery.fn[ type ] = function( fn ) {
11078            return this.on( type, fn );
11079        };
11080    } );
11081
11082
11083
11084
11085    jQuery.fn.extend( {
11086
11087        bind: function( types, data, fn ) {
11088            return this.on( types, null, data, fn );
11089        },
11090        unbind: function( types, fn ) {
11091            return this.off( types, null, fn );
11092        },
11093
11094        delegate: function( selector, types, data, fn ) {
11095            return this.on( types, selector, data, fn );
11096        },
11097        undelegate: function( selector, types, fn ) {
11098
11099            // ( namespace ) or ( selector, types [, fn] )
11100            return arguments.length === 1 ?
11101                this.off( selector, "**" ) :
11102                this.off( types, selector || "**", fn );
11103        },
11104
11105        hover: function( fnOver, fnOut ) {
11106            return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
11107        }
11108    } );
11109
11110    jQuery.each(
11111        ( "blur focus focusin focusout resize scroll click dblclick " +
11112            "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
11113            "change select submit keydown keypress keyup contextmenu" ).split( " " ),
11114        function( _i, name ) {
11115
11116            // Handle event binding
11117            jQuery.fn[ name ] = function( data, fn ) {
11118                return arguments.length > 0 ?
11119                    this.on( name, null, data, fn ) :
11120                    this.trigger( name );
11121            };
11122        }
11123    );
11124
11125
11126
11127
11128// Support: Android <=4.0 only
11129// Make sure we trim BOM and NBSP
11130    var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
11131
11132// Bind a function to a context, optionally partially applying any
11133// arguments.
11134// jQuery.proxy is deprecated to promote standards (specifically Function#bind)
11135// However, it is not slated for removal any time soon
11136    jQuery.proxy = function( fn, context ) {
11137        var tmp, args, proxy;
11138
11139        if ( typeof context === "string" ) {
11140            tmp = fn[ context ];
11141            context = fn;
11142            fn = tmp;
11143        }
11144
11145        // Quick check to determine if target is callable, in the spec
11146        // this throws a TypeError, but we will just return undefined.
11147        if ( !isFunction( fn ) ) {
11148            return undefined;
11149        }
11150
11151        // Simulated bind
11152        args = slice.call( arguments, 2 );
11153        proxy = function() {
11154            return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
11155        };
11156
11157        // Set the guid of unique handler to the same of original handler, so it can be removed
11158        proxy.guid = fn.guid = fn.guid || jQuery.guid++;
11159
11160        return proxy;
11161    };
11162
11163    jQuery.holdReady = function( hold ) {
11164        if ( hold ) {
11165            jQuery.readyWait++;
11166        } else {
11167            jQuery.ready( true );
11168        }
11169    };
11170    jQuery.isArray = Array.isArray;
11171    jQuery.parseJSON = JSON.parse;
11172    jQuery.nodeName = nodeName;
11173    jQuery.isFunction = isFunction;
11174    jQuery.isWindow = isWindow;
11175    jQuery.camelCase = camelCase;
11176    jQuery.type = toType;
11177
11178    jQuery.now = Date.now;
11179
11180    jQuery.isNumeric = function( obj ) {
11181
11182        // As of jQuery 3.0, isNumeric is limited to
11183        // strings and numbers (primitives or objects)
11184        // that can be coerced to finite numbers (gh-2662)
11185        var type = jQuery.type( obj );
11186        return ( type === "number" || type === "string" ) &&
11187
11188            // parseFloat NaNs numeric-cast false positives ("")
11189            // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
11190            // subtraction forces infinities to NaN
11191            !isNaN( obj - parseFloat( obj ) );
11192    };
11193
11194    jQuery.trim = function( text ) {
11195        return text == null ?
11196            "" :
11197            ( text + "" ).replace( rtrim, "" );
11198    };
11199
11200
11201
11202// Register as a named AMD module, since jQuery can be concatenated with other
11203// files that may use define, but not via a proper concatenation script that
11204// understands anonymous AMD modules. A named AMD is safest and most robust
11205// way to register. Lowercase jquery is used because AMD module names are
11206// derived from file names, and jQuery is normally delivered in a lowercase
11207// file name. Do this after creating the global so that if an AMD module wants
11208// to call noConflict to hide this version of jQuery, it will work.
11209
11210// Note that for maximum portability, libraries that are not jQuery should
11211// declare themselves as anonymous modules, and avoid setting a global if an
11212// AMD loader is present. jQuery is a special case. For more information, see
11213// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
11214
11215    if ( typeof define === "function" && define.amd ) {
11216        define( "jquery", [], function() {
11217            return jQuery;
11218        } );
11219    }
11220
11221
11222
11223
11224    var
11225
11226        // Map over jQuery in case of overwrite
11227        _jQuery = window.jQuery,
11228
11229        // Map over the $ in case of overwrite
11230        _$ = window.$;
11231
11232    jQuery.noConflict = function( deep ) {
11233        if ( window.$ === jQuery ) {
11234            window.$ = _$;
11235        }
11236
11237        if ( deep && window.jQuery === jQuery ) {
11238            window.jQuery = _jQuery;
11239        }
11240
11241        return jQuery;
11242    };
11243
11244// Expose jQuery and $ identifiers, even in AMD
11245// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
11246// and CommonJS for browser emulators (#13566)
11247    if ( typeof noGlobal === "undefined" ) {
11248        window.jQuery = window.$ = jQuery;
11249    }
11250
11251
11252
11253
11254    return jQuery;
11255} );
11256/**
11257 * Cookie plugin
11258 *
11259 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
11260 * Dual licensed under the MIT and GPL licenses:
11261 * http://www.opensource.org/licenses/mit-license.php
11262 * http://www.gnu.org/licenses/gpl.html
11263 *
11264 */
11265
11266/**
11267 * Create a cookie with the given name and value and other optional parameters.
11268 *
11269 * @example $.cookie('the_cookie', 'the_value');
11270 * @desc Set the value of a cookie.
11271 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
11272 * @desc Create a cookie with all available options.
11273 * @example $.cookie('the_cookie', 'the_value');
11274 * @desc Create a session cookie.
11275 * @example $.cookie('the_cookie', null);
11276 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
11277 *       used when the cookie was set.
11278 *
11279 * @param String name The name of the cookie.
11280 * @param String value The value of the cookie.
11281 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
11282 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
11283 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
11284 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
11285 *                             when the the browser exits.
11286 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
11287 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
11288 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
11289 *                        require a secure protocol (like HTTPS).
11290 * @type undefined
11291 *
11292 * @name $.cookie
11293 * @cat Plugins/Cookie
11294 * @author Klaus Hartl/[email protected]
11295 */
11296
11297/**
11298 * Get the value of a cookie with the given name.
11299 *
11300 * @example $.cookie('the_cookie');
11301 * @desc Get the value of a cookie.
11302 *
11303 * @param String name The name of the cookie.
11304 * @return The value of the cookie.
11305 * @type String
11306 *
11307 * @name $.cookie
11308 * @cat Plugins/Cookie
11309 * @author Klaus Hartl/[email protected]
11310 */
11311jQuery.cookie = function(name, value, options) {
11312    if (typeof value != 'undefined') { // name and value given, set cookie
11313        options = options || {};
11314        if (value === null) {
11315            value = '';
11316            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
11317            options.expires = -1;
11318        }
11319        var expires = '';
11320        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
11321            var date;
11322            if (typeof options.expires == 'number') {
11323                date = new Date();
11324                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
11325            } else {
11326                date = options.expires;
11327            }
11328            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
11329        }
11330        // NOTE Needed to parenthesize options.path and options.domain
11331        // in the following expressions, otherwise they evaluate to undefined
11332        // in the packed version for some reason...
11333        var path = options.path ? '; path=' + (options.path) : '';
11334        var domain = options.domain ? '; domain=' + (options.domain) : '';
11335        var secure = options.secure ? '; secure' : '';
11336        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
11337    } else { // only name given, get cookie
11338        var cookieValue = null;
11339        if (document.cookie && document.cookie != '') {
11340            var cookies = document.cookie.split(';');
11341            for (var i = 0; i < cookies.length; i++) {
11342                var cookie = jQuery.trim(cookies[i]);
11343                // Does this cookie string begin with the name we want?
11344                if (cookie.substring(0, name.length + 1) == (name + '=')) {
11345                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
11346                    break;
11347                }
11348            }
11349        }
11350        return cookieValue;
11351    }
11352};
11353// JQuery URL Parser plugin - https://github.com/allmarkedup/jQuery-URL-Parser
11354// Written by Mark Perkins, [email protected]
11355// License: http://unlicense.org/ (i.e. do what you want with it!)
11356
11357;(function($) {
11358
11359    var tag2attr = {
11360        a       : 'href',
11361        img     : 'src',
11362        form    : 'action',
11363        base    : 'href',
11364        script  : 'src',
11365        iframe  : 'src',
11366        link    : 'href'
11367    },
11368
11369    key = ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","fragment"], // keys available to query
11370
11371    aliases = { "anchor" : "fragment" }, // aliases for backwards compatability
11372
11373    parser = {
11374        strict  : /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
11375        loose   :  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
11376    },
11377
11378    querystring_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g, // supports both ampersand and semicolon-delimted query string key/value pairs
11379
11380    fragment_parser = /(?:^|&|;)([^&=;]*)=?([^&;]*)/g; // supports both ampersand and semicolon-delimted fragment key/value pairs
11381
11382    function parseUri( url, strictMode )
11383    {
11384        var str = decodeURI( url ),
11385            res   = parser[ strictMode || false ? "strict" : "loose" ].exec( str ),
11386            uri = { attr : {}, param : {}, seg : {} },
11387            i   = 14;
11388
11389        while ( i-- )
11390        {
11391            uri.attr[ key[i] ] = res[i] || "";
11392        }
11393
11394        // build query and fragment parameters
11395
11396        uri.param['query'] = {};
11397        uri.param['fragment'] = {};
11398
11399        uri.attr['query'].replace( querystring_parser, function ( $0, $1, $2 ){
11400            if ($1)
11401            {
11402                uri.param['query'][$1] = $2;
11403            }
11404        });
11405
11406        uri.attr['fragment'].replace( fragment_parser, function ( $0, $1, $2 ){
11407            if ($1)
11408            {
11409                uri.param['fragment'][$1] = $2;
11410            }
11411        });
11412
11413        // split path and fragement into segments
11414
11415        uri.seg['path'] = uri.attr.path.replace(/^\/+|\/+$/g,'').split('/');
11416
11417        uri.seg['fragment'] = uri.attr.fragment.replace(/^\/+|\/+$/g,'').split('/');
11418
11419        // compile a 'base' domain attribute
11420
11421        uri.attr['base'] = uri.attr.host ? uri.attr.protocol+"://"+uri.attr.host + (uri.attr.port ? ":"+uri.attr.port : '') : '';
11422
11423        return uri;
11424    };
11425
11426    function getAttrName( elm )
11427    {
11428        var tn = elm.tagName;
11429        if ( tn !== undefined ) return tag2attr[tn.toLowerCase()];
11430        return tn;
11431    }
11432
11433    $.fn.url = function( strictMode )
11434    {
11435        var url = '';
11436
11437        if ( this.length )
11438        {
11439            url = $(this).attr( getAttrName(this[0]) ) || '';
11440        }
11441
11442        return $.url({ url : url, strict : strictMode });
11443    };
11444
11445    $.url = function( opts )
11446    {
11447        var url     = '',
11448            strict  = false;
11449
11450        if ( typeof opts === 'string' )
11451        {
11452            url = opts;
11453        }
11454        else
11455        {
11456            opts = opts || {};
11457            strict = opts.strict || strict;
11458            url = opts.url === undefined ? window.location.toString() : opts.url;
11459        }
11460
11461        return {
11462
11463            data : parseUri(url, strict),
11464
11465            // get various attributes from the URI
11466            attr : function( attr )
11467            {
11468                attr = aliases[attr] || attr;
11469                return attr !== undefined ? this.data.attr[attr] : this.data.attr;
11470            },
11471
11472            // return query string parameters
11473            param : function( param )
11474            {
11475                return param !== undefined ? this.data.param.query[param] : this.data.param.query;
11476            },
11477
11478            // return fragment parameters
11479            fparam : function( param )
11480            {
11481                return param !== undefined ? this.data.param.fragment[param] : this.data.param.fragment;
11482            },
11483
11484            // return path segments
11485            segment : function( seg )
11486            {
11487                if ( seg === undefined )
11488                {
11489                    return this.data.seg.path;
11490                }
11491                else
11492                {
11493                    seg = seg < 0 ? this.data.seg.path.length + seg : seg - 1; // negative segments count from the end
11494                    return this.data.seg.path[seg];
11495                }
11496            },
11497
11498            // return fragment segments
11499            fsegment : function( seg )
11500            {
11501                if ( seg === undefined )
11502                {
11503                    return this.data.seg.fragment;
11504                }
11505                else
11506                {
11507                    seg = seg < 0 ? this.data.seg.fragment.length + seg : seg - 1; // negative segments count from the end
11508                    return this.data.seg.fragment[seg];
11509                }
11510            },
11511
11512            replace : function( param, value )
11513            {
11514                var sParamPattern = eval('/(&|\\?)'+param+'=[a-zA-Z0-9\_\-\|\+\^\#\@\$\%\*\/\;\:]+/');
11515                var sIsParamPattern = /\?[a-zA-Z0-9_-]+/;
11516                if (sIsParamPattern.test(url) === true) {
11517                    if (sParamPattern.test(url) === true) return url.replace(sParamPattern, '$1'+param+'='+value);
11518                    return url + '&'+param+'='+value;
11519                } else {
11520                    if (sParamPattern.test(url) === true) return url.replace(sParamPattern, '$1'+param+'='+value);
11521                    return url + '?'+param+'='+value;
11522                }
11523
11524            }
11525
11526        };
11527
11528    };
11529
11530})(jQuery);
11531(function($) {
11532    $.fn.setValue = function(value) {
11533        if ($(this).is('SELECT') === true) {
11534            $(this).find('option[value="'+ value +'"]').prop('selected', true);
11535        } else {
11536            $(this).val(value);
11537        }
11538    };
11539})(jQuery);
11540var EC$ = window.jQuery;
11541(function($, jQuery) {
11542    // .uuid 복원
11543    if (typeof jQuery.uuid == 'undefined') {
11544        jQuery.uuid = 0;
11545    }
11546
11547    // .curCSS 복원
11548    if ( !jQuery.curCSS ) {
11549        jQuery.curCSS = jQuery.css;
11550    }
11551
11552    // .browser 복원
11553    if ( !$.browser ) {
11554        $.uaMatch = function( ua ) {
11555            ua = ua.toLowerCase();
11556
11557            var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
11558                /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
11559                /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
11560                /(msie) ([\w.]+)/.exec( ua ) ||
11561                ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
11562                [];
11563
11564            return {
11565                browser: match[ 1 ] || "",
11566                version: match[ 2 ] || "0"
11567            };
11568        };
11569
11570        matched = $.uaMatch( navigator.userAgent );
11571        browser = {};
11572
11573        if ( matched.browser ) {
11574            browser[ matched.browser ] = true;
11575            browser.version = matched.version;
11576        }
11577
11578        // Chrome is Webkit, but Webkit is also Safari.
11579        if ( browser.chrome ) {
11580            browser.webkit = true;
11581        } else if ( browser.webkit ) {
11582            browser.safari = true;
11583        }
11584
11585        $.browser = browser;
11586    }
11587
11588    // $.escapeSelector Polyfill
11589    if ( !$.escapeSelector ) {
11590        $.escapeSelector = function( sel ) {
11591            var rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g;
11592            var fcssescape = function( ch, asCodePoint ) {
11593                if ( asCodePoint ) {
11594
11595                    // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER
11596                    if ( ch === "\0" ) {
11597                        return "\uFFFD";
11598                    }
11599
11600                    // Control characters and (dependent upon position) numbers get escaped as code points
11601                    return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " ";
11602                }
11603
11604                // Other potentially-special ASCII characters get backslash-escaped
11605                return "\\" + ch;
11606            };
11607
11608            return ( sel + "" ).replace( rcssescape, fcssescape );
11609        };
11610    }
11611})($, jQuery);
11612(function(global) {if (global.moment) {global.moment_original = global.moment;}
vendor: 58,852 bytes, line 11613
11613!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.moment=t()}(this,function(){"use strict";var H;function _(){return H.apply(null,arguments)}function y(e){return e instanceof Array||"[object Array]"===Object.prototype.toString.call(e)}function F(e){return null!=e&&"[object Object]"===Object.prototype.toString.call(e)}function c(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function L(e){if(Object.getOwnPropertyNames)return 0===Object.getOwnPropertyNames(e).length;for(var t in e)if(c(e,t))return;return 1}function g(e){return void 0===e}function w(e){return"number"==typeof e||"[object Number]"===Object.prototype.toString.call(e)}function V(e){return e instanceof Date||"[object Date]"===Object.prototype.toString.call(e)}function G(e,t){for(var n=[],s=e.length,i=0;i<s;++i)n.push(t(e[i],i));return n}function E(e,t){for(var n in t)c(t,n)&&(e[n]=t[n]);return c(t,"toString")&&(e.toString=t.toString),c(t,"valueOf")&&(e.valueOf=t.valueOf),e}function l(e,t,n,s){return Wt(e,t,n,s,!0).utc()}function p(e){return null==e._pf&&(e._pf={empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}),e._pf}function A(e){var t,n,s=e._d&&!isNaN(e._d.getTime());return s&&(t=p(e),n=j.call(t.parsedDateParts,function(e){return null!=e}),s=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&n),e._strict)&&(s=s&&0===t.charsLeftOver&&0===t.unusedTokens.length&&void 0===t.bigHour),null!=Object.isFrozen&&Object.isFrozen(e)?s:(e._isValid=s,e._isValid)}function I(e){var t=l(NaN);return null!=e?E(p(t),e):p(t).userInvalidated=!0,t}var j=Array.prototype.some||function(e){for(var t=Object(this),n=t.length>>>0,s=0;s<n;s++)if(s in t&&e.call(this,t[s],s,t))return!0;return!1},Z=_.momentProperties=[],z=!1;function q(e,t){var n,s,i,r=Z.length;if(g(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),g(t._i)||(e._i=t._i),g(t._f)||(e._f=t._f),g(t._l)||(e._l=t._l),g(t._strict)||(e._strict=t._strict),g(t._tzm)||(e._tzm=t._tzm),g(t._isUTC)||(e._isUTC=t._isUTC),g(t._offset)||(e._offset=t._offset),g(t._pf)||(e._pf=p(t)),g(t._locale)||(e._locale=t._locale),0<r)for(n=0;n<r;n++)g(i=t[s=Z[n]])||(e[s]=i);return e}function $(e){q(this,e),this._d=new Date(null!=e._d?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),!1===z&&(z=!0,_.updateOffset(this),z=!1)}function k(e){return e instanceof $||null!=e&&null!=e._isAMomentObject}function B(e){!1===_.suppressDeprecationWarnings&&"undefined"!=typeof console&&console.warn&&console.warn("Deprecation warning: "+e)}function e(r,a){var o=!0;return E(function(){if(null!=_.deprecationHandler&&_.deprecationHandler(null,r),o){for(var e,t,n=[],s=arguments.length,i=0;i<s;i++){if(e="","object"==typeof arguments[i]){for(t in e+="\n["+i+"] ",arguments[0])c(arguments[0],t)&&(e+=t+": "+arguments[0][t]+", ");e=e.slice(0,-2)}else e=arguments[i];n.push(e)}B(r+"\nArguments: "+Array.prototype.slice.call(n).join("")+"\n"+(new Error).stack),o=!1}return a.apply(this,arguments)},a)}var J={};function Q(e,t){null!=_.deprecationHandler&&_.deprecationHandler(e,t),J[e]||(B(t),J[e]=!0)}function a(e){return"undefined"!=typeof Function&&e instanceof Function||"[object Function]"===Object.prototype.toString.call(e)}function X(e,t){var n,s=E({},e);for(n in t)c(t,n)&&(F(e[n])&&F(t[n])?(s[n]={},E(s[n],e[n]),E(s[n],t[n])):null!=t[n]?s[n]=t[n]:delete s[n]);for(n in e)c(e,n)&&!c(t,n)&&F(e[n])&&(s[n]=E({},s[n]));return s}function K(e){null!=e&&this.set(e)}_.suppressDeprecationWarnings=!1,_.deprecationHandler=null;var ee=Object.keys||function(e){var t,n=[];for(t in e)c(e,t)&&n.push(t);return n};function r(e,t,n){var s=""+Math.abs(e);return(0<=e?n?"+":"":"-")+Math.pow(10,Math.max(0,t-s.length)).toString().substr(1)+s}var te=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,ne=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,se={},ie={};function s(e,t,n,s){var i="string"==typeof s?function(){return this[s]()}:s;e&&(ie[e]=i),t&&(ie[t[0]]=function(){return r(i.apply(this,arguments),t[1],t[2])}),n&&(ie[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function re(e,t){return e.isValid()?(t=ae(t,e.localeData()),se[t]=se[t]||function(s){for(var e,i=s.match(te),t=0,r=i.length;t<r;t++)ie[i[t]]?i[t]=ie[i[t]]:i[t]=(e=i[t]).match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"");return function(e){for(var t="",n=0;n<r;n++)t+=a(i[n])?i[n].call(e,s):i[n];return t}}(t),se[t](e)):e.localeData().invalidDate()}function ae(e,t){var n=5;function s(e){return t.longDateFormat(e)||e}for(ne.lastIndex=0;0<=n&&ne.test(e);)e=e.replace(ne,s),ne.lastIndex=0,--n;return e}var oe={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function o(e){return"string"==typeof e?oe[e]||oe[e.toLowerCase()]:void 0}function ue(e){var t,n,s={};for(n in e)c(e,n)&&(t=o(n))&&(s[t]=e[n]);return s}var le={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};var de=/\d/,t=/\d\d/,he=/\d{3}/,ce=/\d{4}/,fe=/[+-]?\d{6}/,n=/\d\d?/,me=/\d\d\d\d?/,_e=/\d\d\d\d\d\d?/,ye=/\d{1,3}/,ge=/\d{1,4}/,we=/[+-]?\d{1,6}/,pe=/\d+/,ke=/[+-]?\d+/,Me=/Z|[+-]\d\d:?\d\d/gi,ve=/Z|[+-]\d\d(?::?\d\d)?/gi,i=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,u=/^[1-9]\d?/,d=/^([1-9]\d|\d)/;function h(e,n,s){Ye[e]=a(n)?n:function(e,t){return e&&s?s:n}}function De(e,t){return c(Ye,e)?Ye[e](t._strict,t._locale):new RegExp(f(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,s,i){return t||n||s||i})))}function f(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function m(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function M(e){var e=+e,t=0;return t=0!=e&&isFinite(e)?m(e):t}var Ye={},Se={};function v(e,n){var t,s,i=n;for("string"==typeof e&&(e=[e]),w(n)&&(i=function(e,t){t[n]=M(e)}),s=e.length,t=0;t<s;t++)Se[e[t]]=i}function Oe(e,i){v(e,function(e,t,n,s){n._w=n._w||{},i(e,n._w,n,s)})}function be(e){return e%4==0&&e%100!=0||e%400==0}var D=0,Y=1,S=2,O=3,b=4,T=5,Te=6,xe=7,Ne=8;function We(e){return be(e)?366:365}s("Y",0,0,function(){var e=this.year();return e<=9999?r(e,4):"+"+e}),s(0,["YY",2],0,function(){return this.year()%100}),s(0,["YYYY",4],0,"year"),s(0,["YYYYY",5],0,"year"),s(0,["YYYYYY",6,!0],0,"year"),h("Y",ke),h("YY",n,t),h("YYYY",ge,ce),h("YYYYY",we,fe),h("YYYYYY",we,fe),v(["YYYYY","YYYYYY"],D),v("YYYY",function(e,t){t[D]=2===e.length?_.parseTwoDigitYear(e):M(e)}),v("YY",function(e,t){t[D]=_.parseTwoDigitYear(e)}),v("Y",function(e,t){t[D]=parseInt(e,10)}),_.parseTwoDigitYear=function(e){return M(e)+(68<M(e)?1900:2e3)};var x,Pe=Re("FullYear",!0);function Re(t,n){return function(e){return null!=e?(Ue(this,t,e),_.updateOffset(this,n),this):Ce(this,t)}}function Ce(e,t){if(!e.isValid())return NaN;var n=e._d,s=e._isUTC;switch(t){case"Milliseconds":return s?n.getUTCMilliseconds():n.getMilliseconds();case"Seconds":return s?n.getUTCSeconds():n.getSeconds();case"Minutes":return s?n.getUTCMinutes():n.getMinutes();case"Hours":return s?n.getUTCHours():n.getHours();case"Date":return s?n.getUTCDate():n.getDate();case"Day":return s?n.getUTCDay():n.getDay();case"Month":return s?n.getUTCMonth():n.getMonth();case"FullYear":return s?n.getUTCFullYear():n.getFullYear();default:return NaN}}function Ue(e,t,n){var s,i,r;if(e.isValid()&&!isNaN(n)){switch(s=e._d,i=e._isUTC,t){case"Milliseconds":return i?s.setUTCMilliseconds(n):s.setMilliseconds(n);case"Seconds":return i?s.setUTCSeconds(n):s.setSeconds(n);case"Minutes":return i?s.setUTCMinutes(n):s.setMinutes(n);case"Hours":return i?s.setUTCHours(n):s.setHours(n);case"Date":return i?s.setUTCDate(n):s.setDate(n);case"FullYear":break;default:return}t=n,r=e.month(),e=29!==(e=e.date())||1!==r||be(t)?e:28,i?s.setUTCFullYear(t,r,e):s.setFullYear(t,r,e)}}function He(e,t){var n;return isNaN(e)||isNaN(t)?NaN:(n=(t%(n=12)+n)%n,e+=(t-n)/12,1==n?be(e)?29:28:31-n%7%2)}x=Array.prototype.indexOf||function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1},s("M",["MM",2],"Mo",function(){return this.month()+1}),s("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)}),s("MMMM",0,0,function(e){return this.localeData().months(this,e)}),h("M",n,u),h("MM",n,t),h("MMM",function(e,t){return t.monthsShortRegex(e)}),h("MMMM",function(e,t){return t.monthsRegex(e)}),v(["M","MM"],function(e,t){t[Y]=M(e)-1}),v(["MMM","MMMM"],function(e,t,n,s){s=n._locale.monthsParse(e,s,n._strict);null!=s?t[Y]=s:p(n).invalidMonth=e});var Fe="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),Le="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Ve=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Ge=i,Ee=i;function Ae(e,t){if(e.isValid()){if("string"==typeof t)if(/^\d+$/.test(t))t=M(t);else if(!w(t=e.localeData().monthsParse(t)))return;var n=(n=e.date())<29?n:Math.min(n,He(e.year(),t));e._isUTC?e._d.setUTCMonth(t,n):e._d.setMonth(t,n)}}function Ie(e){return null!=e?(Ae(this,e),_.updateOffset(this,!0),this):Ce(this,"Month")}function je(){function e(e,t){return t.length-e.length}for(var t,n,s=[],i=[],r=[],a=0;a<12;a++)n=l([2e3,a]),t=f(this.monthsShort(n,"")),n=f(this.months(n,"")),s.push(t),i.push(n),r.push(n),r.push(t);s.sort(e),i.sort(e),r.sort(e),this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function Ze(e,t,n,s,i,r,a){var o;return e<100&&0<=e?(o=new Date(e+400,t,n,s,i,r,a),isFinite(o.getFullYear())&&o.setFullYear(e)):o=new Date(e,t,n,s,i,r,a),o}function ze(e){var t;return e<100&&0<=e?((t=Array.prototype.slice.call(arguments))[0]=e+400,t=new Date(Date.UTC.apply(null,t)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function qe(e,t,n){n=7+t-n;return n-(7+ze(e,0,n).getUTCDay()-t)%7-1}function $e(e,t,n,s,i){var r,t=1+7*(t-1)+(7+n-s)%7+qe(e,s,i),n=t<=0?We(r=e-1)+t:t>We(e)?(r=e+1,t-We(e)):(r=e,t);return{year:r,dayOfYear:n}}function Be(e,t,n){var s,i,r=qe(e.year(),t,n),r=Math.floor((e.dayOfYear()-r-1)/7)+1;return r<1?s=r+N(i=e.year()-1,t,n):r>N(e.year(),t,n)?(s=r-N(e.year(),t,n),i=e.year()+1):(i=e.year(),s=r),{week:s,year:i}}function N(e,t,n){var s=qe(e,t,n),t=qe(e+1,t,n);return(We(e)-s+t)/7}s("w",["ww",2],"wo","week"),s("W",["WW",2],"Wo","isoWeek"),h("w",n,u),h("ww",n,t),h("W",n,u),h("WW",n,t),Oe(["w","ww","W","WW"],function(e,t,n,s){t[s.substr(0,1)]=M(e)});function Je(e,t){return e.slice(t,7).concat(e.slice(0,t))}s("d",0,"do","day"),s("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)}),s("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)}),s("dddd",0,0,function(e){return this.localeData().weekdays(this,e)}),s("e",0,0,"weekday"),s("E",0,0,"isoWeekday"),h("d",n),h("e",n),h("E",n),h("dd",function(e,t){return t.weekdaysMinRegex(e)}),h("ddd",function(e,t){return t.weekdaysShortRegex(e)}),h("dddd",function(e,t){return t.weekdaysRegex(e)}),Oe(["dd","ddd","dddd"],function(e,t,n,s){s=n._locale.weekdaysParse(e,s,n._strict);null!=s?t.d=s:p(n).invalidWeekday=e}),Oe(["d","e","E"],function(e,t,n,s){t[s]=M(e)});var Qe="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Xe="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Ke="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),et=i,tt=i,nt=i;function st(){function e(e,t){return t.length-e.length}for(var t,n,s,i=[],r=[],a=[],o=[],u=0;u<7;u++)s=l([2e3,1]).day(u),t=f(this.weekdaysMin(s,"")),n=f(this.weekdaysShort(s,"")),s=f(this.weekdays(s,"")),i.push(t),r.push(n),a.push(s),o.push(t),o.push(n),o.push(s);i.sort(e),r.sort(e),a.sort(e),o.sort(e),this._weekdaysRegex=new RegExp("^("+o.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+i.join("|")+")","i")}function it(){return this.hours()%12||12}function rt(e,t){s(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}function at(e,t){return t._meridiemParse}s("H",["HH",2],0,"hour"),s("h",["hh",2],0,it),s("k",["kk",2],0,function(){return this.hours()||24}),s("hmm",0,0,function(){return""+it.apply(this)+r(this.minutes(),2)}),s("hmmss",0,0,function(){return""+it.apply(this)+r(this.minutes(),2)+r(this.seconds(),2)}),s("Hmm",0,0,function(){return""+this.hours()+r(this.minutes(),2)}),s("Hmmss",0,0,function(){return""+this.hours()+r(this.minutes(),2)+r(this.seconds(),2)}),rt("a",!0),rt("A",!1),h("a",at),h("A",at),h("H",n,d),h("h",n,u),h("k",n,u),h("HH",n,t),h("hh",n,t),h("kk",n,t),h("hmm",me),h("hmmss",_e),h("Hmm",me),h("Hmmss",_e),v(["H","HH"],O),v(["k","kk"],function(e,t,n){e=M(e);t[O]=24===e?0:e}),v(["a","A"],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),v(["h","hh"],function(e,t,n){t[O]=M(e),p(n).bigHour=!0}),v("hmm",function(e,t,n){var s=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s)),p(n).bigHour=!0}),v("hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s,2)),t[T]=M(e.substr(i)),p(n).bigHour=!0}),v("Hmm",function(e,t,n){var s=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s))}),v("Hmmss",function(e,t,n){var s=e.length-4,i=e.length-2;t[O]=M(e.substr(0,s)),t[b]=M(e.substr(s,2)),t[T]=M(e.substr(i))});i=Re("Hours",!0);var ot,ut={calendar:{sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"},longDateFormat:{LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},invalidDate:"Invalid date",ordinal:"%d",dayOfMonthOrdinalParse:/\d{1,2}/,relativeTime:{future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"},months:Fe,monthsShort:Le,week:{dow:0,doy:6},weekdays:Qe,weekdaysMin:Ke,weekdaysShort:Xe,meridiemParse:/[ap]\.?m?\.?/i},W={},lt={};function dt(e){return e&&e.toLowerCase().replace("_","-")}function ht(e){for(var t,n,s,i,r=0;r<e.length;){for(t=(i=dt(e[r]).split("-")).length,n=(n=dt(e[r+1]))?n.split("-"):null;0<t;){if(s=ct(i.slice(0,t).join("-")))return s;if(n&&n.length>=t&&function(e,t){for(var n=Math.min(e.length,t.length),s=0;s<n;s+=1)if(e[s]!==t[s])return s;return n}(i,n)>=t-1)break;t--}r++}return ot}function ct(t){var e,n;if(void 0===W[t]&&"undefined"!=typeof module&&module&&module.exports&&(n=t)&&n.match("^[^/\\\\]*$"))try{e=ot._abbr,require("./locale/"+t),ft(e)}catch(e){W[t]=null}return W[t]}function ft(e,t){return e&&((t=g(t)?P(e):mt(e,t))?ot=t:"undefined"!=typeof console&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ot._abbr}function mt(e,t){if(null===t)return delete W[e],null;var n,s=ut;if(t.abbr=e,null!=W[e])Q("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),s=W[e]._config;else if(null!=t.parentLocale)if(null!=W[t.parentLocale])s=W[t.parentLocale]._config;else{if(null==(n=ct(t.parentLocale)))return lt[t.parentLocale]||(lt[t.parentLocale]=[]),lt[t.parentLocale].push({name:e,config:t}),null;s=n._config}return W[e]=new K(X(s,t)),lt[e]&&lt[e].forEach(function(e){mt(e.name,e.config)}),ft(e),W[e]}function P(e){var t;if(!(e=e&&e._locale&&e._locale._abbr?e._locale._abbr:e))return ot;if(!y(e)){if(t=ct(e))return t;e=[e]}return ht(e)}function _t(e){var t=e._a;return t&&-2===p(e).overflow&&(t=t[Y]<0||11<t[Y]?Y:t[S]<1||t[S]>He(t[D],t[Y])?S:t[O]<0||24<t[O]||24===t[O]&&(0!==t[b]||0!==t[T]||0!==t[Te])?O:t[b]<0||59<t[b]?b:t[T]<0||59<t[T]?T:t[Te]<0||999<t[Te]?Te:-1,p(e)._overflowDayOfYear&&(t<D||S<t)&&(t=S),p(e)._overflowWeeks&&-1===t&&(t=xe),p(e)._overflowWeekday&&-1===t&&(t=Ne),p(e).overflow=t),e}var yt=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gt=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,wt=/Z|[+-]\d\d(?::?\d\d)?/,pt=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],kt=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],Mt=/^\/?Date\((-?\d+)/i,vt=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Dt={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Yt(e){var t,n,s,i,r,a,o=e._i,u=yt.exec(o)||gt.exec(o),o=pt.length,l=kt.length;if(u){for(p(e).iso=!0,t=0,n=o;t<n;t++)if(pt[t][1].exec(u[1])){i=pt[t][0],s=!1!==pt[t][2];break}if(null==i)e._isValid=!1;else{if(u[3]){for(t=0,n=l;t<n;t++)if(kt[t][1].exec(u[3])){r=(u[2]||" ")+kt[t][0];break}if(null==r)return void(e._isValid=!1)}if(s||null==r){if(u[4]){if(!wt.exec(u[4]))return void(e._isValid=!1);a="Z"}e._f=i+(r||"")+(a||""),xt(e)}else e._isValid=!1}}else e._isValid=!1}function St(e,t,n,s,i,r){e=[function(e){e=parseInt(e,10);{if(e<=49)return 2e3+e;if(e<=999)return 1900+e}return e}(e),Le.indexOf(t),parseInt(n,10),parseInt(s,10),parseInt(i,10)];return r&&e.push(parseInt(r,10)),e}function Ot(e){var t,n,s=vt.exec(e._i.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,""));s?(t=St(s[4],s[3],s[2],s[5],s[6],s[7]),function(e,t,n){if(!e||Xe.indexOf(e)===new Date(t[0],t[1],t[2]).getDay())return 1;p(n).weekdayMismatch=!0,n._isValid=!1}(s[1],t,e)&&(e._a=t,e._tzm=(t=s[8],n=s[9],s=s[10],t?Dt[t]:n?0:60*(((t=parseInt(s,10))-(n=t%100))/100)+n),e._d=ze.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),p(e).rfc2822=!0)):e._isValid=!1}function bt(e,t,n){return null!=e?e:null!=t?t:n}function Tt(e){var t,n,s,i,r,a,o,u,l,d,h,c=[];if(!e._d){for(s=e,i=new Date(_.now()),n=s._useUTC?[i.getUTCFullYear(),i.getUTCMonth(),i.getUTCDate()]:[i.getFullYear(),i.getMonth(),i.getDate()],e._w&&null==e._a[S]&&null==e._a[Y]&&(null!=(i=(s=e)._w).GG||null!=i.W||null!=i.E?(u=1,l=4,r=bt(i.GG,s._a[D],Be(R(),1,4).year),a=bt(i.W,1),((o=bt(i.E,1))<1||7<o)&&(d=!0)):(u=s._locale._week.dow,l=s._locale._week.doy,h=Be(R(),u,l),r=bt(i.gg,s._a[D],h.year),a=bt(i.w,h.week),null!=i.d?((o=i.d)<0||6<o)&&(d=!0):null!=i.e?(o=i.e+u,(i.e<0||6<i.e)&&(d=!0)):o=u),a<1||a>N(r,u,l)?p(s)._overflowWeeks=!0:null!=d?p(s)._overflowWeekday=!0:(h=$e(r,a,o,u,l),s._a[D]=h.year,s._dayOfYear=h.dayOfYear)),null!=e._dayOfYear&&(i=bt(e._a[D],n[D]),(e._dayOfYear>We(i)||0===e._dayOfYear)&&(p(e)._overflowDayOfYear=!0),d=ze(i,0,e._dayOfYear),e._a[Y]=d.getUTCMonth(),e._a[S]=d.getUTCDate()),t=0;t<3&&null==e._a[t];++t)e._a[t]=c[t]=n[t];for(;t<7;t++)e._a[t]=c[t]=null==e._a[t]?2===t?1:0:e._a[t];24===e._a[O]&&0===e._a[b]&&0===e._a[T]&&0===e._a[Te]&&(e._nextDay=!0,e._a[O]=0),e._d=(e._useUTC?ze:Ze).apply(null,c),r=e._useUTC?e._d.getUTCDay():e._d.getDay(),null!=e._tzm&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[O]=24),e._w&&void 0!==e._w.d&&e._w.d!==r&&(p(e).weekdayMismatch=!0)}}function xt(e){if(e._f===_.ISO_8601)Yt(e);else if(e._f===_.RFC_2822)Ot(e);else{e._a=[],p(e).empty=!0;for(var t,n,s,i,r,a=""+e._i,o=a.length,u=0,l=ae(e._f,e._locale).match(te)||[],d=l.length,h=0;h<d;h++)n=l[h],(t=(a.match(De(n,e))||[])[0])&&(0<(s=a.substr(0,a.indexOf(t))).length&&p(e).unusedInput.push(s),a=a.slice(a.indexOf(t)+t.length),u+=t.length),ie[n]?(t?p(e).empty=!1:p(e).unusedTokens.push(n),s=n,r=e,null!=(i=t)&&c(Se,s)&&Se[s](i,r._a,r,s)):e._strict&&!t&&p(e).unusedTokens.push(n);p(e).charsLeftOver=o-u,0<a.length&&p(e).unusedInput.push(a),e._a[O]<=12&&!0===p(e).bigHour&&0<e._a[O]&&(p(e).bigHour=void 0),p(e).parsedDateParts=e._a.slice(0),p(e).meridiem=e._meridiem,e._a[O]=function(e,t,n){if(null==n)return t;return null!=e.meridiemHour?e.meridiemHour(t,n):null!=e.isPM?((e=e.isPM(n))&&t<12&&(t+=12),t=e||12!==t?t:0):t}(e._locale,e._a[O],e._meridiem),null!==(o=p(e).era)&&(e._a[D]=e._locale.erasConvertYear(o,e._a[D])),Tt(e),_t(e)}}function Nt(e){var t,n,s,i=e._i,r=e._f;if(e._locale=e._locale||P(e._l),null===i||void 0===r&&""===i)return I({nullInput:!0});if("string"==typeof i&&(e._i=i=e._locale.preparse(i)),k(i))return new $(_t(i));if(V(i))e._d=i;else if(y(r)){var a,o,u,l,d,h,c=e,f=!1,m=c._f.length;if(0===m)p(c).invalidFormat=!0,c._d=new Date(NaN);else{for(l=0;l<m;l++)d=0,h=!1,a=q({},c),null!=c._useUTC&&(a._useUTC=c._useUTC),a._f=c._f[l],xt(a),A(a)&&(h=!0),d=(d+=p(a).charsLeftOver)+10*p(a).unusedTokens.length,p(a).score=d,f?d<u&&(u=d,o=a):(null==u||d<u||h)&&(u=d,o=a,h)&&(f=!0);E(c,o||a)}}else if(r)xt(e);else if(g(r=(i=e)._i))i._d=new Date(_.now());else V(r)?i._d=new Date(r.valueOf()):"string"==typeof r?(n=i,null!==(t=Mt.exec(n._i))?n._d=new Date(+t[1]):(Yt(n),!1===n._isValid&&(delete n._isValid,Ot(n),!1===n._isValid)&&(delete n._isValid,n._strict?n._isValid=!1:_.createFromInputFallback(n)))):y(r)?(i._a=G(r.slice(0),function(e){return parseInt(e,10)}),Tt(i)):F(r)?(t=i)._d||(s=void 0===(n=ue(t._i)).day?n.date:n.day,t._a=G([n.year,n.month,s,n.hour,n.minute,n.second,n.millisecond],function(e){return e&&parseInt(e,10)}),Tt(t)):w(r)?i._d=new Date(r):_.createFromInputFallback(i);return A(e)||(e._d=null),e}function Wt(e,t,n,s,i){var r={};return!0!==t&&!1!==t||(s=t,t=void 0),!0!==n&&!1!==n||(s=n,n=void 0),(F(e)&&L(e)||y(e)&&0===e.length)&&(e=void 0),r._isAMomentObject=!0,r._useUTC=r._isUTC=i,r._l=n,r._i=e,r._f=t,r._strict=s,(i=new $(_t(Nt(i=r))))._nextDay&&(i.add(1,"d"),i._nextDay=void 0),i}function R(e,t,n,s){return Wt(e,t,n,s,!1)}_.createFromInputFallback=e("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))}),_.ISO_8601=function(){},_.RFC_2822=function(){};me=e("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=R.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:I()}),_e=e("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=R.apply(null,arguments);return this.isValid()&&e.isValid()?this<e?this:e:I()});function Pt(e,t){var n,s;if(!(t=1===t.length&&y(t[0])?t[0]:t).length)return R();for(n=t[0],s=1;s<t.length;++s)t[s].isValid()&&!t[s][e](n)||(n=t[s]);return n}var Rt=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ct(e){var e=ue(e),t=e.year||0,n=e.quarter||0,s=e.month||0,i=e.week||e.isoWeek||0,r=e.day||0,a=e.hour||0,o=e.minute||0,u=e.second||0,l=e.millisecond||0;this._isValid=function(e){var t,n,s=!1,i=Rt.length;for(t in e)if(c(e,t)&&(-1===x.call(Rt,t)||null!=e[t]&&isNaN(e[t])))return!1;for(n=0;n<i;++n)if(e[Rt[n]]){if(s)return!1;parseFloat(e[Rt[n]])!==M(e[Rt[n]])&&(s=!0)}return!0}(e),this._milliseconds=+l+1e3*u+6e4*o+1e3*a*60*60,this._days=+r+7*i,this._months=+s+3*n+12*t,this._data={},this._locale=P(),this._bubble()}function Ut(e){return e instanceof Ct}function Ht(e){return e<0?-1*Math.round(-1*e):Math.round(e)}function Ft(e,n){s(e,0,0,function(){var e=this.utcOffset(),t="+";return e<0&&(e=-e,t="-"),t+r(~~(e/60),2)+n+r(~~e%60,2)})}Ft("Z",":"),Ft("ZZ",""),h("Z",ve),h("ZZ",ve),v(["Z","ZZ"],function(e,t,n){n._useUTC=!0,n._tzm=Vt(ve,e)});var Lt=/([\+\-]|\d\d)/gi;function Vt(e,t){var t=(t||"").match(e);return null===t?null:0===(t=60*(e=((t[t.length-1]||[])+"").match(Lt)||["-",0,0])[1]+M(e[2]))?0:"+"===e[0]?t:-t}function Gt(e,t){var n;return t._isUTC?(t=t.clone(),n=(k(e)||V(e)?e:R(e)).valueOf()-t.valueOf(),t._d.setTime(t._d.valueOf()+n),_.updateOffset(t,!1),t):R(e).local()}function Et(e){return-Math.round(e._d.getTimezoneOffset())}function At(){return!!this.isValid()&&this._isUTC&&0===this._offset}_.updateOffset=function(){};var It=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,jt=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function C(e,t){var n,s=e;return Ut(e)?s={ms:e._milliseconds,d:e._days,M:e._months}:w(e)||!isNaN(+e)?(s={},t?s[t]=+e:s.milliseconds=+e):(t=It.exec(e))?(n="-"===t[1]?-1:1,s={y:0,d:M(t[S])*n,h:M(t[O])*n,m:M(t[b])*n,s:M(t[T])*n,ms:M(Ht(1e3*t[Te]))*n}):(t=jt.exec(e))?(n="-"===t[1]?-1:1,s={y:Zt(t[2],n),M:Zt(t[3],n),w:Zt(t[4],n),d:Zt(t[5],n),h:Zt(t[6],n),m:Zt(t[7],n),s:Zt(t[8],n)}):null==s?s={}:"object"==typeof s&&("from"in s||"to"in s)&&(t=function(e,t){var n;if(!e.isValid()||!t.isValid())return{milliseconds:0,months:0};t=Gt(t,e),e.isBefore(t)?n=zt(e,t):((n=zt(t,e)).milliseconds=-n.milliseconds,n.months=-n.months);return n}(R(s.from),R(s.to)),(s={}).ms=t.milliseconds,s.M=t.months),n=new Ct(s),Ut(e)&&c(e,"_locale")&&(n._locale=e._locale),Ut(e)&&c(e,"_isValid")&&(n._isValid=e._isValid),n}function Zt(e,t){e=e&&parseFloat(e.replace(",","."));return(isNaN(e)?0:e)*t}function zt(e,t){var n={};return n.months=t.month()-e.month()+12*(t.year()-e.year()),e.clone().add(n.months,"M").isAfter(t)&&--n.months,n.milliseconds=+t-+e.clone().add(n.months,"M"),n}function qt(s,i){return function(e,t){var n;return null===t||isNaN(+t)||(Q(i,"moment()."+i+"(period, number) is deprecated. Please use moment()."+i+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),n=e,e=t,t=n),$t(this,C(e,t),s),this}}function $t(e,t,n,s){var i=t._milliseconds,r=Ht(t._days),t=Ht(t._months);e.isValid()&&(s=null==s||s,t&&Ae(e,Ce(e,"Month")+t*n),r&&Ue(e,"Date",Ce(e,"Date")+r*n),i&&e._d.setTime(e._d.valueOf()+i*n),s)&&_.updateOffset(e,r||t)}C.fn=Ct.prototype,C.invalid=function(){return C(NaN)};Fe=qt(1,"add"),Qe=qt(-1,"subtract");function Bt(e){return"string"==typeof e||e instanceof String}function Jt(e){return k(e)||V(e)||Bt(e)||w(e)||function(t){var e=y(t),n=!1;e&&(n=0===t.filter(function(e){return!w(e)&&Bt(t)}).length);return e&&n}(e)||function(e){var t,n,s=F(e)&&!L(e),i=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],a=r.length;for(t=0;t<a;t+=1)n=r[t],i=i||c(e,n);return s&&i}(e)||null==e}function Qt(e,t){var n,s;return e.date()<t.date()?-Qt(t,e):-((n=12*(t.year()-e.year())+(t.month()-e.month()))+(t-(s=e.clone().add(n,"months"))<0?(t-s)/(s-e.clone().add(n-1,"months")):(t-s)/(e.clone().add(1+n,"months")-s)))||0}function Xt(e){return void 0===e?this._locale._abbr:(null!=(e=P(e))&&(this._locale=e),this)}_.defaultFormat="YYYY-MM-DDTHH:mm:ssZ",_.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";Ke=e("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return void 0===e?this.localeData():this.locale(e)});function Kt(){return this._locale}var en=126227808e5;function tn(e,t){return(e%t+t)%t}function nn(e,t,n){return e<100&&0<=e?new Date(e+400,t,n)-en:new Date(e,t,n).valueOf()}function sn(e,t,n){return e<100&&0<=e?Date.UTC(e+400,t,n)-en:Date.UTC(e,t,n)}function rn(e,t){return t.erasAbbrRegex(e)}function an(){for(var e,t,n,s=[],i=[],r=[],a=[],o=this.eras(),u=0,l=o.length;u<l;++u)e=f(o[u].name),t=f(o[u].abbr),n=f(o[u].narrow),i.push(e),s.push(t),r.push(n),a.push(e),a.push(t),a.push(n);this._erasRegex=new RegExp("^("+a.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+i.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+s.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+r.join("|")+")","i")}function on(e,t){s(0,[e,e.length],0,t)}function un(e,t,n,s,i){var r;return null==e?Be(this,s,i).year:(r=N(e,s,i),function(e,t,n,s,i){e=$e(e,t,n,s,i),t=ze(e.year,0,e.dayOfYear);return this.year(t.getUTCFullYear()),this.month(t.getUTCMonth()),this.date(t.getUTCDate()),this}.call(this,e,t=r<t?r:t,n,s,i))}s("N",0,0,"eraAbbr"),s("NN",0,0,"eraAbbr"),s("NNN",0,0,"eraAbbr"),s("NNNN",0,0,"eraName"),s("NNNNN",0,0,"eraNarrow"),s("y",["y",1],"yo","eraYear"),s("y",["yy",2],0,"eraYear"),s("y",["yyy",3],0,"eraYear"),s("y",["yyyy",4],0,"eraYear"),h("N",rn),h("NN",rn),h("NNN",rn),h("NNNN",function(e,t){return t.erasNameRegex(e)}),h("NNNNN",function(e,t){return t.erasNarrowRegex(e)}),v(["N","NN","NNN","NNNN","NNNNN"],function(e,t,n,s){s=n._locale.erasParse(e,s,n._strict);s?p(n).era=s:p(n).invalidEra=e}),h("y",pe),h("yy",pe),h("yyy",pe),h("yyyy",pe),h("yo",function(e,t){return t._eraYearOrdinalRegex||pe}),v(["y","yy","yyy","yyyy"],D),v(["yo"],function(e,t,n,s){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),n._locale.eraYearOrdinalParse?t[D]=n._locale.eraYearOrdinalParse(e,i):t[D]=parseInt(e,10)}),s(0,["gg",2],0,function(){return this.weekYear()%100}),s(0,["GG",2],0,function(){return this.isoWeekYear()%100}),on("gggg","weekYear"),on("ggggg","weekYear"),on("GGGG","isoWeekYear"),on("GGGGG","isoWeekYear"),h("G",ke),h("g",ke),h("GG",n,t),h("gg",n,t),h("GGGG",ge,ce),h("gggg",ge,ce),h("GGGGG",we,fe),h("ggggg",we,fe),Oe(["gggg","ggggg","GGGG","GGGGG"],function(e,t,n,s){t[s.substr(0,2)]=M(e)}),Oe(["gg","GG"],function(e,t,n,s){t[s]=_.parseTwoDigitYear(e)}),s("Q",0,"Qo","quarter"),h("Q",de),v("Q",function(e,t){t[Y]=3*(M(e)-1)}),s("D",["DD",2],"Do","date"),h("D",n,u),h("DD",n,t),h("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),v(["D","DD"],S),v("Do",function(e,t){t[S]=M(e.match(n)[0])});ge=Re("Date",!0);s("DDD",["DDDD",3],"DDDo","dayOfYear"),h("DDD",ye),h("DDDD",he),v(["DDD","DDDD"],function(e,t,n){n._dayOfYear=M(e)}),s("m",["mm",2],0,"minute"),h("m",n,d),h("mm",n,t),v(["m","mm"],b);var ln,ce=Re("Minutes",!1),we=(s("s",["ss",2],0,"second"),h("s",n,d),h("ss",n,t),v(["s","ss"],T),Re("Seconds",!1));for(s("S",0,0,function(){return~~(this.millisecond()/100)}),s(0,["SS",2],0,function(){return~~(this.millisecond()/10)}),s(0,["SSS",3],0,"millisecond"),s(0,["SSSS",4],0,function(){return 10*this.millisecond()}),s(0,["SSSSS",5],0,function(){return 100*this.millisecond()}),s(0,["SSSSSS",6],0,function(){return 1e3*this.millisecond()}),s(0,["SSSSSSS",7],0,function(){return 1e4*this.millisecond()}),s(0,["SSSSSSSS",8],0,function(){return 1e5*this.millisecond()}),s(0,["SSSSSSSSS",9],0,function(){return 1e6*this.millisecond()}),h("S",ye,de),h("SS",ye,t),h("SSS",ye,he),ln="SSSS";ln.length<=9;ln+="S")h(ln,pe);function dn(e,t){t[Te]=M(1e3*("0."+e))}for(ln="S";ln.length<=9;ln+="S")v(ln,dn);fe=Re("Milliseconds",!1),s("z",0,0,"zoneAbbr"),s("zz",0,0,"zoneName");u=$.prototype;function hn(e){return e}u.add=Fe,u.calendar=function(e,t){1===arguments.length&&(arguments[0]?Jt(arguments[0])?(e=arguments[0],t=void 0):function(e){for(var t=F(e)&&!L(e),n=!1,s=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],i=0;i<s.length;i+=1)n=n||c(e,s[i]);return t&&n}(arguments[0])&&(t=arguments[0],e=void 0):t=e=void 0);var e=e||R(),n=Gt(e,this).startOf("day"),n=_.calendarFormat(this,n)||"sameElse",t=t&&(a(t[n])?t[n].call(this,e):t[n]);return this.format(t||this.localeData().calendar(n,this,R(e)))},u.clone=function(){return new $(this)},u.diff=function(e,t,n){var s,i,r;if(!this.isValid())return NaN;if(!(s=Gt(e,this)).isValid())return NaN;switch(i=6e4*(s.utcOffset()-this.utcOffset()),t=o(t)){case"year":r=Qt(this,s)/12;break;case"month":r=Qt(this,s);break;case"quarter":r=Qt(this,s)/3;break;case"second":r=(this-s)/1e3;break;case"minute":r=(this-s)/6e4;break;case"hour":r=(this-s)/36e5;break;case"day":r=(this-s-i)/864e5;break;case"week":r=(this-s-i)/6048e5;break;default:r=this-s}return n?r:m(r)},u.endOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year()+1,0,1)-1;break;case"quarter":t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=n(this.year(),this.month()+1,1)-1;break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=n(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=36e5-tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5)-1;break;case"minute":t=this._d.valueOf(),t+=6e4-tn(t,6e4)-1;break;case"second":t=this._d.valueOf(),t+=1e3-tn(t,1e3)-1;break}this._d.setTime(t),_.updateOffset(this,!0)}return this},u.format=function(e){return e=e||(this.isUtc()?_.defaultFormatUtc:_.defaultFormat),e=re(this,e),this.localeData().postformat(e)},u.from=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||R(e).isValid())?C({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},u.fromNow=function(e){return this.from(R(),e)},u.to=function(e,t){return this.isValid()&&(k(e)&&e.isValid()||R(e).isValid())?C({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()},u.toNow=function(e){return this.to(R(),e)},u.get=function(e){return a(this[e=o(e)])?this[e]():this},u.invalidAt=function(){return p(this).overflow},u.isAfter=function(e,t){return e=k(e)?e:R(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()>e.valueOf():e.valueOf()<this.clone().startOf(t).valueOf())},u.isBefore=function(e,t){return e=k(e)?e:R(e),!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()<e.valueOf():this.clone().endOf(t).valueOf()<e.valueOf())},u.isBetween=function(e,t,n,s){return e=k(e)?e:R(e),t=k(t)?t:R(t),!!(this.isValid()&&e.isValid()&&t.isValid())&&("("===(s=s||"()")[0]?this.isAfter(e,n):!this.isBefore(e,n))&&(")"===s[1]?this.isBefore(t,n):!this.isAfter(t,n))},u.isSame=function(e,t){var e=k(e)?e:R(e);return!(!this.isValid()||!e.isValid())&&("millisecond"===(t=o(t)||"millisecond")?this.valueOf()===e.valueOf():(e=e.valueOf(),this.clone().startOf(t).valueOf()<=e&&e<=this.clone().endOf(t).valueOf()))},u.isSameOrAfter=function(e,t){return this.isSame(e,t)||this.isAfter(e,t)},u.isSameOrBefore=function(e,t){return this.isSame(e,t)||this.isBefore(e,t)},u.isValid=function(){return A(this)},u.lang=Ke,u.locale=Xt,u.localeData=Kt,u.max=_e,u.min=me,u.parsingFlags=function(){return E({},p(this))},u.set=function(e,t){if("object"==typeof e)for(var n=function(e){var t,n=[];for(t in e)c(e,t)&&n.push({unit:t,priority:le[t]});return n.sort(function(e,t){return e.priority-t.priority}),n}(e=ue(e)),s=n.length,i=0;i<s;i++)this[n[i].unit](e[n[i].unit]);else if(a(this[e=o(e)]))return this[e](t);return this},u.startOf=function(e){var t,n;if(void 0!==(e=o(e))&&"millisecond"!==e&&this.isValid()){switch(n=this._isUTC?sn:nn,e){case"year":t=n(this.year(),0,1);break;case"quarter":t=n(this.year(),this.month()-this.month()%3,1);break;case"month":t=n(this.year(),this.month(),1);break;case"week":t=n(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=n(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=tn(t+(this._isUTC?0:6e4*this.utcOffset()),36e5);break;case"minute":t=this._d.valueOf(),t-=tn(t,6e4);break;case"second":t=this._d.valueOf(),t-=tn(t,1e3);break}this._d.setTime(t),_.updateOffset(this,!0)}return this},u.subtract=Qe,u.toArray=function(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]},u.toObject=function(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}},u.toDate=function(){return new Date(this.valueOf())},u.toISOString=function(e){var t;return this.isValid()?(t=(e=!0!==e)?this.clone().utc():this).year()<0||9999<t.year()?re(t,e?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):a(Date.prototype.toISOString)?e?this.toDate().toISOString():new Date(this.valueOf()+60*this.utcOffset()*1e3).toISOString().replace("Z",re(t,"Z")):re(t,e?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ"):null},u.inspect=function(){var e,t,n;return this.isValid()?(t="moment",e="",this.isLocal()||(t=0===this.utcOffset()?"moment.utc":"moment.parseZone",e="Z"),t="["+t+'("]',n=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",this.format(t+n+"-MM-DD[T]HH:mm:ss.SSS"+(e+'[")]'))):"moment.invalid(/* "+this._i+" */)"},"undefined"!=typeof Symbol&&null!=Symbol.for&&(u[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"}),u.toJSON=function(){return this.isValid()?this.toISOString():null},u.toString=function(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")},u.unix=function(){return Math.floor(this.valueOf()/1e3)},u.valueOf=function(){return this._d.valueOf()-6e4*(this._offset||0)},u.creationData=function(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}},u.eraName=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].name;if(t[n].until<=e&&e<=t[n].since)return t[n].name}return""},u.eraNarrow=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].narrow;if(t[n].until<=e&&e<=t[n].since)return t[n].narrow}return""},u.eraAbbr=function(){for(var e,t=this.localeData().eras(),n=0,s=t.length;n<s;++n){if(e=this.clone().startOf("day").valueOf(),t[n].since<=e&&e<=t[n].until)return t[n].abbr;if(t[n].until<=e&&e<=t[n].since)return t[n].abbr}return""},u.eraYear=function(){for(var e,t,n=this.localeData().eras(),s=0,i=n.length;s<i;++s)if(e=n[s].since<=n[s].until?1:-1,t=this.clone().startOf("day").valueOf(),n[s].since<=t&&t<=n[s].until||n[s].until<=t&&t<=n[s].since)return(this.year()-_(n[s].since).year())*e+n[s].offset;return this.year()},u.year=Pe,u.isLeapYear=function(){return be(this.year())},u.weekYear=function(e){return un.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)},u.isoWeekYear=function(e){return un.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)},u.quarter=u.quarters=function(e){return null==e?Math.ceil((this.month()+1)/3):this.month(3*(e-1)+this.month()%3)},u.month=Ie,u.daysInMonth=function(){return He(this.year(),this.month())},u.week=u.weeks=function(e){var t=this.localeData().week(this);return null==e?t:this.add(7*(e-t),"d")},u.isoWeek=u.isoWeeks=function(e){var t=Be(this,1,4).week;return null==e?t:this.add(7*(e-t),"d")},u.weeksInYear=function(){var e=this.localeData()._week;return N(this.year(),e.dow,e.doy)},u.weeksInWeekYear=function(){var e=this.localeData()._week;return N(this.weekYear(),e.dow,e.doy)},u.isoWeeksInYear=function(){return N(this.year(),1,4)},u.isoWeeksInISOWeekYear=function(){return N(this.isoWeekYear(),1,4)},u.date=ge,u.day=u.days=function(e){var t,n,s;return this.isValid()?(t=Ce(this,"Day"),null!=e?(n=e,s=this.localeData(),e="string"!=typeof n?n:isNaN(n)?"number"==typeof(n=s.weekdaysParse(n))?n:null:parseInt(n,10),this.add(e-t,"d")):t):null!=e?this:NaN},u.weekday=function(e){var t;return this.isValid()?(t=(this.day()+7-this.localeData()._week.dow)%7,null==e?t:this.add(e-t,"d")):null!=e?this:NaN},u.isoWeekday=function(e){var t,n;return this.isValid()?null!=e?(t=e,n=this.localeData(),n="string"==typeof t?n.weekdaysParse(t)%7||7:isNaN(t)?null:t,this.day(this.day()%7?n:n-7)):this.day()||7:null!=e?this:NaN},u.dayOfYear=function(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return null==e?t:this.add(e-t,"d")},u.hour=u.hours=i,u.minute=u.minutes=ce,u.second=u.seconds=we,u.millisecond=u.milliseconds=fe,u.utcOffset=function(e,t,n){var s,i=this._offset||0;if(!this.isValid())return null!=e?this:NaN;if(null==e)return this._isUTC?i:Et(this);if("string"==typeof e){if(null===(e=Vt(ve,e)))return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(s=Et(this)),this._offset=e,this._isUTC=!0,null!=s&&this.add(s,"m"),i!==e&&(!t||this._changeInProgress?$t(this,C(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,_.updateOffset(this,!0),this._changeInProgress=null)),this},u.utc=function(e){return this.utcOffset(0,e)},u.local=function(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e)&&this.subtract(Et(this),"m"),this},u.parseZone=function(){var e;return null!=this._tzm?this.utcOffset(this._tzm,!1,!0):"string"==typeof this._i&&(null!=(e=Vt(Me,this._i))?this.utcOffset(e):this.utcOffset(0,!0)),this},u.hasAlignedHourOffset=function(e){return!!this.isValid()&&(e=e?R(e).utcOffset():0,(this.utcOffset()-e)%60==0)},u.isDST=function(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()},u.isLocal=function(){return!!this.isValid()&&!this._isUTC},u.isUtcOffset=function(){return!!this.isValid()&&this._isUTC},u.isUtc=At,u.isUTC=At,u.zoneAbbr=function(){return this._isUTC?"UTC":""},u.zoneName=function(){return this._isUTC?"Coordinated Universal Time":""},u.dates=e("dates accessor is deprecated. Use date instead.",ge),u.months=e("months accessor is deprecated. Use month instead",Ie),u.years=e("years accessor is deprecated. Use year instead",Pe),u.zone=e("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",function(e,t){return null!=e?(this.utcOffset(e="string"!=typeof e?-e:e,t),this):-this.utcOffset()}),u.isDSTShifted=e("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",function(){var e,t;return g(this._isDSTShifted)&&(q(e={},this),(e=Nt(e))._a?(t=(e._isUTC?l:R)(e._a),this._isDSTShifted=this.isValid()&&0<function(e,t,n){for(var s=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),r=0,a=0;a<s;a++)(n&&e[a]!==t[a]||!n&&M(e[a])!==M(t[a]))&&r++;return r+i}(e._a,t.toArray())):this._isDSTShifted=!1),this._isDSTShifted});d=K.prototype;function cn(e,t,n,s){var i=P(),s=l().set(s,t);return i[n](s,e)}function fn(e,t,n){if(w(e)&&(t=e,e=void 0),e=e||"",null!=t)return cn(e,t,n,"month");for(var s=[],i=0;i<12;i++)s[i]=cn(e,i,n,"month");return s}function mn(e,t,n,s){t=("boolean"==typeof e?w(t)&&(n=t,t=void 0):(t=e,e=!1,w(n=t)&&(n=t,t=void 0)),t||"");var i,r=P(),a=e?r._week.dow:0,o=[];if(null!=n)return cn(t,(n+a)%7,s,"day");for(i=0;i<7;i++)o[i]=cn(t,(i+a)%7,s,"day");return o}d.calendar=function(e,t,n){return a(e=this._calendar[e]||this._calendar.sameElse)?e.call(t,n):e},d.longDateFormat=function(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(te).map(function(e){return"MMMM"===e||"MM"===e||"DD"===e||"dddd"===e?e.slice(1):e}).join(""),this._longDateFormat[e])},d.invalidDate=function(){return this._invalidDate},d.ordinal=function(e){return this._ordinal.replace("%d",e)},d.preparse=hn,d.postformat=hn,d.relativeTime=function(e,t,n,s){var i=this._relativeTime[n];return a(i)?i(e,t,n,s):i.replace(/%d/i,e)},d.pastFuture=function(e,t){return a(e=this._relativeTime[0<e?"future":"past"])?e(t):e.replace(/%s/i,t)},d.set=function(e){var t,n;for(n in e)c(e,n)&&(a(t=e[n])?this[n]=t:this["_"+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)},d.eras=function(e,t){for(var n,s=this._eras||P("en")._eras,i=0,r=s.length;i<r;++i){switch(typeof s[i].since){case"string":n=_(s[i].since).startOf("day"),s[i].since=n.valueOf();break}switch(typeof s[i].until){case"undefined":s[i].until=1/0;break;case"string":n=_(s[i].until).startOf("day").valueOf(),s[i].until=n.valueOf();break}}return s},d.erasParse=function(e,t,n){var s,i,r,a,o,u=this.eras();for(e=e.toUpperCase(),s=0,i=u.length;s<i;++s)if(r=u[s].name.toUpperCase(),a=u[s].abbr.toUpperCase(),o=u[s].narrow.toUpperCase(),n)switch(t){case"N":case"NN":case"NNN":if(a===e)return u[s];break;case"NNNN":if(r===e)return u[s];break;case"NNNNN":if(o===e)return u[s];break}else if(0<=[r,a,o].indexOf(e))return u[s]},d.erasConvertYear=function(e,t){var n=e.since<=e.until?1:-1;return void 0===t?_(e.since).year():_(e.since).year()+(t-e.offset)*n},d.erasAbbrRegex=function(e){return c(this,"_erasAbbrRegex")||an.call(this),e?this._erasAbbrRegex:this._erasRegex},d.erasNameRegex=function(e){return c(this,"_erasNameRegex")||an.call(this),e?this._erasNameRegex:this._erasRegex},d.erasNarrowRegex=function(e){return c(this,"_erasNarrowRegex")||an.call(this),e?this._erasNarrowRegex:this._erasRegex},d.months=function(e,t){return e?(y(this._months)?this._months:this._months[(this._months.isFormat||Ve).test(t)?"format":"standalone"])[e.month()]:y(this._months)?this._months:this._months.standalone},d.monthsShort=function(e,t){return e?(y(this._monthsShort)?this._monthsShort:this._monthsShort[Ve.test(t)?"format":"standalone"])[e.month()]:y(this._monthsShort)?this._monthsShort:this._monthsShort.standalone},d.monthsParse=function(e,t,n){var s,i;if(this._monthsParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],s=0;s<12;++s)r=l([2e3,s]),this._shortMonthsParse[s]=this.monthsShort(r,"").toLocaleLowerCase(),this._longMonthsParse[s]=this.months(r,"").toLocaleLowerCase();return n?"MMM"===t?-1!==(i=x.call(this._shortMonthsParse,e))?i:null:-1!==(i=x.call(this._longMonthsParse,e))?i:null:"MMM"===t?-1!==(i=x.call(this._shortMonthsParse,e))||-1!==(i=x.call(this._longMonthsParse,e))?i:null:-1!==(i=x.call(this._longMonthsParse,e))||-1!==(i=x.call(this._shortMonthsParse,e))?i:null}.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),s=0;s<12;s++){if(i=l([2e3,s]),n&&!this._longMonthsParse[s]&&(this._longMonthsParse[s]=new RegExp("^"+this.months(i,"").replace(".","")+"$","i"),this._shortMonthsParse[s]=new RegExp("^"+this.monthsShort(i,"").replace(".","")+"$","i")),n||this._monthsParse[s]||(i="^"+this.months(i,"")+"|^"+this.monthsShort(i,""),this._monthsParse[s]=new RegExp(i.replace(".",""),"i")),n&&"MMMM"===t&&this._longMonthsParse[s].test(e))return s;if(n&&"MMM"===t&&this._shortMonthsParse[s].test(e))return s;if(!n&&this._monthsParse[s].test(e))return s}},d.monthsRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||je.call(this),e?this._monthsStrictRegex:this._monthsRegex):(c(this,"_monthsRegex")||(this._monthsRegex=Ee),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)},d.monthsShortRegex=function(e){return this._monthsParseExact?(c(this,"_monthsRegex")||je.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(c(this,"_monthsShortRegex")||(this._monthsShortRegex=Ge),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)},d.week=function(e){return Be(e,this._week.dow,this._week.doy).week},d.firstDayOfYear=function(){return this._week.doy},d.firstDayOfWeek=function(){return this._week.dow},d.weekdays=function(e,t){return t=y(this._weekdays)?this._weekdays:this._weekdays[e&&!0!==e&&this._weekdays.isFormat.test(t)?"format":"standalone"],!0===e?Je(t,this._week.dow):e?t[e.day()]:t},d.weekdaysMin=function(e){return!0===e?Je(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin},d.weekdaysShort=function(e){return!0===e?Je(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort},d.weekdaysParse=function(e,t,n){var s,i;if(this._weekdaysParseExact)return function(e,t,n){var s,i,r,e=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],s=0;s<7;++s)r=l([2e3,1]).day(s),this._minWeekdaysParse[s]=this.weekdaysMin(r,"").toLocaleLowerCase(),this._shortWeekdaysParse[s]=this.weekdaysShort(r,"").toLocaleLowerCase(),this._weekdaysParse[s]=this.weekdays(r,"").toLocaleLowerCase();return n?"dddd"===t?-1!==(i=x.call(this._weekdaysParse,e))?i:null:"ddd"===t?-1!==(i=x.call(this._shortWeekdaysParse,e))?i:null:-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:"dddd"===t?-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._shortWeekdaysParse,e))||-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:"ddd"===t?-1!==(i=x.call(this._shortWeekdaysParse,e))||-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._minWeekdaysParse,e))?i:null:-1!==(i=x.call(this._minWeekdaysParse,e))||-1!==(i=x.call(this._weekdaysParse,e))||-1!==(i=x.call(this._shortWeekdaysParse,e))?i:null}.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),s=0;s<7;s++){if(i=l([2e3,1]).day(s),n&&!this._fullWeekdaysParse[s]&&(this._fullWeekdaysParse[s]=new RegExp("^"+this.weekdays(i,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[s]=new RegExp("^"+this.weekdaysShort(i,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[s]=new RegExp("^"+this.weekdaysMin(i,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[s]||(i="^"+this.weekdays(i,"")+"|^"+this.weekdaysShort(i,"")+"|^"+this.weekdaysMin(i,""),this._weekdaysParse[s]=new RegExp(i.replace(".",""),"i")),n&&"dddd"===t&&this._fullWeekdaysParse[s].test(e))return s;if(n&&"ddd"===t&&this._shortWeekdaysParse[s].test(e))return s;if(n&&"dd"===t&&this._minWeekdaysParse[s].test(e))return s;if(!n&&this._weekdaysParse[s].test(e))return s}},d.weekdaysRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(c(this,"_weekdaysRegex")||(this._weekdaysRegex=et),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)},d.weekdaysShortRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(c(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=tt),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)},d.weekdaysMinRegex=function(e){return this._weekdaysParseExact?(c(this,"_weekdaysRegex")||st.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(c(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=nt),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)},d.isPM=function(e){return"p"===(e+"").toLowerCase().charAt(0)},d.meridiem=function(e,t,n){return 11<e?n?"pm":"PM":n?"am":"AM"},ft("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(1===M(e%100/10)?"th":1==t?"st":2==t?"nd":3==t?"rd":"th")}}),_.lang=e("moment.lang is deprecated. Use moment.locale instead.",ft),_.langData=e("moment.langData is deprecated. Use moment.localeData instead.",P);var _n=Math.abs;function yn(e,t,n,s){t=C(t,n);return e._milliseconds+=s*t._milliseconds,e._days+=s*t._days,e._months+=s*t._months,e._bubble()}function gn(e){return e<0?Math.floor(e):Math.ceil(e)}function wn(e){return 4800*e/146097}function pn(e){return 146097*e/4800}function kn(e){return function(){return this.as(e)}}de=kn("ms"),t=kn("s"),ye=kn("m"),he=kn("h"),Fe=kn("d"),_e=kn("w"),me=kn("M"),Qe=kn("Q"),i=kn("y"),ce=de;function Mn(e){return function(){return this.isValid()?this._data[e]:NaN}}var we=Mn("milliseconds"),fe=Mn("seconds"),ge=Mn("minutes"),Pe=Mn("hours"),d=Mn("days"),vn=Mn("months"),Dn=Mn("years");var Yn=Math.round,Sn={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function On(e,t,n,s){var i=C(e).abs(),r=Yn(i.as("s")),a=Yn(i.as("m")),o=Yn(i.as("h")),u=Yn(i.as("d")),l=Yn(i.as("M")),d=Yn(i.as("w")),i=Yn(i.as("y")),r=(r<=n.ss?["s",r]:r<n.s&&["ss",r])||(a<=1?["m"]:a<n.m&&["mm",a])||(o<=1?["h"]:o<n.h&&["hh",o])||(u<=1?["d"]:u<n.d&&["dd",u]);return(r=(r=null!=n.w?r||(d<=1?["w"]:d<n.w&&["ww",d]):r)||(l<=1?["M"]:l<n.M&&["MM",l])||(i<=1?["y"]:["yy",i]))[2]=t,r[3]=0<+e,r[4]=s,function(e,t,n,s,i){return i.relativeTime(t||1,!!n,e,s)}.apply(null,r)}var bn=Math.abs;function Tn(e){return(0<e)-(e<0)||+e}function xn(){var e,t,n,s,i,r,a,o,u,l,d;return this.isValid()?(e=bn(this._milliseconds)/1e3,t=bn(this._days),n=bn(this._months),(o=this.asSeconds())?(s=m(e/60),i=m(s/60),e%=60,s%=60,r=m(n/12),n%=12,a=e?e.toFixed(3).replace(/\.?0+$/,""):"",u=Tn(this._months)!==Tn(o)?"-":"",l=Tn(this._days)!==Tn(o)?"-":"",d=Tn(this._milliseconds)!==Tn(o)?"-":"",(o<0?"-":"")+"P"+(r?u+r+"Y":"")+(n?u+n+"M":"")+(t?l+t+"D":"")+(i||s||e?"T":"")+(i?d+i+"H":"")+(s?d+s+"M":"")+(e?d+a+"S":"")):"P0D"):this.localeData().invalidDate()}var U=Ct.prototype;return U.isValid=function(){return this._isValid},U.abs=function(){var e=this._data;return this._milliseconds=_n(this._milliseconds),this._days=_n(this._days),this._months=_n(this._months),e.milliseconds=_n(e.milliseconds),e.seconds=_n(e.seconds),e.minutes=_n(e.minutes),e.hours=_n(e.hours),e.months=_n(e.months),e.years=_n(e.years),this},U.add=function(e,t){return yn(this,e,t,1)},U.subtract=function(e,t){return yn(this,e,t,-1)},U.as=function(e){if(!this.isValid())return NaN;var t,n,s=this._milliseconds;if("month"===(e=o(e))||"quarter"===e||"year"===e)switch(t=this._days+s/864e5,n=this._months+wn(t),e){case"month":return n;case"quarter":return n/3;case"year":return n/12}else switch(t=this._days+Math.round(pn(this._months)),e){case"week":return t/7+s/6048e5;case"day":return t+s/864e5;case"hour":return 24*t+s/36e5;case"minute":return 1440*t+s/6e4;case"second":return 86400*t+s/1e3;case"millisecond":return Math.floor(864e5*t)+s;default:throw new Error("Unknown unit "+e)}},U.asMilliseconds=de,U.asSeconds=t,U.asMinutes=ye,U.asHours=he,U.asDays=Fe,U.asWeeks=_e,U.asMonths=me,U.asQuarters=Qe,U.asYears=i,U.valueOf=ce,U._bubble=function(){var e=this._milliseconds,t=this._days,n=this._months,s=this._data;return 0<=e&&0<=t&&0<=n||e<=0&&t<=0&&n<=0||(e+=864e5*gn(pn(n)+t),n=t=0),s.milliseconds=e%1e3,e=m(e/1e3),s.seconds=e%60,e=m(e/60),s.minutes=e%60,e=m(e/60),s.hours=e%24,t+=m(e/24),n+=e=m(wn(t)),t-=gn(pn(e)),e=m(n/12),n%=12,s.days=t,s.months=n,s.years=e,this},U.clone=function(){return C(this)},U.get=function(e){return e=o(e),this.isValid()?this[e+"s"]():NaN},U.milliseconds=we,U.seconds=fe,U.minutes=ge,U.hours=Pe,U.days=d,U.weeks=function(){return m(this.days()/7)},U.months=vn,U.years=Dn,U.humanize=function(e,t){var n,s;return this.isValid()?(n=!1,s=Sn,"object"==typeof e&&(t=e,e=!1),"boolean"==typeof e&&(n=e),"object"==typeof t&&(s=Object.assign({},Sn,t),null!=t.s)&&null==t.ss&&(s.ss=t.s-1),e=this.localeData(),t=On(this,!n,s,e),n&&(t=e.pastFuture(+this,t)),e.postformat(t)):this.localeData().invalidDate()},U.toISOString=xn,U.toString=xn,U.toJSON=xn,U.locale=Xt,U.localeData=Kt,U.toIsoString=e("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",xn),U.lang=Ke,s("X",0,0,"unix"),s("x",0,0,"valueOf"),h("x",ke),h("X",/[+-]?\d+(\.\d{1,3})?/),v("X",function(e,t,n){n._d=new Date(1e3*parseFloat(e))}),v("x",function(e,t,n){n._d=new Date(M(e))}),_.version="2.30.1",H=R,_.fn=u,_.min=function(){return Pt("isBefore",[].slice.call(arguments,0))},_.max=function(){return Pt("isAfter",[].slice.call(arguments,0))},_.now=function(){return Date.now?Date.now():+new Date},_.utc=l,_.unix=function(e){return R(1e3*e)},_.months=function(e,t){return fn(e,t,"months")},_.isDate=V,_.locale=ft,_.invalid=I,_.duration=C,_.isMoment=k,_.weekdays=function(e,t,n){return mn(e,t,n,"weekdays")},_.parseZone=function(){return R.apply(null,arguments).parseZone()},_.localeData=P,_.isDuration=Ut,_.monthsShort=function(e,t){return fn(e,t,"monthsShort")},_.weekdaysMin=function(e,t,n){return mn(e,t,n,"weekdaysMin")},_.defineLocale=mt,_.updateLocale=function(e,t){var n,s;return null!=t?(s=ut,null!=W[e]&&null!=W[e].parentLocale?W[e].set(X(W[e]._config,t)):(t=X(s=null!=(n=ct(e))?n._config:s,t),null==n&&(t.abbr=e),(s=new K(t)).parentLocale=W[e],W[e]=s),ft(e)):null!=W[e]&&(null!=W[e].parentLocale?(W[e]=W[e].parentLocale,e===ft()&&ft(e)):null!=W[e]&&delete W[e]),W[e]},_.locales=function(){return ee(W)},_.weekdaysShort=function(e,t,n){return mn(e,t,n,"weekdaysShort")},_.normalizeUnits=o,_.relativeTimeRounding=function(e){return void 0===e?Yn:"function"==typeof e&&(Yn=e,!0)},_.relativeTimeThreshold=function(e,t){return void 0!==Sn[e]&&(void 0===t?Sn[e]:(Sn[e]=t,"s"===e&&(Sn.ss=t-1),!0))},_.calendarFormat=function(e,t){return(e=e.diff(t,"days",!0))<-6?"sameElse":e<-1?"lastWeek":e<0?"lastDay":e<1?"sameDay":e<2?"nextDay":e<7?"nextWeek":"sameElse"},_.prototype=u,_.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"},_});
vendor: 4,990 bytes, line 11614
11614!function(a,i){"use strict";"object"==typeof module&&module.exports?module.exports=i(require("moment")):"function"==typeof define&&define.amd?define(["moment"],i):i(a.moment)}(this,function(o){"use strict";void 0===o.version&&o.default&&(o=o.default);var i,s={},c={},A={},u={},m={},a=(o&&"string"==typeof o.version||y("Moment Timezone requires Moment.js. See https://momentjs.com/timezone/docs/#/use-it/browser/"),o.version.split(".")),r=+a[0],e=+a[1];function n(a){return 96<a?a-87:64<a?a-29:a-48}function t(a){var i=0,r=a.split("."),e=r[0],o=r[1]||"",c=1,A=0,r=1;for(45===a.charCodeAt(0)&&(r=-(i=1));i<e.length;i++)A=60*A+n(e.charCodeAt(i));for(i=0;i<o.length;i++)c/=60,A+=n(o.charCodeAt(i))*c;return A*r}function l(a){for(var i=0;i<a.length;i++)a[i]=t(a[i])}function f(a,i){for(var r=[],e=0;e<i.length;e++)r[e]=a[i[e]];return r}function p(a){for(var a=a.split("|"),i=a[2].split(" "),r=a[3].split(""),e=a[4].split(" "),o=(l(i),l(r),l(e),e),c=r.length,A=0;A<c;A++)o[A]=Math.round((o[A-1]||0)+6e4*o[A]);return o[c-1]=1/0,{name:a[0],abbrs:f(a[1].split(" "),r),offsets:f(i,r),untils:e,population:0|a[5]}}function M(a){a&&this._set(p(a))}function b(a,i){this.name=a,this.zones=i}function h(a){var i=a.toTimeString(),r=i.match(/\([a-z ]+\)/i);"GMT"===(r=r&&r[0]?(r=r[0].match(/[A-Z]/g))?r.join(""):void 0:(r=i.match(/[A-Z]{3,5}/g))?r[0]:void 0)&&(r=void 0),this.at=+a,this.abbr=r,this.offset=a.getTimezoneOffset()}function d(a){this.zone=a,this.offsetScore=0,this.abbrScore=0}function E(){for(var a,i,r,e=(new Date).getFullYear()-2,o=new h(new Date(e,0,1)),c=o.offset,A=[o],n=1;n<48;n++)(r=new Date(e,n,1).getTimezoneOffset())!==c&&(a=function(a,i){for(var r;r=6e4*((i.at-a.at)/12e4|0);)(r=new h(new Date(a.at+r))).offset===a.offset?a=r:i=r;return a}(o,i=new h(new Date(e,n,1))),A.push(a),A.push(new h(new Date(a.at+6e4))),o=i,c=r);for(n=0;n<4;n++)A.push(new h(new Date(e+n,0,1))),A.push(new h(new Date(e+n,6,1)));return A}function g(a,i){return a.offsetScore!==i.offsetScore?a.offsetScore-i.offsetScore:a.abbrScore!==i.abbrScore?a.abbrScore-i.abbrScore:a.zone.population!==i.zone.population?i.zone.population-a.zone.population:i.zone.name.localeCompare(a.zone.name)}function P(){try{var a=Intl.DateTimeFormat().resolvedOptions().timeZone;if(a&&3<a.length){var i=u[S(a)];if(i)return i;y("Moment Timezone found "+a+" from the Intl api, but did not have that data loaded.")}}catch(a){}for(var r,e,o=E(),c=o.length,A=function(a){for(var i,r,e,o=a.length,c={},A=[],n={},t=0;t<o;t++)if(r=a[t].offset,!n.hasOwnProperty(r)){for(i in e=m[r]||{})e.hasOwnProperty(i)&&(c[i]=!0);n[r]=!0}for(t in c)c.hasOwnProperty(t)&&A.push(u[t]);return A}(o),n=[],t=0;t<A.length;t++){for(r=new d(z(A[t])),e=0;e<c;e++)r.scoreOffsetAt(o[e]);n.push(r)}return n.sort(g),0<n.length?n[0].zone.name:void 0}function S(a){return(a||"").toLowerCase().replace(/\//g,"_")}function T(a){var i,r,e,o;for("string"==typeof a&&(a=[a]),i=0;i<a.length;i++){o=S(r=(e=a[i].split("|"))[0]),s[o]=a[i],u[o]=r,A=c=t=n=void 0;var c,A,n=o,t=e[2].split(" ");for(l(t),c=0;c<t.length;c++)A=t[c],m[A]=m[A]||{},m[A][n]=!0}}function z(a,i){a=S(a);var r=s[a];return r instanceof M?r:"string"==typeof r?(r=new M(r),s[a]=r):c[a]&&i!==z&&(i=z(c[a],z))?((r=s[a]=new M)._set(i),r.name=u[a],r):null}function k(a){var i,r,e,o;for("string"==typeof a&&(a=[a]),i=0;i<a.length;i++)e=S((r=a[i].split("|"))[0]),o=S(r[1]),c[e]=o,u[e]=r[0],c[o]=e,u[o]=r[1]}function _(a){T(a.zones),k(a.links);var i,r,e,o=a.countries;if(o&&o.length)for(i=0;i<o.length;i++)r=(e=o[i].split("|"))[0].toUpperCase(),e=e[1].split(" "),A[r]=new b(r,e);L.dataVersion=a.version}function C(a){return C.didShowError||(C.didShowError=!0,y("moment.tz.zoneExists('"+a+"') has been deprecated in favor of !moment.tz.zone('"+a+"')")),!!z(a)}function B(a){var i="X"===a._f||"x"===a._f;return!(!a._a||void 0!==a._tzm||i)}function y(a){"undefined"!=typeof console&&"function"==typeof console.error&&console.error(a)}function L(a){var i=Array.prototype.slice.call(arguments,0,-1),r=arguments[arguments.length-1],i=o.utc.apply(null,i);return!o.isMoment(a)&&B(i)&&(a=z(r))&&i.add(a.parse(i),"minutes"),i.tz(r),i}(r<2||2==r&&e<6)&&y("Moment Timezone requires Moment.js >= 2.6.0. You are using Moment.js "+o.version+". See momentjs.com"),M.prototype={_set:function(a){this.name=a.name,this.abbrs=a.abbrs,this.untils=a.untils,this.offsets=a.offsets,this.population=a.population},_index:function(a){a=function(a,i){var r,e=i.length;if(a<i[0])return 0;if(1<e&&i[e-1]===1/0&&a>=i[e-2])return e-1;if(a>=i[e-1])return-1;for(var o=0,c=e-1;1<c-o;)i[r=Math.floor((o+c)/2)]<=a?o=r:c=r;return c}(+a,this.untils);if(0<=a)return a},countries:function(){var i=this.name;return Object.keys(A).filter(function(a){return-1!==A[a].zones.indexOf(i)})},parse:function(a){for(var i,r,e,o=+a,c=this.offsets,A=this.untils,n=A.length-1,t=0;t<n;t++)if(i=c[t],r=c[t+1],e=c[t&&t-1],i<r&&L.moveAmbiguousForward?i=r:e<i&&L.moveInvalidForward&&(i=e),o<A[t]-6e4*i)return c[t];return c[n]},abbr:function(a){return this.abbrs[this._index(a)]}
vendor: 4,616 bytes, line 11614
11614,offset:function(a){return y("zone.offset has been deprecated in favor of zone.utcOffset"),this.offsets[this._index(a)]},utcOffset:function(a){return this.offsets[this._index(a)]}},d.prototype.scoreOffsetAt=function(a){this.offsetScore+=Math.abs(this.zone.utcOffset(a.at)-a.offset),this.zone.abbr(a.at).replace(/[^A-Z]/g,"")!==a.abbr&&this.abbrScore++},L.version="0.5.45",L.dataVersion="",L._zones=s,L._links=c,L._names=u,L._countries=A,L.add=T,L.link=k,L.load=_,L.zone=z,L.zoneExists=C,L.guess=function(a){return i=i&&!a?i:P()},L.names=function(){var a,i=[];for(a in u)u.hasOwnProperty(a)&&(s[a]||s[c[a]])&&u[a]&&i.push(u[a]);return i.sort()},L.Zone=M,L.unpack=p,L.unpackBase60=t,L.needsOffset=B,L.moveInvalidForward=!0,L.moveAmbiguousForward=!1,L.countries=function(){return Object.keys(A)},L.zonesForCountry=function(a,i){var r;return r=(r=a).toUpperCase(),(a=A[r]||null)?(r=a.zones.sort(),i?r.map(function(a){return{name:a,offset:z(a).utcOffset(new Date)}}):r):null};var D,a=o.fn;function N(a){return function(){return this._z?this._z.abbr(this):a.call(this)}}function O(a){return function(){return this._z=null,a.apply(this,arguments)}}o.tz=L,o.defaultZone=null,o.updateOffset=function(a,i){var r,e=o.defaultZone;void 0===a._z&&(e&&B(a)&&!a._isUTC&&a.isValid()&&(a._d=o.utc(a._a)._d,a.utc().add(e.parse(a),"minutes")),a._z=e),a._z&&(e=a._z.utcOffset(a),Math.abs(e)<16&&(e/=60),void 0!==a.utcOffset?(r=a._z,a.utcOffset(-e,i),a._z=r):a.zone(e,i))},a.tz=function(a,i){if(a){if("string"!=typeof a)throw new Error("Time zone name must be a string, got "+a+" ["+typeof a+"]");return this._z=z(a),this._z?o.updateOffset(this,i):y("Moment Timezone has no data for "+a+". See http://momentjs.com/timezone/docs/#/data-loading/."),this}if(this._z)return this._z.name},a.zoneName=N(a.zoneName),a.zoneAbbr=N(a.zoneAbbr),a.utc=O(a.utc),a.local=O(a.local),a.utcOffset=(D=a.utcOffset,function(){return 0<arguments.length&&(this._z=null),D.apply(this,arguments)}),o.tz.setDefault=function(a){return(r<2||2==r&&e<9)&&y("Moment Timezone setDefault() requires Moment.js >= 2.9.0. You are using Moment.js "+o.version+"."),o.defaultZone=a?z(a):null,o};a=o.momentProperties;return"[object Array]"===Object.prototype.toString.call(a)?(a.push("_z"),a.push("_a")):a&&(a._z=null),_({version:"2024a",zones:["Africa/Abidjan|GMT|0|0||48e5","Africa/Nairobi|EAT|-30|0||47e5","Africa/Algiers|CET|-10|0||26e5","Africa/Lagos|WAT|-10|0||17e6","Africa/Khartoum|CAT|-20|0||51e5","Africa/Cairo|EET EEST|-20 -30|010101010101010|29NW0 1cL0 1cN0 1fz0 1a10 1fz0 1a10 1fz0 1cN0 1cL0 1cN0 1cL0 1cN0 1cL0|15e6","Africa/Casablanca|+01 +00|-10 0|010101010101010101010101|208q0 e00 2600 gM0 2600 e00 2600 gM0 2600 e00 28M0 e00 2600 gM0 2600 e00 28M0 e00 2600 gM0 2600 e00 2600|32e5","Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|11e6","Africa/Johannesburg|SAST|-20|0||84e5","Africa/Juba|EAT CAT|-30 -20|01|24nx0|","Africa/Sao_Tome|WAT GMT|-10 0|01|1XiN0|","Africa/Tripoli|EET|-20|0||11e5","America/Adak|HST HDT|a0 90|01010101010101010101010|1XKc0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|326","America/Anchorage|AKST AKDT|90 80|01010101010101010101010|1XKb0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|30e4","America/Santo_Domingo|AST|40|0||29e5","America/Fortaleza|-03|30|0||34e5","America/Asuncion|-03 -04|30 40|01010101010101010101010|1XPD0 1ip0 17b0 1ip0 19X0 1fB0 19X0 1fB0 19X0 1fB0 19X0 1ip0 17b0 1ip0 17b0 1ip0 19X0 1fB0 19X0 1fB0 19X0 1ip0|28e5","America/Panama|EST|50|0||15e5","America/Mexico_City|CST CDT|60 50|010101010|1XVk0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0|20e6","America/Managua|CST|60|0||22e5","America/Caracas|-04|40|0||29e5","America/Lima|-05|50|0||11e6","America/Denver|MST MDT|70 60|01010101010101010101010|1XK90 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|26e5","America/Campo_Grande|-03 -04|30 40|01|1XBD0|77e4","America/Chicago|CST CDT|60 50|01010101010101010101010|1XK80 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|92e5","America/Chihuahua|MST MDT CST|70 60 60|010101012|1XVl0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0|81e4","America/Ciudad_Juarez|MST MDT CST|70 60 60|010101012010101010101010|1XK90 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1wn0 cm0 EP0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|","America/Phoenix|MST|70|0||42e5","America/Whitehorse|PST PDT MST|80 70 70|01012|1XKa0 1zb0 Op0 1z90|23e3","America/Ne
11614w_York|EST EDT|50 40|01010101010101010101010|1XK70 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|21e6","America/Los_Angeles|PST PDT|80 70|01010101010101010101010|1XKa0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|15e6","America/Halifax|AST ADT|40 30|01010101010101010101010|1XK60 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|39e4","America/Godthab|-03 -02 -01|30 20 10|0101010101212121212121|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 2so0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|17e3","America/Havana|CST CDT|50 40|01010101010101010101010|1XK50 1zc0 Oo0 1zc0 Rc0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Oo0 1zc0 Rc0 1zc0 Oo0 1zc0 Oo0 1zc0|21e5","America/Mazatlan|MST MDT|70 60|010101010|1XVl0 1lb0 14p0 1lb0 14p0 1nX0 11B0 1nX0|44e4","America/Metlakatla|PST AKST AKDT|80 90 80|012121212121212121212121|1Xqy0 jB0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|14e2","America/Miquelon|-03 -02|30 20|01010101010101010101010|1XK50 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|61e2","America/Noronha|-02|20|0||30e2","America/Ojinaga|MST MDT CST CDT|70 60 60 50|01010101232323232323232|1XK90 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1wn0 Rc0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|23e3","America/Santiago|-03 -04|30 40|01010101010101010101010|1XVf0 11B0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 11B0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0|62e5","America/Sao_Paulo|-02 -03|20 30|01|1XBC0|20e6","America/Scoresbysund|-01 +00 -02|10 0 20|0101010101020202020202|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 2pA0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|452","America/St_Johns|NST NDT|3u 2u|01010101010101010101010|1XK5u 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Op0 1zb0 Rd0 1zb0 Op0 1zb0 Op0 1zb0|11e4","Antarctica/Casey|+11 +08|-b0 -80|0101010101|1XME0 1kr0 12l0 1o01 14kX 1lf1 14kX 1lf1 13bX|10","Asia/Bangkok|+07|-70|0||15e6","Asia/Vladivostok|+10|-a0|0||60e4","Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1XV40 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0|40e5","Asia/Tashkent|+05|-50|0||23e5","Pacific/Auckland|NZDT NZST|-d0 -c0|01010101010101010101010|1XV20 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1io0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1cM0|14e5","Europe/Istanbul|+03|-30|0||13e6","Antarctica/Troll|+00 +02|0 -20|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|40","Antarctica/Vostok|+07 +05|-70 -50|01|2bnv0|25","Asia/Almaty|+06 +05|-60 -50|01|2bR60|15e5","Asia/Amman|EET EEST +03|-20 -30 -30|010101012|1XRy0 1o00 11A0 1qM0 WM0 1qM0 LA0 1C00|25e5","Asia/Kamchatka|+12|-c0|0||18e4","Asia/Dubai|+04|-40|0||39e5","Asia/Beirut|EET EEST|-20 -30|01010101010101010101010|1XSm0 1nX0 11B0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0|22e5","Asia/Dhaka|+06|-60|0||16e6","Asia/Kuala_Lumpur|+08|-80|0||71e5","Asia/Kolkata|IST|-5u|0||15e6","Asia/Chita|+09|-90|0||33e4","Asia/Shanghai|CST|-80|0||23e6","Asia/Colombo|+0530|-5u|0||22e5","Asia/Damascus|EET EEST +03|-20 -30 -30|010101012|1XRy0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0|26e5","Europe/Athens|EET EEST|-20 -30|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|35e5","Asia/Gaza|EET EEST|-20 -30|01010101010101010101010|1XRy0 1on0 11B0 1o00 11A0 1qo0 XA0 1qp0 1cN0 1cL0 1a10 1fz0 17d0 1in0 11B0 1nX0 11B0 1qL0 WN0 1qL0 WN0 1qL0|18e5","Asia/Hong_Kong|HKT|-80|0||73e5","Asia/Jakarta|WIB|-70|0||31e6","Asia/Jayapura|WIT|-90|0||26e4","Asia/Jerusalem|IST IDT|-20 -30|01010101010101010101010|1XRA0 1oL0 10N0 1oL0 10N0 1rz0 W10 1rz0 W10 1rz0 10N0 1oL0 10N0 1oL0 10N0 1oL0 10N0 1rz0 W10 1rz0 W10 1rz0|81e4","Asia/Kabul|+0430|-4u|0||46e5","Asia/Karachi|PKT|-50|0||24e6","Asia/Kathmandu|+0545|-5J|0||12e5","Asia/Sakhalin|+11|-b0|0||58e4","Asia/Makassar|WITA|-80|0||15e5","Asia/Manila|PST|-80|0||24e6","Asia/Seoul|KST|-90|0||23e6","Asia/Rangoon|+0630|-6u|0||48e5","Asia/Tehran|+0330 +0430|-3u -4u|010101010|1XOIu 1dz0 1cp0 1dz0 1cN0 1dz0 1cp0 1dz0|14e6","Asia/Tokyo|JST|-90|0||38e6","Atlantic/Azores|-01 +00|10 0|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|25e4","Europe/Lisbon|WET WEST|0 -10|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|27e5","Atlantic/Cape_Verde|-01|10|0||50e4","Australia/Adelaide|ACDT ACST|-au -9u|01010101010101010101010|1XV4u 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0|11e5","Australia/Brisbane|AEST|-a0|0||20e5","Australia/Darwin|ACST|-9u|0||12e4","Australia/Eucla|+0845|-8J|0||368","Australia/Lord_Howe|+11 +1030|-b0 -au|01010101010101010101010|1XV30 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1fzu 1cMu 
116141cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1cMu 1cLu 1fAu|347","Australia/Perth|AWST|-80|0||18e5","Pacific/Easter|-05 -06|50 60|01010101010101010101010|1XVf0 11B0 1nX0 11B0 1nX0 11B0 1nX0 14p0 1lb0 11B0 1qL0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1nX0 11B0 1qL0 WN0|30e2","Europe/Dublin|GMT IST|0 -10|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|12e5","Etc/GMT-1|+01|-10|0||","Pacific/Tongatapu|+13|-d0|0||75e3","Pacific/Kiritimati|+14|-e0|0||51e2","Etc/GMT-2|+02|-20|0||","Pacific/Tahiti|-10|a0|0||18e4","Pacific/Niue|-11|b0|0||12e2","Etc/GMT+12|-12|c0|0||","Pacific/Galapagos|-06|60|0||25e3","Etc/GMT+7|-07|70|0||","Pacific/Pitcairn|-08|80|0||56","Pacific/Gambier|-09|90|0||125","Etc/UTC|UTC|0|0||","Europe/London|GMT BST|0 -10|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|10e6","Europe/Chisinau|EET EEST|-20 -30|01010101010101010101010|1XSo0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|67e4","Europe/Moscow|MSK|-30|0||16e6","Europe/Volgograd|+04 MSK|-40 -30|01|249a0|10e5","Pacific/Honolulu|HST|a0|0||37e4","MET|MET MEST|-10 -20|01010101010101010101010|1XSp0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0|","Pacific/Chatham|+1345 +1245|-dJ -cJ|01010101010101010101010|1XV20 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1io0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1a00 1fA0 1cM0|600","Pacific/Apia|+14 +13|-e0 -d0|010101|1XV20 1a00 1fA0 1a00 1fA0|37e3","Pacific/Fiji|+13 +12|-d0 -c0|010101|1Xnq0 20o0 pc0 2hc0 bc0|88e4","Pacific/Guam|ChST|-a0|0||17e4","Pacific/Marquesas|-0930|9u|0||86e2","Pacific/Pago_Pago|SST|b0|0||37e2","Pacific/Norfolk|+11 +12|-b0 -c0|0101010101010101010101|219P0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0|25e4"],links:["Africa/Abidjan|Africa/Accra","Africa/Abidjan|Africa/Bamako","Africa/Abidjan|Africa/Banjul","Africa/Abidjan|Africa/Bissau","Africa/Abidjan|Africa/Conakry","Africa/Abidjan|Africa/Dakar","Africa/Abidjan|Africa/Freetown","Africa/Abidjan|Africa/Lome","Africa/Abidjan|Africa/Monrovia","Africa/Abidjan|Africa/Nouakchott","Africa/Abidjan|Africa/Ouagadougou","Africa/Abidjan|Africa/Timbuktu","Africa/Abidjan|America/Danmarkshavn","Africa/Abidjan|Atlantic/Reykjavik","Africa/Abidjan|Atlantic/St_Helena","Africa/Abidjan|Etc/GMT","Africa/Abidjan|Etc/GMT+0","Africa/Abidjan|Etc/GMT-0","Africa/Abidjan|Etc/GMT0","Africa/Abidjan|Etc/Greenwich","Africa/Abidjan|GMT","Africa/Abidjan|GMT+0","Africa/Abidjan|GMT-0","Africa/Abidjan|GMT0","Africa/Abidjan|Greenwich","Africa/Abidjan|Iceland","Africa/Algiers|Africa/Tunis","Africa/Cairo|Egypt","Africa/Casablanca|Africa/El_Aaiun","Africa/Johannesburg|Africa/Maseru","Africa/Johannesburg|Africa/Mbabane","Africa/Khartoum|Africa/Blantyre","Africa/Khartoum|Africa/Bujumbura","Africa/Khartoum|Africa/Gaborone","Africa/Khartoum|Africa/Harare","Africa/Khartoum|Africa/Kigali","Africa/Khartoum|Africa/Lubumbashi","Africa/Khartoum|Africa/Lusaka","Africa/Khartoum|Africa/Maputo","Africa/Khartoum|Africa/Windhoek","Africa/Lagos|Africa/Bangui","Africa/Lagos|Africa/Brazzaville","Africa/Lagos|Africa/Douala","Africa/Lagos|Africa/Kinshasa","Africa/Lagos|Africa/Libreville","Africa/Lagos|Africa/Luanda","Africa/Lagos|Africa/Malabo","Africa/Lagos|Africa/Ndjamena","Africa/Lagos|Africa/Niamey","Africa/Lagos|Africa/Porto-Novo","Africa/Nairobi|Africa/Addis_Ababa","Africa/Nairobi|Africa/Asmara","Africa/Nairobi|Africa/Asmera","Africa/Nairobi|Africa/Dar_es_Salaam","Africa/Nairobi|Africa/Djibouti","Africa/Nairobi|Africa/Kampala","Africa/Nairobi|Africa/Mogadishu","Africa/Nairobi|Indian/Antananarivo","Africa/Nairobi|Indian/Comoro","Africa/Nairobi|Indian/Mayotte","Africa/Tripoli|Europe/Kaliningrad","Africa/Tripoli|Libya","America/Adak|America/Atka","America/Adak|US/Aleutian","America/Anchorage|America/Juneau","America/Anchorage|America/Nome","America/Anchorage|America/Sitka","America/Anchorage|America/Yakutat","America/Anchorage|US/Alaska","America/Campo_Grande|America/Cuiaba","America/Caracas|America/Boa_Vista","America/Caracas|America/Guyana","America/Caracas|America/La_Paz","America/Caracas|America/Manaus","America/Caracas|America/Porto_Velho","America/Caracas|Brazil/West","America/Caracas|Etc/GMT+4","America/Chicago|America/Indiana/Knox","America/Chicago|America/Indiana/Tell_City","America/Chicago|America/Knox_IN","America/Chicago|America/Matamoros","America/Chicago|America/Menominee","America/Chicago|America/North_Dakota/Beulah","America/Chicago|America/North_Dakota/Center","America/Chicago|America/North_Dakota/New_Salem","America/Chicago|America/Rainy_River","America/Chicago|America/Rankin_Inlet","America/Chicago|America/Resolute","America/Chicago|America/Winnipeg","America/Chicago|CST6CDT","America/Chicago|Canada
11614/Central","America/Chicago|US/Central","America/Chicago|US/Indiana-Starke","America/Denver|America/Boise","America/Denver|America/Cambridge_Bay","America/Denver|America/Edmonton","America/Denver|America/Inuvik","America/Denver|America/Shiprock","America/Denver|America/Yellowknife","America/Denver|Canada/Mountain","America/Denver|MST7MDT","America/Denver|Navajo","America/Denver|US/Mountain","America/Fortaleza|America/Araguaina","America/Fortaleza|America/Argentina/Buenos_Aires","America/Fortaleza|America/Argentina/Catamarca","America/Fortaleza|America/Argentina/ComodRivadavia","America/Fortaleza|America/Argentina/Cordoba","America/Fortaleza|America/Argentina/Jujuy","America/Fortaleza|America/Argentina/La_Rioja","America/Fortaleza|America/Argentina/Mendoza","America/Fortaleza|America/Argentina/Rio_Gallegos","America/Fortaleza|America/Argentina/Salta","America/Fortaleza|America/Argentina/San_Juan","America/Fortaleza|America/Argentina/San_Luis","America/Fortaleza|America/Argentina/Tucuman","America/Fortaleza|America/Argentina/Ushuaia","America/Fortaleza|America/Bahia","America/Fortaleza|America/Belem","America/Fortaleza|America/Buenos_Aires","America/Fortaleza|America/Catamarca","America/Fortaleza|America/Cayenne","America/Fortaleza|America/Cordoba","America/Fortaleza|America/Jujuy","America/Fortaleza|America/Maceio","America/Fortaleza|America/Mendoza","America/Fortaleza|America/Montevideo","America/Fortaleza|America/Paramaribo","America/Fortaleza|America/Punta_Arenas","America/Fortaleza|America/Recife","America/Fortaleza|America/Rosario","America/Fortaleza|America/Santarem","America/Fortaleza|Antarctica/Palmer","America/Fortaleza|Antarctica/Rothera","America/Fortaleza|Atlantic/Stanley","America/Fortaleza|Etc/GMT+3","America/Godthab|America/Nuuk","America/Halifax|America/Glace_Bay","America/Halifax|America/Goose_Bay","America/Halifax|America/Moncton","America/Halifax|America/Thule","America/Halifax|Atlantic/Bermuda","America/Halifax|Canada/Atlantic","America/Havana|Cuba","America/Lima|America/Bogota","America/Lima|America/Eirunepe","America/Lima|America/Guayaquil","America/Lima|America/Porto_Acre","America/Lima|America/Rio_Branco","America/Lima|Brazil/Acre","America/Lima|Etc/GMT+5","America/Los_Angeles|America/Ensenada","America/Los_Angeles|America/Santa_Isabel","America/Los_Angeles|America/Tijuana","America/Los_Angeles|America/Vancouver","America/Los_Angeles|Canada/Pacific","America/Los_Angeles|Mexico/BajaNorte","America/Los_Angeles|PST8PDT","America/Los_Angeles|US/Pacific","America/Managua|America/Belize","America/Managua|America/Costa_Rica","America/Managua|America/El_Salvador","America/Managua|America/Guatemala","America/Managua|America/Regina","America/Managua|America/Swift_Current","America/Managua|America/Tegucigalpa","America/Managua|Canada/Saskatchewan","America/Mazatlan|Mexico/BajaSur","America/Mexico_City|America/Bahia_Banderas","America/Mexico_City|America/Merida","America/Mexico_City|America/Monterrey","America/Mexico_City|Mexico/General","America/New_York|America/Detroit","America/New_York|America/Fort_Wayne","America/New_York|America/Grand_Turk
vendor: 2,561 bytes, line 11614
11614","America/New_York|America/Indiana/Indianapolis","America/New_York|America/Indiana/Marengo","America/New_York|America/Indiana/Petersburg","America/New_York|America/Indiana/Vevay","America/New_York|America/Indiana/Vincennes","America/New_York|America/Indiana/Winamac","America/New_York|America/Indianapolis","America/New_York|America/Iqaluit","America/New_York|America/Kentucky/Louisville","America/New_York|America/Kentucky/Monticello","America/New_York|America/Louisville","America/New_York|America/Montreal","America/New_York|America/Nassau","America/New_York|America/Nipigon","America/New_York|America/Pangnirtung","America/New_York|America/Port-au-Prince","America/New_York|America/Thunder_Bay","America/New_York|America/Toronto","America/New_York|Canada/Eastern","America/New_York|EST5EDT","America/New_York|US/East-Indiana","America/New_York|US/Eastern","America/New_York|US/Michigan","America/Noronha|Atlantic/South_Georgia","America/Noronha|Brazil/DeNoronha","America/Noronha|Etc/GMT+2","America/Panama|America/Atikokan","America/Panama|America/Cancun","America/Panama|America/Cayman","America/Panama|America/Coral_Harbour","America/Panama|America/Jamaica","America/Panama|EST","America/Panama|Jamaica","America/Phoenix|America/Creston","America/Phoenix|America/Dawson_Creek","America/Phoenix|America/Fort_Nelson","America/Phoenix|America/Hermosillo","America/Phoenix|MST","America/Phoenix|US/Arizona","America/Santiago|Chile/Continental","America/Santo_Domingo|America/Anguilla","America/Santo_Domingo|America/Antigua","America/Santo_Domingo|America/Aruba","America/Santo_Domingo|America/Barbados","America/Santo_Domingo|America/Blanc-Sablon","America/Santo_Domingo|America/Curacao","America/Santo_Domingo|America/Dominica","America/Santo_Domingo|America/Grenada","America/Santo_Domingo|America/Guadeloupe","America/Santo_Domingo|America/Kralendijk","America/Santo_Domingo|America/Lower_Princes","America/Santo_Domingo|America/Marigot","America/Santo_Domingo|America/Martinique","America/Santo_Domingo|America/Montserrat","America/Santo_Domingo|America/Port_of_Spain","America/Santo_Domingo|America/Puerto_Rico","America/Santo_Domingo|America/St_Barthelemy","America/Santo_Domingo|America/St_Kitts","America/Santo_Domingo|America/St_Lucia","America/Santo_Domingo|America/St_Thomas","America/Santo_Domingo|America/St_Vincent","America/Santo_Domingo|America/Tortola","America/Santo_Domingo|America/Virgin","America/Sao_Paulo|Brazil/East","America/St_Johns|Canada/Newfoundland","America/Whitehorse|America/Dawson","America/Whitehorse|Canada/Yukon","Asia/
11614Almaty|Asia/Qostanay","Asia/Bangkok|Antarctica/Davis","Asia/Bangkok|Asia/Barnaul","Asia/Bangkok|Asia/Ho_Chi_Minh","Asia/Bangkok|Asia/Hovd","Asia/Bangkok|Asia/Krasnoyarsk","Asia/Bangkok|Asia/Novokuznetsk","Asia/Bangkok|Asia/Novosibirsk","Asia/Bangkok|Asia/Phnom_Penh","Asia/Bangkok|Asia/Saigon","Asia/Bangkok|Asia/Tomsk","Asia/Bangkok|Asia/Vientiane","Asia/Bangkok|Etc/GMT-7","Asia/Bangkok|Indian/Christmas","Asia/Chita|Asia/Dili","Asia/Chita|Asia/Khandyga","Asia/Chita|Asia/Yakutsk","Asia/Chita|Etc/GMT-9","Asia/Chita|Pacific/Palau","Asia/Dhaka|Asia/Bishkek","Asia/Dhaka|Asia/Dacca","Asia/Dhaka|Asia/Kashgar","Asia/Dhaka|Asia/Omsk","Asia/Dhaka|Asia/Thimbu","Asia/Dhaka|Asia/Thimphu","Asia/Dhaka|Asia/Urumqi","Asia/Dhaka|Etc/GMT-6","Asia/Dhaka|Indian/Chagos","Asia/Dubai|Asia/Baku","Asia/Dubai|Asia/Muscat","Asia/Dubai|Asia/Tbilisi","Asia/Dubai|Asia/Yerevan","Asia/Dubai|Etc/GMT-4","Asia/Dubai|Europe/Astrakhan","Asia/Dubai|Europe/Samara","Asia/Dubai|Europe/Saratov","Asia/Dubai|Europe/Ulyanovsk","Asia/Dubai|Indian/Mahe","Asia/Dubai|Indian/Mauritius","Asia/Dubai|Indian/Reunion","Asia/Gaza|Asia/Hebron","Asia/Hong_Kong|Hongkong","Asia/Jakarta|Asia/Pontianak","Asia/Jerusalem|Asia/Tel_Aviv","Asia/Jerusalem|Israel","Asia/Kamchatka|Asia/Anadyr","Asia/Kamchatka|Etc/GMT-12","Asia/Kamchatka|Kwajalein","Asia/Kamchatka|Pacific/Funafuti","Asia/Kamchatka|Pacific/Kwajalein","Asia/Kamchatka|Pacific/Majuro","Asia/Kamchatka|Pacific/Nauru","Asia/Kamchatka|Pacific/Tarawa","Asia/Kamchatka|Pacific/Wake","Asia/Kamchatka|Pacific/Wallis","Asia/Kathmandu|Asia/Katmandu","Asia/Kolkata|Asia/Calcutta","Asia/Kuala_Lumpur|Asia/Brunei","Asia/Kuala_Lumpur|Asia/Choibalsan","Asia/Kuala_Lumpur|Asia/Irkutsk","Asia/Kuala_Lumpur|Asia/Kuching","Asia/Kuala_Lumpur|Asia/Singapore","Asia/Kuala_Lumpur|Asia/Ulaanbaatar","Asia/Kuala_Lumpur|Asia/Ulan_Bator","Asia/Kuala_Lumpur|Etc/GMT-8","Asia/Kuala_Lumpur|Singapore","Asia/Makassar|Asia/Ujung_Pandang","Asia/Rangoon|Asia/Yangon","Asia/Rangoon|Indian/Cocos","Asia/Sakhalin|Asia/Magadan","Asia/Sakhalin|Asia/Srednekolymsk","Asia/Sakhalin|Etc/GMT-11","Asia/Sakhalin|Pacific/Bougainville","Asia/Sakhalin|Pacific/Efate","Asia/Sakhalin|Pacific/Guadalcanal","Asia/Sakhalin|Pacific/Kosrae","Asia/Sakhalin|Pacific/Noumea","Asia/Sakhalin|Pacific/Pohnpei","Asia/Sakhalin|Pacific/Ponape","Asia/Seoul|Asia/Pyongyang","Asia/Seoul|ROK","Asia/Shanghai|Asia/Chongqing","Asia/Shanghai|Asia/Chungking","Asia/Shanghai|Asia/Harbin","Asia/Shanghai|Asia/Macao","Asia/Shanghai|Asia/Macau","Asia/Shanghai|Asia/Taipei","Asia/Shanghai|PRC","Asia/Shanghai|ROC","Asia/Tashkent|Antarctica/Mawson","Asia/Tashkent|Asia/Aqtau","Asia/Tashkent|Asia/Aqtobe","Asia/Tashkent|Asia/Ashgabat","Asia/Tashkent|Asia/Ashkhabad","Asia/Tashkent|Asia/Atyrau","Asia/Tashkent|Asia/Dushanbe","Asia/Tashkent|Asia/Oral","Asia/Tashkent|Asia/Qyzylorda","Asia/Tashkent|Asia/Samarkand","Asia/Tashkent|Asia/Yekaterinburg","Asia/Tashkent|Etc/GMT-5","Asia/Tashkent|Indian/Kerguelen","Asia/Tashkent|Indian/Maldives","Asia/Tehran|Iran","Asia/Tokyo|Japan","Asia/Vladivostok|Antarctica/DumontDUrville","Asia/Vladivostok|Asia/Ust-Nera","Asia/Vladivostok|Etc/GMT-10","Asia/Vladivostok|Pacific/Chuuk","Asia/Vladivostok|Pacific/Port_Moresby","Asia/Vladivostok|Pacific/Truk","Asia/Vladivostok|Pacific/Yap","Atlantic/Cape_Verde|Etc/GMT+1","Australia/Adelaide|Australia/Broken_Hill","Australia/Adelaide|Australia/South","Australia/Adelaide|Australia/Yancowinna","Australia/Brisbane|Australia/Lindeman","Australia/Brisbane|Australia/Queensland","Australia/Darwin|Australia/North","Australia/Lord_Howe|Australia/LHI","Australia/Perth|Australia/West","Australia/Sydney|Antarctica/Macquarie","Australia/Sydney|Australia/ACT","Australia/Sydney|Australia/Canberra","Australia/Sydney|Australia/Currie","Australia/Sydney|Australia/Hobart","Australia/Sydney|Australia/Melbourne","Australia/Sydney|Australia/NSW","Australia/Sydney|Australia/Tasmania","Australia/Sydney|Australia/Victoria","Etc/UTC|Etc/UCT","Etc/UTC|Etc/Universal","Etc/UTC|Etc/Zulu","Etc/UTC|UCT","Etc/UTC|UTC","Etc/UTC|Universal","Etc/UTC|Zulu","Europe/Athens|Asia/Famagusta","Europe/Athens|Asia/Nicosia","Europe/Athens|EET","Europe/Athens|Europe/Bucharest","Europe/Athens|Europe/Helsinki","Europe/Athens|Europe/Kiev","Europe/Athens|Europe/Kyiv","Europe/Athens|Europe/Mariehamn","Europe/Athens|Europe/Nicosia","Europe/Athens|Europe/Riga","Europe/Athens|Europe/Sofia","Europe/Athens|Europe/Tallinn","Europe/Athens|Europe/Uzhgorod","Europe/Athens|Europe/Vilnius","Europe/Athens|Europe/Zaporozhye","Europe/Chisinau|Europe/Tiraspol","Europe/Dublin|Eire","Europe/Istanbul|Antarctica/Syowa","Europe/Istanbul|Asia/Aden","Europe/Istanbul|Asia/Baghdad","Europe/Istanbul|Asia/Bahrain","Europe/Istanbul|Asia/Istanbul","Europe/Istanbul|Asia/Kuwait","Europe/Istanbul|Asia/Qatar","Europe/Istanbul|Asia/Riyadh","Europe/Istanbul|Etc/GMT-3","Europe/Istanbul|Europe/Minsk","Europe/Istanbul|Turkey","Europe/Lisbon|Atlantic/Canary","Europe/Lisbon|Atlantic/Faeroe","Europe/Lisbon|Atlantic/Faroe","Europe/Lisbon|Atlantic/Madeira","Europe/Lisbon|Portugal","Europe/Lisbon|WET","Europe/London|Europe/Belfast","Europe/London|Europe/Guernsey","Europe/London|Europe/Isle_of_Man","Europe/London|Europe/Jersey","Europe/London|GB","Europe/London|GB-Eire","Europe/Moscow|Europe/Kirov","Europe/Moscow|Europe/Simferopol","Europe/Moscow|W-SU","Europe/Paris|Africa/Ceuta","Europe/Paris|Arctic/Longyearbyen","Europe/Paris|Atlantic/Jan_Mayen","Europe/Paris|CET","Europe/Paris|Europe/Amsterdam","Europe/Paris|Europe/Andorra","Europe/Paris|Europe/Belgrade","Europe/Paris|Europe/Berlin","Europe/Paris|Europe/Bratislava","Europe/Paris|Europe/Brussels","Europe/Paris|Europe/Budapest","Europe/Paris|Europe/Busingen","Europe/Paris|Europe/Copenhagen","Europe/Paris|Europe/Gibraltar","Europe/Paris|Europe/Ljubljana","Europe/Paris|Europe/Luxembourg","Europe/Paris|Europe/Madrid","Europe/Paris|Europe/Malta","Europe/Paris|Europe/Monaco","Europe/Paris|Europe/Oslo","Europe/Paris|Europe/Podgorica","Europe/Paris|Europe/Prague","Europe/Paris|Europe/Rome","Europe/Paris|Europe/San_Marino","Europe/Paris|Europe/Sarajevo","Europe/Paris|Europe/Skopje","Europe/Paris|Europe/Stockholm","Europe/Paris|Europe/Tirane","Europe/Paris|Europe/Vaduz","Europe/Paris|Europe/Vatican","Europe/Paris|Europe/Vienna","Europe/Paris|Europe/Warsaw","Europe/Paris|Europe/Zagreb","Europe/Paris|Europe/Zurich","Europe/Paris|Poland","Pacific/Auckland|Antarctica/McMurdo","Pacific/Auckland|Antarctica/South_Pole","Pacific/Auckland|NZ","Pacific/Chatham|NZ-CHAT","Pacific/Easter|Chile/EasterIsland","Pacific/Galapagos|Etc/GMT+6","Pacific/Gambier|Etc/GMT+9","Pacific/Guam|Pacific/Saipan","Pacific/Honolulu|HST","Pacific/Honolulu|Pacific/Johnston","Pacific/Honolulu|US/Hawaii","Pacific/Kiritimati|Etc/GMT-14","Pacific/Niue|Etc/GMT+11","Pacific/Pago_Pago|Pacific/Midway","Pacific/Pago_Pago|Pacific/Samoa","Pacific/Pago_Pago|US/Samoa","Pacific/Pitcairn|Etc/GMT+8","Pacific/Tahiti|Etc/GMT+10","Pacific/Tahiti|Pacific/Rarotonga","Pacific/Tongatapu|Etc/GMT-13","Pacific/Tongatapu|Pacific/Enderbury","Pacific/Tongatapu|Pacific/Fakaofo","Pacific/Tongatapu|Pacific/Kanton"],countries:["AD|Europe/Andorra","AE|Asia/Dubai","AF|Asia/Kabul","AG|America/Puerto_Rico America/Antigua","AI|America/Puerto_Rico America/Anguilla","AL|Europe/Tirane","AM|Asia/Yerevan","AO|Africa/Lagos Africa/Luanda","AQ|Antarctica/Casey Antarctica/Davis Antarctica/Mawson Antarctica/Palmer Antarctica/Rothera Antarctica/Troll Antarctica/Vostok Pacific/Auckland Pacific/Port_Moresby Asia/Riyadh Antarctica/McMurdo Antarctica/DumontDUrville Antarctica/Syowa
vendor: 9,310 bytes, line 11614
11614","AR|America/Argentina/Buenos_Aires America/Argentina/Cordoba America/Argentina/Salta America/Argentina/Jujuy America/Argentina/Tucuman America/Argentina/Catamarca America/Argentina/La_Rioja America/Argentina/San_Juan America/Argentina/Mendoza America/Argentina/San_Luis America/Argentina/Rio_Gallegos America/Argentina/Ushuaia","AS|Pacific/Pago_Pago","AT|Europe/Vienna","AU|Australia/Lord_Howe Antarctica/Macquarie Australia/Hobart Australia/Melbourne Australia/Sydney Australia/Broken_Hill Australia/Brisbane Australia/Lindeman Australia/Adelaide Australia/Darwin Australia/Perth Australia/Eucla","AW|America/Puerto_Rico America/Aruba","AX|Europe/Helsinki Europe/Mariehamn","AZ|Asia/Baku","BA|Europe/Belgrade Europe/Sarajevo","BB|America/Barbados","BD|Asia/Dhaka","BE|Europe/Brussels","BF|Africa/Abidjan Africa/Ouagadougou","BG|Europe/Sofia","BH|Asia/Qatar Asia/Bahrain","BI|Africa/Maputo Africa/Bujumbura","BJ|Africa/Lagos Africa/Porto-Novo","BL|America/Puerto_Rico America/St_Barthelemy","BM|Atlantic/Bermuda","BN|Asia/Kuching Asia/Brunei","BO|America/La_Paz","BQ|America/Puerto_Rico America/Kralendijk","BR|America/Noronha America/Belem America/Fortaleza America/Recife America/Araguaina America/Maceio America/Bahia America/Sao_Paulo America/Campo_Grande America/Cuiaba America/Santarem America/Porto_Velho America/Boa_Vista America/Manaus America/Eirunepe America/Rio_Branco","BS|America/Toronto America/Nassau","BT|Asia/Thimphu","BW|Africa/Maputo Africa/Gaborone","BY|Europe/Minsk","BZ|America/Belize","CA|America/St_Johns America/Halifax America/Glace_Bay America/Moncton America/Goose_Bay America/Toronto America/Iqaluit America/Winnipeg America/Resolute America/Rankin_Inlet America/Regina America/Swift_Current America/Edmonton America/Cambridge_Bay America/Inuvik America/Dawson_Creek America/Fort_Nelson America/Whitehorse America/Dawson America/Vancouver America/Panama America/Puerto_Rico America/Phoenix America/Blanc-Sablon America/Atikokan America/Creston","CC|Asia/Yangon Indian/Cocos","CD|Africa/Maputo Africa/Lagos Africa/Kinshasa Africa/Lubumbashi","CF|Africa/Lagos Africa/Bangui","CG|Africa/Lagos Africa/Brazzaville","CH|Europe/Zurich","CI|Africa/Abidjan","CK|Pacific/Rarotonga","CL|America/Santiago America/Punta_Arenas Pacific/Easter","CM|Africa/Lagos Africa/Douala","CN|Asia/Shanghai Asia/Urumqi","CO|America/Bogota","CR|America/Costa_Rica","CU|America/Havana","CV|Atlantic/Cape_Verde","CW|America/Puerto_Rico America/Curacao","CX|Asia/Bangkok Indian/Christmas","CY|Asia/Nicosia Asia/Famagusta","CZ|Europe/Prague","DE|Europe/Zurich Europe/Berlin Europe/Busingen","DJ|Africa/Nairobi Africa/Djibouti","DK|Europe/Berlin Europe/Copenhagen","DM|America/Puerto_Rico America/Dominica","DO|America/Santo_Domingo","DZ|Africa/Algiers","EC|America/Guayaquil Pacific/Galapagos","EE|Europe/Tallinn","EG|Africa/Cairo","EH|Africa/El_Aaiun","ER|Africa/Nairobi Africa/Asmara","ES|Europe/Madrid Africa/Ceuta Atlantic/Canary","ET|Africa/Nairobi Africa/Addis_Ababa","FI|Europe/Helsinki","FJ|Pacific/Fiji","FK|Atlantic/Stanley","FM|Pacific/Kosrae Pacific/Port_Moresby Pacific/Guadalcanal Pacific/Chuuk Pacific/Pohnpei","FO|Atlantic/Faroe","FR|Europe/Paris","GA|Africa/Lagos Africa/Libreville","GB|Europe/London","GD|America/Puerto_Rico America/Grenada","GE|Asia/Tbilisi","GF|America/Cayenne","GG|Europe/London Europe/Guernsey","GH|Africa/Abidjan Africa/Accra","GI|Europe/Gibraltar","GL|America/Nuuk America/Danmarkshavn America/Scoresbysund America/Thule","GM|Africa/Abidjan Africa/Banjul","GN|Africa/Abidjan Africa/Conakry","GP|America/Puerto_Rico America/Guadeloupe","GQ|Africa/Lagos Africa/Malabo","GR|Europe/Athens","GS|Atlantic/South_Georgia","GT|America/Guatemala","GU|Pacific/Guam","GW|Africa/Bissau","GY|America/Guyana","HK|Asia/Hong_Kong","HN|America/Tegucigalpa","HR|Europe/Belgrade Europe/Zagreb","HT|America/Port-au-Prince","HU|Europe/Budapest","ID|Asia/Jakarta Asia/Pontianak Asia/Makassar Asia/Jayapura","IE|Europe/Dublin","IL|Asia/Jerusalem","IM|Europe/London Europe/Isle_of_Man","IN|Asia/Kolkata","IO|Indian/Chagos","IQ|Asia/Baghdad","IR|Asia/Tehran","IS|Africa/Abidjan Atlantic/Reykjavik","IT|Europe/Rome","JE|Europe/London Europe/Jersey","JM|America/Jamaica","JO|Asia/Amman","JP|Asia/Tokyo","KE|Africa/Nairobi","KG|Asia/Bishkek","KH|Asia/Bangkok Asia/Phnom_Penh","KI|Pacific/Tarawa Pacific/Kanton Pacific/Kiritimati","KM|Africa/Nairobi Indian/Comoro","KN|America/Puerto_Rico America/St_Kitts","KP|Asia/Pyongyang","KR|Asia/Seoul","KW|Asia/Riyadh Asia/Kuwait","KY|America/Panama America/Cayman","KZ|Asia/Almaty Asia/Qyzylorda Asia/Qostanay Asia/Aqtobe Asia/Aqtau Asia/Atyrau Asia/Oral","LA|Asia/Bangkok Asia/Vientiane","LB|Asia/Beirut","LC|America/Puerto_Rico America/St_Lucia","LI|Europe/Zurich Europe/Vaduz","LK|Asia/Colombo","LR|Africa/Monrovia","LS|Africa/Johannesburg Africa/Maseru","LT|Europe/Vilnius","LU|Europe/Brussels Europe/Luxembourg","LV|Europe/Riga","LY|Africa/Tripoli","MA|Africa/Casablanca","MC|Europe/Paris Europe/Monaco","MD|Europe/Chisinau","ME|Europe/Belgrade Europe/Podgorica","MF|America/Puerto_Rico America/Marigot","MG|Africa/Nairobi Indian/Antananarivo","MH|Pacific/Tarawa Pacific/Kwajalein Pacific/Majuro","MK|Europe/Belgrade Europe/Skopje","ML|Africa/Abidjan Africa/Bamako","MM|Asia/Yangon","MN|Asia/Ulaanbaatar Asia/Hovd Asia/Choibalsan","MO|Asia/Macau","MP|Pacific/Guam Pacific/Saipan","MQ|America/Martinique","MR|Africa/Abidjan Africa/Nouakchott","MS|America/Puerto_Rico America/Montserrat","MT|Europe/Malta","MU|Indian/Mauritius","MV|Indian/Maldives","MW|Africa/Maputo Africa/Blantyre","MX|America/Mexico_City America/Cancun America/Merida America/Monterrey America/Matamoros America/Chihuahua America/Ciudad_Juarez America/Ojinaga America/Mazatlan America/Bahia_Banderas America/Hermosillo America/Tijuana","MY|Asia/Kuching Asia/Singapore Asia/Kuala_Lumpur","MZ|Africa/Maputo","NA|Africa/Windhoek","NC|Pacific/Noumea","NE|Africa/Lagos Africa/Niamey","NF|Pacific/Norfolk","NG|Africa/Lagos","NI|America/Managua","NL|Europe/Brussels Europe/Amsterdam","NO|Europe/Berlin Europe/Oslo","NP|Asia/Kathmandu","NR|Pacific/Nauru","NU|Pacific/Niue","NZ|Pacific/Auckland Pacific/Chatham","OM|Asia/Dubai Asia/Muscat","PA|America/Panama","PE|America/Lima","PF|Pacific/Tahiti Pacific/Marquesas Pacific/Gambier","PG|Pacific/Port_Moresby Pacific/Bougainville","PH|Asia/Manila","PK|Asia/Karachi","PL|Europe/Warsaw","PM|America/Miquelon","PN|Pacific/Pitcairn","PR|America/Puerto_Rico","PS|Asia/Gaza Asia/Hebron","PT|Europe/Lisbon Atlantic/Madeira Atlantic/Azores","PW|Pacific/Palau","PY|America/Asuncion","QA|Asia/Qatar","RE|Asia/Dubai Indian/Reunion","RO|Europe/Bucharest","RS|Europe/Belgrade","RU|Europe/Kaliningrad Europe/Moscow Europe/Simferopol Europe/Kirov Europe/Volgograd Europe/Astrakhan Europe/Saratov Europe/Ulyanovsk Europe/Samara Asia/Yekaterinburg Asia/Omsk Asia/Novosibirsk Asia/Barnaul Asia/Tomsk Asia/Novokuznetsk Asia/Krasnoyarsk Asia/Irkutsk Asia/Chita Asia/Yakutsk Asia/Khandyga Asia/Vladivostok Asia/Ust-Nera Asia/Magadan Asia/Sakhalin Asia/Srednekolymsk Asia/Kamchatka Asia/Anadyr","RW|Africa/Maputo Africa/Kigali","SA|Asia/Riyadh","SB|Pacific/Guadalcanal","SC|Asia/Dubai Indian/Mahe","SD|Africa/Khartoum","SE|Europe/Berlin Europe/Stockholm","SG|Asia/Singapore","SH|Africa/Abidjan Atlantic/St_Helena","SI|Europe/Belgrade Europe/Ljubljana","SJ|Europe/Berlin Arctic/Longyearbyen","SK|Europe/Prague Europe/Bratislava","SL|Africa/Abidjan Africa/Freetown","SM|Europe/Rome Europe/San_Marino","SN|Africa/Abidjan Africa/Dakar","SO|Africa/Nairobi Africa/Mogadishu","SR|America/Paramaribo","SS|Africa/Juba","ST|Africa/Sao_Tome","SV|America/El_Salvador","SX|America/Puerto_Rico America/Lower_Princes","SY|Asia/Damascus","SZ|Africa/Johannesburg Africa/Mbabane","TC|America/Grand_Turk","TD|Africa/Ndjamena","TF|Asia/Dubai Indian/Maldives Indian/Kerguelen","TG|Africa/Abidjan Africa/Lome","TH|Asia/Bangkok","TJ|Asia/Dushanbe","TK|Pacific/Fakaofo","TL|Asia/Dili","TM|Asia/Ashgabat","TN|Africa/Tunis","TO|Pacific/Tongatapu","TR|Europe/Istanbul","TT|America/Puerto_Rico America/Port_of_Spain","TV|Pacific/Tarawa Pacific/Funafuti","TW|Asia/Taipei","TZ|Africa/Nairobi Africa/Dar_es_Salaam","UA|Europe/Simferopol Europe/Kyiv","UG|Africa/Nairobi Africa/Kampala","UM|Pacific/Pago_Pago Pacific/Tarawa Pacific/Midway Pacific/Wake","US|America/New_York America/Detroit America/Kentucky/Louisville America/Kentucky/Monticello America/Indiana/Indianapolis America/Indiana/Vincennes America/Indiana/Winamac America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Vevay America/Chicago America/Indiana/Tell_City America/Indiana/Knox America/Menominee America/North_Dakota/Center America/North_Dakota/New_Salem America/North_Dakota/Beulah America/Denver America/Boise America/Phoenix America/Los_Angeles America/Anchorage America/Juneau America/Sitka America/Metlakatla America/Yakutat America/Nome America/Adak Pacific/Honolulu","UY|America/Montevideo","UZ|Asia/Samarkand Asia/Tashkent","VA|Europe/Rome Europe/Vatican","VC|America/Puerto_Rico America/St_Vincent","VE|America/Caracas","VG|America/Puerto_Rico America/Tortola","VI|America/Puerto_Rico America/St_Thomas","VN|Asia/Bangkok Asia/Ho_Chi_Minh","VU|Pacific/Efate","WF|Pacific/Tarawa Pacific/Wallis","WS|Pacific/Apia","YE|Asia/Riyadh Asia/Aden","YT|Africa/Nairobi Indian/Mayotte","ZA|Africa/Johannesburg","ZM|Africa
116142/Maputo Africa/Lusaka","ZW|Africa/Maputo Africa/Harare"]}),o});
11615global.EC_GLOBAL_MOMENT = global.moment; global.moment = global.moment_original || (delete global.moment, undefined);
11616})(typeof window !== 'undefined' ? window : global);
11617CAFE24.GLOBAL_DATETIME = (function() {
11618    var getDateTimeInfo = function (sInfo, mDefault) {
11619       if (typeof window.CAFE24.GLOBAL_DATETIME_INFO === 'object' && sInfo in window.CAFE24.GLOBAL_DATETIME_INFO) {
11620           return window.CAFE24.GLOBAL_DATETIME_INFO[sInfo];
11621       }
11622
11623       return mDefault;
11624    };
11625    var oConstants = getDateTimeInfo('oConstants', {});
11626    var oOptions = getDateTimeInfo('oOptions', {});
11627    var oPolicies = getDateTimeInfo('oPolicies', {});
11628    var sOverrideTimezone = getDateTimeInfo('sOverrideTimezone', '');
11629    var sMomentNamespace = getDateTimeInfo('sMomentNamespace', '');
11630
11631    var fMomentLoaded = function() {
11632        var bMomentLoaded = !!window[sMomentNamespace];
11633        var bMomentTZLoaded = false;
11634        if (bMomentLoaded) {
11635            bMomentTZLoaded = !!window[sMomentNamespace].tz;
11636        }
11637
11638        return bMomentLoaded && bMomentTZLoaded;
11639    };
11640
11641    var fMomentWrapper = function() {
11642        return window[sMomentNamespace];
11643    };
11644
11645    var fShallowMerge = function(oTarget, oSource) {
11646        oSource = oSource || {};
11647        for (var sKey in oSource) {
11648            if (oSource.hasOwnProperty(sKey)) {
11649                oTarget[sKey] = oSource[sKey];
11650            }
11651        }
11652
11653        return oTarget;
11654    };
11655
11656    var getFormatFromFlag = function(oOptions, iFlag, bOpposite) {
11657        if (bOpposite) {
11658            switch (iFlag) {
11659                case 1:
11660                    return oOptions[oConstants.IN_DATE_FORMAT];
11661                case 2:
11662                    return oOptions[oConstants.IN_TIME_FORMAT];
11663                default:
11664                    return oOptions[oConstants.IN_FORMAT];
11665            }
11666        }
11667
11668        switch (iFlag) {
11669            case 1:
11670                return oOptions[oConstants.OUT_DATE_FORMAT];
11671            case 2:
11672                return oOptions[oConstants.OUT_TIME_FORMAT];
11673            default:
11674                return oOptions[oConstants.OUT_FORMAT];
11675        }
11676    };
11677
11678    return {
11679        'const': oConstants,
11680
11681        init: function(fCallback) {
11682            if (fMomentLoaded()) {
11683                if (typeof fCallback === 'function') {
11684                    fCallback();
11685                }
11686
11687                return;
11688            }
11689
11690            var oScript = document.createElement('script');
11691            oScript.type = 'text/javascript';
11692            oScript.async = true;
11693            oScript.src = '/ind-script/moment.php?convert={$sConvert}';
11694            oScript.onload = oScript.onreadystatechange = function () {
11695                fMomentWrapper().defaultFormat = oOptions[oConstants.OUT_FORMAT];
11696                fMomentWrapper().tz.setDefault(oOptions[oConstants.IN_ZONE]);
11697
11698                if (typeof fCallback === 'function') {
11699                    fCallback();
11700                }
11701            };
11702
11703            var oFirstScript = document.getElementsByTagName('script')[0];
11704            oFirstScript.parentNode.insertBefore(oScript, oFirstScript);
11705        },
11706
11707        initPromise: function() {
11708            if (!window.Promise) {
11709                return;
11710            }
11711
11712            return new Promise(function(resolve) {
11713                this.init(resolve);
11714            }.bind(this));
11715        },
11716
11717        isLoaded: function() {
11718            return fMomentLoaded();
11719        },
11720
11721        setOptions: function(oNewOptions) {
11722            if (typeof oNewOptions === 'object') {
11723                for (var sKey in oNewOptions) {
11724                    if (oNewOptions.hasOwnProperty(sKey) && oOptions.hasOwnProperty(sKey)) {
11725                        oOptions[sKey] = oNewOptions[sKey];
11726                    }
11727                }
11728            }
11729
11730            return this;
11731        },
11732
11733        now: function(mOptions, iFlag) {
11734            if (fMomentLoaded() === false) {
11735                return Math.floor(new Date().getTime() / 1000);
11736            }
11737
11738            var oFormatOptions = this.getOptions(mOptions);
11739            return fMomentWrapper()()
11740                .tz(oFormatOptions.outZone)
11741                .format(getFormatFromFlag(oFormatOptions, iFlag));
11742        },
11743
11744        format: function(sTime, mOptions, iFlag) {
11745            if (fMomentLoaded() === false) {
11746                return sTime;
11747            }
11748
11749            var oFormatOptions = this.getOptions(mOptions);
11750            return fMomentWrapper()
11751                .tz(sTime, oFormatOptions.inZone)
11752                .tz(oFormatOptions.outZone)
11753                .format(getFormatFromFlag(oFormatOptions, iFlag));
11754        },
11755
11756        parse: function(sTime, mOptions) {
11757            if (fMomentLoaded() === false) {
11758                return sTime;
11759            }
11760
11761            var oParseOptions = this.getOptions(mOptions);
11762            return fMomentWrapper().tz((sTime || new Date()), oParseOptions.inZone).tz(oParseOptions.outZone);
11763        },
11764
11765        getOptions: function(mOptions, iFlag) {
11766            mOptions = mOptions || {};
11767
11768            var oMergedOptions = fShallowMerge({}, oOptions);
11769            if (typeof mOptions === 'string' && oPolicies[mOptions]) {
11770                oMergedOptions = fShallowMerge(oMergedOptions, oPolicies[mOptions]);
11771            } else if (typeof mOptions === 'object') {
11772                oMergedOptions = fShallowMerge(oMergedOptions, mOptions);
11773            }
11774
11775            if (sOverrideTimezone) {
11776                if ((typeof mOptions === 'string' && mOptions === 'shop') || (typeof mOptions === 'object' && !mOptions[oConstants.OUT_ZONE])) {
11777                    oMergedOptions[oConstants.OUT_ZONE] = sOverrideTimezone;
11778                }
11779            }
11780
11781            return oMergedOptions;
11782        },
11783
11784        getRevertOptions: function(mOptions) {
11785            var oCurrentOptions = this.getOptions(mOptions);
11786            var oMergedOptions = fShallowMerge({}, oOptions);
11787            oMergedOptions[oConstants.IN_ZONE] = oCurrentOptions[oConstants.OUT_ZONE];
11788            oMergedOptions[oConstants.IN_FORMAT] = oCurrentOptions[oConstants.OUT_FORMAT];
11789            oMergedOptions[oConstants.IN_DATE_FORMAT] = oCurrentOptions[oConstants.OUT_DATE_FORMAT];
11790            oMergedOptions[oConstants.IN_TIME_FORMAT] = oCurrentOptions[oConstants.OUT_TIME_FORMAT];
11791
11792            return oMergedOptions;
11793        },
11794
11795        today: function(sTime, mOptions, iFlag) {
11796            if (fMomentLoaded() === false) {
11797                throw new Error('MomentJS didnt initialize');
11798            }
11799
11800            mOptions = mOptions || 'shop';
11801            var oRevertOptions = this.getRevertOptions(mOptions);
11802            var oToday;
11803            if (!sTime || sTime === 'now') {
11804                oToday = this.parse('', mOptions);
11805            } else {
11806                iFlag = iFlag || oConstants.IN_FORMAT_ALL || 3;
11807                oToday = fMomentWrapper().tz(sTime, getFormatFromFlag(oRevertOptions, iFlag, true), oRevertOptions[oConstants.IN_ZONE]);
11808                if (oToday.isValid() === false) {
11809                    var oStandardDateRegex = new RegExp(oConstants.STANDARD_DATE_REGEX.replace(/\//g, ''));
11810                    if (oStandardDateRegex.test(sTime) === true) {
11811                        oToday = fMomentWrapper().tz(sTime, oRevertOptions[oConstants.IN_ZONE]);
11812                    } else {
11813                        oToday = fMomentWrapper()();
11814                    }
11815                }
11816            }
11817
11818            var oStartOfDay = oToday.clone().startOf('day');
11819            var oEndOfDay = oToday.clone().endOf('day');
11820
11821            var sStartOfDayInSeoul = oStartOfDay.tz(oConstants.SEOUL).format(
11821oConstants.FULL_TIME);
11822            var sEndOfDayInSeoul = oEndOfDay.tz(oConstants.SEOUL).format(oConstants.FULL_TIME);
11823
11824            return [sStartOfDayInSeoul, sEndOfDayInSeoul];
11825        },
11826
11827        parseFromFormat: function(sTime, mOptions, iFlag) {
11828            if (fMomentLoaded() === false) {
11829                return sTime;
11830            }
11831
11832            mOptions = mOptions || 'shop';
11833            iFlag = iFlag || oConstants.IN_FORMAT_ALL || 3;
11834
11835            var oRevertOptions = {};
11836            if (typeof mOptions === 'string') {
11837                oRevertOptions = this.getRevertOptions(mOptions);
11838            } else {
11839                oRevertOptions = this.getOptions(mOptions);
11840            }
11841
11842            return fMomentWrapper()(sTime, getFormatFromFlag(oRevertOptions, iFlag, true));
11843        }
11844    };
11845})();
11846
11847var EC_GLOBAL_DATETIME = CAFE24.getDeprecatedNamespace('EC_GLOBAL_DATETIME');
11848
11849!function() {
11850    'use strict';
11851    var re = {
11852        not_string: /[^s]/,
11853        not_bool: /[^t]/,
11854        not_type: /[^T]/,
11855        not_primitive: /[^v]/,
11856        number: /[diefg]/,
11857        numeric_arg: /[bcdiefguxX]/,
11858        json: /[j]/,
11859        not_json: /[^j]/,
11860        text: /^[^\x25]+/,
11861        modulo: /^\x25{2}/,
11862        placeholder: /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/,
11863        key: /^([a-z_][a-z_\d]*)/i,
11864        key_access: /^\.([a-z_][a-z_\d]*)/i,
11865        index_access: /^\[(\d+)\]/,
11866        sign: /^[\+\-]/
11867    };
11868
11869    function sprintf(key) {
11870        try {
11871            // `arguments` is not an array, but should be fine for this call
11872            return sprintf_format(sprintf_parse(key), arguments);
11873        } catch (e) {
11874            return key;
11875        }
11876    }
11877
11878    function vsprintf(fmt, argv) {
11879        return sprintf.apply(null, [fmt].concat(argv || []));
11880    }
11881
11882    function sprintf_format(parse_tree, argv) {
11883        var cursor = 1, tree_length = parse_tree.length, arg, output = '', i, k, ph, pad, pad_character, pad_length, is_positive, sign;
11884        for (i = 0; i < tree_length; i++) {
11885            if (typeof parse_tree[i] === 'string') {
11886                output += parse_tree[i];
11887            }
11888            else if (typeof parse_tree[i] === 'object') {
11889                ph = parse_tree[i]; // convenience purposes only
11890                if (ph.keys) { // keyword argument
11891                    arg = argv[cursor];
11892                    for (k = 0; k < ph.keys.length; k++) {
11893                        if (arg == undefined) {
11894                            throw new Error(sprintf('[sprintf] Cannot access property "%s" of undefined value "%s"', ph.keys[k], ph.keys[k-1]));
11895                        }
11896                        arg = arg[ph.keys[k]];
11897                    }
11898                }
11899                else if (ph.param_no) { // positional argument (explicit)
11900                    arg = argv[ph.param_no];
11901                }
11902                else { // positional argument (implicit)
11903                    arg = argv[cursor++];
11904                }
11905
11906                if (re.not_type.test(ph.type) && re.not_primitive.test(ph.type) && arg instanceof Function) {
11907                    arg = arg();
11908                }
11909
11910                if (re.numeric_arg.test(ph.type) && (typeof arg !== 'number' && isNaN(arg))) {
11911                    throw new TypeError(sprintf('[sprintf] expecting number but found %T', arg));
11912                }
11913
11914                if (re.number.test(ph.type)) {
11915                    is_positive = arg >= 0;
11916                }
11917
11918                switch (ph.type) {
11919                    case 'b':
11920                        arg = parseInt(arg, 10).toString(2);
11921                        break;
11922                    case 'c':
11923                        arg = String.fromCharCode(parseInt(arg, 10));
11924                        break;
11925                    case 'd':
11926                    case 'i':
11927                        arg = parseInt(arg, 10);
11928                        break;
11929                    case 'j':
11930                        arg = JSON.stringify(arg, null, ph.width ? parseInt(ph.width) : 0);
11931                        break;
11932                    case 'e':
11933                        arg = ph.precision ? parseFloat(arg).toExponential(ph.precision) : parseFloat(arg).toExponential();
11934                        break;
11935                    case 'f':
11936                        arg = ph.precision ? parseFloat(arg).toFixed(ph.precision) : parseFloat(arg);
11937                        break;
11938                    case 'g':
11939                        arg = ph.precision ? String(Number(arg.toPrecision(ph.precision))) : parseFloat(arg);
11940                        break;
11941                    case 'o':
11942                        arg = (parseInt(arg, 10) >>> 0).toString(8);
11943                        break;
11944                    case 's':
11945                        arg = String(arg);
11946                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
11947                        break;
11948                    case 't':
11949                        arg = String(!!arg);
11950                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
11951                        break;
11952                    case 'T':
11953                        arg = Object.prototype.toString.call(arg).slice(8, -1).toLowerCase();
11954                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
11955                        break;
11956                    case 'u':
11957                        arg = parseInt(arg, 10) >>> 0;
11958                        break;
11959                    case 'v':
11960                        arg = arg.valueOf();
11961                        arg = (ph.precision ? arg.substring(0, ph.precision) : arg);
11962                        break;
11963                    case 'x':
11964                        arg = (parseInt(arg, 10) >>> 0).toString(16);
11965                        break;
11966                    case 'X':
11967                        arg = (parseInt(arg, 10) >>> 0).toString(16).toUpperCase();
11968                        break;
11969                }
11970                if (re.json.test(ph.type)) {
11971                    output += arg;
11972                }
11973                else {
11974                    if (re.number.test(ph.type) && (!is_positive || ph.sign)) {
11975                        sign = is_positive ? '+' : '-';
11976                        arg = arg.toString().replace(re.sign, '');
11977                    }
11978                    else {
11979                        sign = '';
11980                    }
11981                    pad_character = ph.pad_char ? ph.pad_char === '0' ? '0' : ph.pad_char.charAt(1) : ' ';
11982                    pad_length = ph.width - (sign + arg).length;
11983                    pad = ph.width ? (pad_length > 0 ? pad_character.repeat(pad_length) : '') : '';
11984                    output += ph.align ? sign + arg + pad : (pad_character === '0' ? sign + pad + arg : pad + sign + arg);
11985                }
11986            }
11987        }
11988        return output;
11989    }
11990
11991    var sprintf_cache = Object.create(null);
11992
11993    function sprintf_parse(fmt) {
11994        if (sprintf_cache[fmt]) {
11995            return sprintf_cache[fmt];
11996        }
11997
11998        var _fmt = fmt, match, parse_tree = [], arg_names = 0;
11999        while (_fmt) {
12000            if ((match = re.text.exec(_fmt)) !== null) {
12001                parse_tree.push(match[0]);
12002            }
12003            else if ((match = re.modulo.exec(_fmt)) !== null) {
12004                parse_tree.push('%');
12005            }
12006            else if ((match = re.placeholder.exec(_fmt)) !== null) {
12007                if (match[2]) {
12008                    arg_names |= 1;
12009                    var field_list = [], replacement_field = match[2], field_match = [];
12010                    if ((field_match = re.key.exec(replacement_field)) !== null) {
12011                        field_list.push(field_match[1]);
12012                        while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
12013                            if ((field_match = re.key_access.exec(replacement_field)) !== null) {
12014                                field_list.push(field_match[1]);
12015                            }
12016                            else if ((field_match = re.index_access.exec(replacement_field)) !== null) {
12017                                field_list.push(field_match[1]);
12018                            }
12019                            else {
12020                                throw new SyntaxError('[sprintf] failed to parse named argument key');
12021                            }
12022                        }
12023                    }
12024                    else {
12025                        throw new SyntaxError('[sprintf] failed to parse named argument key');
12026                    }
12027                    match[2] = field_list;
12028                }
12029                else {
12030                    arg_names |= 2;
12031                }
12032                if (arg_names === 3) {
12033                    throw new Error('[sprintf] mixing positional and named placeholders is not (yet) supported');
12034                }
12035                parse_tree.push(
12036                    {
12037                        placeholder: match[0],
12038                        param_no: match[1],
12039                        keys: match[2],
12040                        sign: match[3],
12041                        pad_char: match[4],
12042                        align: match[5],
12043                        width: match[6],
12044                        precision: match[7],
12045                        type: match[8]
12046                    }
12047                );
12048            } else {
12049                throw new SyntaxError('[sprintf] unexpected placeholder');
12050            }
12051            _fmt = _fmt.substring(match[0].length);
12052        }
12053        return sprintf_cache[fmt] = parse_tree;
12054    }
12055
12056    /**
12057     * export to either browser or node.js
12058     */
12059    /* eslint-disable quote-props */
12060    if (typeof exports !== 'undefined') {
12061        exports['sprintf'] = sprintf;
12062        exports['vsprintf'] = vsprintf;
12063    }
12064    if (typeof window !== 'undefined') {
12065        window['sprintf'] = sprintf;
12066        window['vsprintf'] = vsprintf;
12067
12068        if (typeof define === 'function' && define['amd']) {
12069            define(function() {
12070                return {
12071                    'sprintf': sprintf,
12072                    'vsprintf': vsprintf
12073                };
12074            });
12075        }
12076    }
12077    /* eslint-enable quote-props */
12078}();
12079
12080/*
12081 * 각개체 별 항목 컨트롤 을 위해서 차후 확장을 고려 하여 별도로 추출
12082 * 
12083 */
12084var secondZipcodeHidden = function() {
12085    //Front Page 우편번호 2번째 엘레멘트 리스트
12086    var secondZipcodeElementId = ["postcode2", "rzipcode2", "ozipcode2", "zip2", "address_zip2"];
12087    for (var i in secondZipcodeElementId) {
12088        try {
12089            document.getElementById(secondZipcodeElementId[i]).style.display = "none";
12090        } catch (e) { }
12091    }
12092
12093    // 구디자인 회원 가입수정 zip2 제거
12094    try {
12095        document.frm.zip2.style.display = "none";
12096    } catch (e) { }
12097
12098    // 구디자인 배송목록 zip2 제거
12099    try {
12100        document.addr_set.rcv_zipcode2.style.display = "none";
12101    } catch (e) { }
12102
12103    // 구디자인 주문서 작성 zip2 제거
12104    try {
12105        document.frm.rzipcode2.style.display = "none";
12106        document.frm.ozipcode2.style.display = "none";
12107    } catch (e) { }
12108
12109    // 구디자인 세금계산서 신청약식 zip2 제거
12110    try {
12111        document.frm.mall_zipcode2.style.display = "none";
12112    } catch (e) { }
12113};
12114
12115secondZipcodeHidden();
12116
12117CAFE24.PLUSAPP_BRIDGE = (function() {
12118    var bUsePlusAppBridge = false;
12119
12120    return {
12121        /**
12122         * 해당 메소드를 사용해야 플러스앱에 데이터 전달 가능
12123         */
12124        setBridgeFunction: function () {
12125            bUsePlusAppBridge = true;
12126        },
12127
12128        /**
12129         * 플러스앱에 여러 데이터 전달
12130         * @param oBridgeData JSON 타입의 데이터
12131         */
12132        sendBridgeData: function (oBridgeData) {
12133            if (bUsePlusAppBridge && typeof (UsePlusAppBridge) !== undefined) {
12134                var browserInfo = navigator.userAgent;
12135                try {
12136                    if (browserInfo.indexOf("Cafe24Plus") > -1) {
12137                        var sBridgeData = JSON.stringify(oBridgeData);
12138
12139                        // Flutter 데이터 전송
12140                        if (window.flutter_inappwebview && window.flutter_inappwebview.callHandler) {
12141                            window.flutter_inappwebview.callHandler("sendDatasToApp", sBridgeData);
12142                            return;
12143                        } else {
12144                            if (window.flutter_inappwebview && window.flutter_inappwebview._callHandler) {
12145                                window.flutter_inappwebview._callHandler("sendDatasToApp", sBridgeData);
12146                                return;
12147                            }
12148                        }
12149
12150                        if (browserInfo.indexOf("android") > -1) {
12151                            if (window.PlusAppBridge.hasOwnProperty('sendDatasToApp') === true) {
12152                                window.PlusAppBridge.sendDatasToApp(sBridgeData);
12153                            }
12154                        } else if (typeof (webkit.messageHandlers.sendDatasToApp) !== 'undefined') {
12155                            webkit.messageHandlers.sendDatasToApp.postMessage(sBridgeData);
12156                        }
12157                    }
12158                } catch (e) {}
12159            }
12160        },
12161
12162        /**
12163         * 상품 번호 반환
12164         * @param sCheckedProduct
12165         */
12166        getProductNo: function (sCheckedProduct) {
12167            return sCheckedProduct.split(':')[0];
12168        },
12169
12170        /**
12171         * serialize 된 Form을 Json Object 포맷으로 변경
12172         * @param sParam
12173         */
12174        unserialize: function (sParam) {
12175            var objParam, aParam;
12176            aParam = sParam.replace(/\?/, "").split("&");
12177            objParam = {};
12178            EC$.each(aParam, function(iKey, sValue) {
12179                var aValue = sValue.split('=');
12180                return objParam[aValue[0]] = aValue[1];
12181            });
12182            return objParam;
12183        },
12184
12185        /**
12186         * 장바구니 등록 이벤트시 데이터 전송 처리
12187         * @param oParam
12188         */
12189        addBasket: function (oParam) {
12190            var oData = {
12191                type: 'basket',
12192                raw_data: oParam
12193            };
12194
12195            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oData);
12196        },
12197
12198        /**
12199         * 위시리스트 등록 이벤트시 데이터 전송 처리
12200         * @param iProductNo
12201         */
12202        addWishList: function (iProductNo) {
12203            var oData = {
12204                type: 'wish',
12205                raw_data: {
12206                    product_no: iProductNo
12207                }
12208            };
12209
12210            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oData);
12211        },
12212
12213        /**
12214         * SNS 링크 공유하기 이벤트시 데이터 전송 처리
12215         * @param {string} sMedia 소셜 미디어
12216         * @param {int} iProductNo 상품번호
12217         */
12218        shareSocialLink: function (sMedia, iProductNo) {
12219            var oData = {
12220                type: 'share',
12221                raw_data: {
12222                    method: sMedia,
12223                    product_no: iProductNo,
12224                }
12225            };
12226
12227            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oData);
12228        },
12229
12230        /**
12231         * 시리얼 쿠폰 등록에 성공시 데이터 전송 처리
12232         * @param string sCouponCode 시리얼 쿠폰 코드
12233         */
12234        addSerialCoupon: function (sCouponCode) {
12235            var oData = {
12236                type: 'coupon',
12237                raw_data: {
12238                    coupon_code: sCouponCode
12239                }
12240            };
12241
12242            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oData);
12243        },
12244
12245        /**
12246         * 주문 완료 후 데이터 전송 처리
12247         * @param object oParam 주문 완료 데이터
12248         */
12249        addOrderResult: function (oParam) {
12250            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oParam);
12251        },
12252
12253        /**
12254         * 프론트 주문서에서 결제 시작시 데이터 전송 처리
12255         * @param object oParam 결제 시작 데이터 (결제 금액, 통화 정보)
12256         */
12257        addBeginCheckout: function (oParam) {
12258            var oData = {
12259                type: 'begin_checkout',
12260                raw_data: oParam
12261            };
12262
12263            CAFE24.PLUSAPP_BRIDGE.sendBridgeData(oData);
12264        }
12265    };
12266})();
12267
12268var EC_PlusAppBridge = CAFE24.getDeprecatedNamespace('PLUSAPP_BRIDGE');
12269
12270CAFE24.UTIL = CAFE24.UTIL || {};
12271
12272// $.parseJSON 대체
12273CAFE24.UTIL.parseJSON = function(data) {
12274    if (typeof data !== "string" || !data) {
12275        return null;
12276    }
12277    return JSON.parse(data.trim());
12278};
12279
12280// $.trim 대체
12281CAFE24.UTIL.trim = function(text) {
12282    var trim = String.prototype.trim;
12283
12284    return text == null ? "" : trim.call(text);
12285};
12286
12287// $.browser 대체
12288CAFE24.UTIL.browser = (function() {
12289    var uaMatch = function(ua) {
12290        ua = ua.toLowerCase();
12291
12292        var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
12293            /(webkit)[ \/]([\w.]+)/.exec(ua) ||
12294            /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
12295            /(msie) ([\w.]+)/.exec(ua) ||
12296            ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
12297            [];
12298
12299        return {
12300            browser: match[1] || "",
12301            version: match[2] || "0"
12302        };
12303    };
12304
12305    matched = uaMatch(navigator.userAgent);
12306    browser = {};
12307
12308    if (matched.browser) {
12309        browser[matched.browser] = true;
12310        browser.version = matched.version;
12311    }
12312
12313    // Chrome is Webkit, but Webkit is also Safari.
12314    if (browser.chrome) {
12315        browser.webkit = true;
12316    } else if (browser.webkit) {
12317        browser.safari = true;
12318    }
12319    return browser;
12320})();
12321
12322
12323CAFE24.UTIL.topWindowJquery = function(selector) {
12324    if (window.top) {
12325        if (window.top.EC$) {
12326            return window.top.EC$(selector);
12327        }
12328        if (window.top.$) {
12329            return window.top.$(selector);
12330        }
12331    }
12332    return false;
12333};
12334
12335CAFE24.UTIL.parentWindowJquery = function(selector) {
12336    if (window.parent) {
12337        if (window.parent.EC$) {
12338            return window.parent.EC$(selector);
12339        }
12340        if (window.parent.$) {
12341            return window.parent.$(selector);
12342        }
12343    }
12344    return false;
12345};
12346
12347CAFE24.UTIL.openerWindowJquery = function(selector) {
12348    if (window.opener) {
12349        if (window.opener.EC$) {
12350            return window.opener.EC$(selector);
12351        }
12352        if (window.opener.$) {
12353            return window.opener.$(selector);
12354        }
12355    }
12356    return false;
12357};
12358
12359var EC_UTIL = CAFE24.getDeprecatedNamespace('EC_UTIL');
12360
12361/* 사용자 안내띠 버튼 리사이징 */
12362EC$(function() {
12363    window.addEventListener("resize", handleEvent);
12364    window.addEventListener('scroll', handleEvent);
12365
12366    handleEvent();
12367
12368    function handleEvent(){
12369        var targetEl = document.querySelectorAll('.certifyBox');
12370        var bodyWidth = document.body.offsetWidth,
12371            winWidth = window.innerWidth-16,
12372            rightNum = 48;
12373
12374        for(var i=0; i<targetEl.length; i++){
12375            var btnElChk = targetEl[i].querySelector('.btnTxt span');
12376            if(btnElChk){
12377                var btnWidth = btnElChk.offsetWidth;
12378                if(winWidth < 600) winWidth = 600;
12379                var left = (winWidth-(btnWidth+rightNum)+window.scrollX),
12380                    cul = bodyWidth - winWidth;
12381
12382                if(bodyWidth > winWidth && window.scrollX <= cul) {
12383                    targetEl[i].querySelector('.btnTxt').style.left = left + "px";
12384                }else{
12385                    targetEl[i].querySelector('.btnTxt').style.left = "";
12386                }
12387            }
12388        }
12389    }
12390});
12391EC$(function () {
12392    var oAgent = navigator.userAgent.toLowerCase();
12393    if (!EC$.cookie('ec_ipad_device') || /[TF]/.exec(EC$.cookie('ec_ipad_device')) == undefined) {
12394        if ((oAgent.indexOf('macintosh') != -1 && 'ontouchend' in document) === true) {
12395            EC$.cookie('ec_ipad_device', 'T', {path: '/'});
12396        } else { EC$.cookie('ec_ipad_device', 'F', {path: '/'}); }
12397    }
12398
12399    // 장바구니 link에 ch_ref 파라미터 추가
12400    if (typeof CAFE24 !== 'undefined' && CAFE24.hasChRef && CAFE24.hasChRef()) {
12401        $('a[href*="/order/basket.html"]').each(function () {
12402            try {
12403                const $link = $(this);
12404                const href = $link.attr("href");
12405
12406                // href가 유효한지 확인
12407                if (!href || href.startsWith('javascript:') || href.startsWith('mailto:')) {
12408                    return;
12409                }
12410
12411                // URL 파싱 (IE 호환성 고려)
12412                let url;
12413                try {
12414                    url = new URL(href, window.location.origin);
12415                } catch (e) {
12416                    // IE 호환성을 위한 폴백
12417                    const link = document.createElement('a');
12418                    link.href = href;
12419                    url = {
12420                        pathname: link.pathname,
12421                        search: link.search,
12422                        hash: link.hash,
12423                        searchParams: {
12424                            set: function(key, value) {
12425                                const params = new URLSearchParams(this.toString());
12426                                params.set(key, value);
12427                                this.toString = function() { return params.toString(); };
12428                            }
12429                        }
12430                    };
12431                }
12432
12433                const chRef = CAFE24.getChRefData && CAFE24.getChRefData();
12434                if (chRef) {
12435                    url.searchParams.set('ch_ref', chRef);
12436                    $link.attr("href", url.pathname + url.search + url.hash);
12437                }
12438            } catch (error) {
12439                console.warn('Error processing basket link:', error);
12440            }
12441        });
12442    }
12443});
12444
12445CAFE24.FRONT_XANS_INTERPRETER = (function() {
12446    // 변수 정규표현식
12447    var XANS_VAR_FULL_NAME_REGEXP = '\\{\\$([a-z0-9_\\.]+)(?:[\\s]*[\\|][\\s]*([a-z0-9]+)[\\s]*[:]?((?:[^\\{\\}]+)*))?\\}';
12448
12449    // 템플릿에서 모든 변수를 찾기 위한 정규식
12450    var regexpFindSDEVarFullName = new RegExp(XANS_VAR_FULL_NAME_REGEXP, 'ig');
12451
12452    // '{$var_name|display}'과 같은 문자열에서 변수명과 모디파이어를 분리하기 위한 정규식
12453    var regexpSDEVarFullname = new RegExp('^' + XANS_VAR_FULL_NAME_REGEXP + '$', 'i');
12454
12455    // 모디파이어
12456    var aSDEModifier = {
12457        display: function(sVar)
12458        {
12459            if (sVar) {
12460                return '';
12461            } else {
12462                return 'displaynone';
12463            }
12464        },
12465        numberformat: function(sVar)
12466        {
12467            if (isFinite(sVar)) {
12468                return number_format(sVar);
12469            } else {
12470                return '';
12471            }
12472        },
12473        striptag: function(sVar)
12474        {
12475            return sVar.replace(/(<([^>]+)>)/ig, '');
12476        }
12477    };
12478
12479    /**
12480     * 숫자를 3자리씩 콤마(,)로 끊어서 문자열로 변환하여 리턴합니다.
12481     * @param string sNumber 숫자
12482     * @returns {string} 콤마 반영된 문자열
12483     */
12484    function number_format(sNumber)
12485    {
12486        // 3자리씩 ,로 끊어서 리턴
12487        var sNumber = String(parseInt(sNumber));
12488        var regexp = /^(-?[0-9]+)([0-9]{3})($|\.|,)/;
12489        while (regexp.test(sNumber)) {
12490            sNumber = sNumber.replace(regexp, "$1,$2$3");
12491        }
12492        return sNumber;
12493    }
12494
12495    /**
12496     * 전체 변수명에서 실제 변수명과 모디파이어 등을 분리하여 리턴합니다.
12497     * @param string sVarFullName '{$var_name|display}' 형태의 전체 변수명
12498     * @returns {{var_name: *, modifire: *}}
12499     */
12500    function parseVariableInfo(sVarFullName)
12501    {
12502        var aMatches = sVarFullName.match(regexpSDEVarFullname);
12503
12504        return {
12505            var_name: aMatches[1],
12506            modifire: aMatches[2]
12507        };
12508    }
12509
12510    /**
12511     * XANS 템플릿에서 변수를 반영하여 리턴합니다.
12512     * @param string sTemplate 템플릿 (HTML)
12513     * @param array aVars 변수 리스트
12514     * @return string 완성된 HTML
12515     */
12516    function fetch(sTemplate, aVars)
12517    {
12518        var aHtml = sTemplate.split('<!--#-->');
12519        var sHtml = '';
12520
12521        EC$(aHtml).each(function(iIndex, sModuleHtml) {
12522            if (iIndex < 1 || (iIndex % 2) !== 1) {
12523                sHtml += convertHtmlVars(sModuleHtml, aVars);
12524            } else {
12525                var oObj = EC$(sModuleHtml);
12526                var sChildNode = EC$('<div>').append(oObj.children().first().clone()).html();
12527                if (/<!--\$--><!--@-->([\s\S]+)<!--\$-->/gm.test(sModuleHtml) === true) {
12528                    sChildNode = /<!--\$--><!--@-->([\s\S]+)<!--\$-->/gm.exec(sModuleHtml)[1].split('<!--@-->')[0];
12529                }
12530                var sModuleClass = EC$(oObj).attr('class');
12531                var sModuleName = ucfirst(sModuleClass.match(/xans-product-([^- ]+)/)[1]);
12532
12533                if (typeof(aVars['@' + sModuleName]) === 'object') {
12534                    var s = '';
12535                    EC$(aVars['@' + sModuleName]).each(function(i, aData) {
12536                        s += convertHtmlVars(sChildNode, aData);
12537                    });
12538
12539                    if (s !== '') {
12540                        sHtml += EC$('<div>').append(oObj.html(s).clone()).html();
12541                    }
12542                }
12543            }
12544        });
12545
12546        return sHtml;
12547    }
12548
12549    function ucfirst(sString)
12550    {
12551        if (typeof(sString) !== 'string') {
12552            return '';
12553        }
12554        return sString.substring(0, 1).toUpperCase() + sString.substring(1).toLowerCase();
12555    }
12556
12557    function convertHtmlVars(sTemplate, aVars)
12558    {
12559        return sTemplate.replace(regexpFindSDEVarFullName, function(sVarFullName) {
12560            var aVarInfo = parseVariableInfo(sVarFullName);
12561
12562            var sValue = '';
12563            if (aVars[aVarInfo.var_name] || aVars[aVarInfo.var_name] === 0) {
12564                sValue = aVars[aVarInfo.var_name];
12565            }
12566
12567            if (aVarInfo.modifire !== undefined && aSDEModifier.hasOwnProperty(aVarInfo.modifire) === true) {
12568                return aSDEModifier[aVarInfo.modifire](sValue);
12569
12570            } else {
12571                return sValue;
12572
12573            }
12574        });
12575    }
12576
12577    /**
12578     * XANS 템플릿에서 변수 리스트를 얻어서 리턴합니다.
12579     * @param string sTemplate 템플릿 (HTML)
12580     * @return array 변수 리스트 (ex: ['{$var_name}', '{$var_name|display}'])
12581     */
12582    function getVariables(sTemplate)
12583    {
12584        return sTemplate.match(regexpFindSDEVarFullName);
12585    }
12586
12587    return {
12588        getVariables: getVariables,
12589        parseVariableInfo: parseVariableInfo,
12590        fetch: fetch
12591    };
12592})();
12593
12594var EC_FRONT_XANS_INTERPRETER = CAFE24.getDeprecatedNamespace('EC_FRONT_XANS_INTERPRETER');
12595
12596CAFE24.FRONT_XANS_TEMPLATE = (function() {
12597    // 모듈별 템플릿
12598    var aModuleTemplates = {};
12599
12600    /**
12601     * 모듈별 템플릿을 셋팅합니다.
12602     * @param string sModuleName 모듈명 (xans-product-listmain-1)
12603     * @param string sModuleTemplate 모듈 템플릿
12604     */
12605    function setTemplate(sModuleName, sModuleTemplate)
12606    {
12607        aModuleTemplates[sModuleName] = sModuleTemplate;
12608
12609        if (/^xans-product-list|^xans-product-hashtaglist/.test(sModuleName) === true) {
12610            var sTemplateForVDOM = getTemplateForVDOM(sModuleName);
12611            var $li = EC$(sTemplateForVDOM).find('li').first();
12612            var sLiHTMLForVDOM = EC$('<ul>').append($li).html();
12613
12614            // 해시태그 모듈에 대한 별도 캐싱 처리
12615            if (/^xans-product-hashtaglist/.test(sModuleName) === true) {
12616                aModuleTemplates[sModuleName] = convertVDomHtmlToHTML(sLiHTMLForVDOM);
12617            } else {
12618                // oMobileDomData를 여전히 사용중인 사용자js와의 호환성을 위한 예외처리 - ECHOSTING-142586
12619                window.oMobileDomData = {
12620                    dom: convertVDomHtmlToHTML(sLiHTMLForVDOM),
12621                    data: CAFE24.FRONT_XANS_INTERPRETER.getVariables(sLiHTMLForVDOM)
12622                };
12623            }
12624        }
12625    }
12626
12627    /**
12628     * 모듈별 템플릿을 가져옵니다.
12629     * @param string sModuleName 모듈명
12630     * @return string 모듈별 템플릿
12631     */
12632    function getTemplate(sModuleName)
12633    {
12634        if (aModuleTemplates.hasOwnProperty(sModuleName)) {
12635            return aModuleTemplates[sModuleName];
12636        } else {
12637            return undefined;
12638        }
12639    }
12640
12641    /**
12642     * Virtual DOM 에서 사용할 모듈별 템플릿을 가져옵니다.
12643     * @param string sModuleName 모듈명
12644     * @return string 모듈별 템플릿
12645     */
12646    function getTemplateForVDOM(sModuleName)
12647    {
12648        var sTemplate = getTemplate(sModuleName) || '';
12649
12650        // src 속성에 대해 "//:0" 처리해줍니다.
12651        var sTemplateForVDOM = sTemplate.replace(/(\s+src\s*=\s*["'])/g, '$1//:0#xansjs');
12652
12653        return sTemplateForVDOM;
12654    }
12655
12656    /**
12657     * "Virtual DOM"용 HTML을 일반 HTML로 변환하여 리턴합니다.
12658     * @param string sTemplateForVDOM "Virtual DOM"용 사용한 템플릿 HTML
12659     * @return string 일반 HTML
12660     */
12661    function convertVDomHtmlToHTML(sTemplateForVDOM)
12662    {
12663        // src 속성에서 "//:0#xansjs"를 삭제합니다.
12664        var sTemplate = sTemplateForVDOM.replace(/(\s+src\s*=\s*["'])\/\/:0#xansjs/g, '$1');
12665
12666        return sTemplate;
12667    }
12668
12669    return {
12670        setTemplate: setTemplate,
12671        getTemplate: getTemplate,
12672        getTemplateForVDOM: getTemplateForVDOM,
12673        convertVDomHtmlToHTML: convertVDomHtmlToHTML
12674    };
12675})();
12676
12677var EC_FRONT_XANS_TEMPLATE = CAFE24.getDeprecatedNamespace('EC_FRONT_XANS_TEMPLATE');
12678
12679/**
12680 * 모바일 전용 Util
12681 */
12682CAFE24.MOBILE_UTIL = {
12683    /*
12684     * get li
12685     */
12686    convertNode: function(node) {
12687        return CAFE24.FRONT_XANS_INTERPRETER.fetch(oMobileDomData.dom, node);
12688    },
12689
12690    /*
12691     * set default img
12692     */
12693    setDefaultImage: function() {
12694        EC$(".thumbnail img,img.ThumbImage,img.BigImage").each(function($i,$item) {
12695            var $img = new Image();
12696            $img.onerror = function () {
12697                    $item.src="//img.echosting.cafe24.com/thumb/img_product_big.gif";
12698            };
12699            $img.src = this.src;
12700        });
12701    },
12702
12703    /*
12704     * get ajax url
12705     */
12706    getAjaxUrl: function(sModule) {
12707        var aAjax = [];
12708
12709        aAjax['xans-product-listnormal'] = '/exec/front/Product/ApiProductNormal';
12710        aAjax['xans-product-listmain'] = '/exec/front/Product/ApiProductMain';
12711
12712        return aAjax[sModule];
12713    },
12714
12715    /*
12716     * set param
12717     */
12718    setAjaxParam: function(aData, sModule) {
12719        var aParam = [];
12720
12721        if (typeof(aData['cate_no']) === 'number' && aData['cate_no'] > 0) { aParam.push('cate_no=' + aData['cate_no']); }
12722        if (typeof(aData['display_group']) === 'number' && aData['display_group'] > 0) { aParam.push('display_group=' + aData['display_group']); }
12723        if (typeof(aData['sort_method']) === 'number' && aData['sort_method'] > 0) { aParam.push('sort_method=' + aData['sort_method']); }
12724        if (typeof(aData['supplier_code']) === 'string' && aData['supplier_code'] !== '') { aParam.push('supplier_code=' + aData['supplier_code']); }
12725        if (typeof(aData['ec_soldout_display']) === 'string' && aData['ec_soldout_display'] !== '') { aParam.push('ec_soldout_display=' + aData['ec_soldout_display']); }
12726        aParam.push('page=' + aData['page']);
12727        aParam.push('bInitMore=' + aData['bInitMore']);
12728        aParam.push('count=' + aData['count']);
12729
12730        return this.getAjaxUrl(sModule) + '?' + aParam.join('&');
12731    }
12732};
12733
12734var EC_MOBILE_UTIL = CAFE24.getDeprecatedNamespace('EC_MOBILE_UTIL');
12735
12736/*
12737 * Swipe 1.0
12738 *
12739 * Brad Birdsall, Prime
12740 * Copyright 2011, Licensed GPL & MIT
12741 *
12742*/
12743window.SwipeClient = function(element, options) {
12744    // return immediately if element doesn't exist
12745    if (! element) {
12746        return null;
12747    }
12748
12749    var _this = this;
12750
12751    // retreive options
12752    this.options = options || {};
12753    this.index = this.options.startSlide || 0;
12754    this.speed = this.options.speed || 300;
12755    this.callback = this.options.callback || function() {};
12756    this.delay = this.options.auto || 0;
12757    this.postback = this.options.postback || true;
12758
12759    // 캐싱 사용유무 (기본값으로 이미 넘어오지만 그래도 no로 한번 더 저장)
12760    this.cache = this.options.cache || 'no';
12761
12762    // 현재 슬라이드 개별 모듈의 순서(인덱스)를 저장하기 위해 저장 (상품번호, 카테코리 번호 등으로 조합된 상품별 유니크 값)
12763    this.storageId = this.options.elementId || '';
12764
12765    // reference dom elements
12766    this.container = element;
12767    this.element = this.container.getElementsByTagName('ul')[0]; // the slide pane
12768
12769    // static css
12770    this.container.style.overflow = 'hidden';
12771    this.element.style.listStyle = 'none';
12772    this.element.style.margin = 0;
12773
12774    // trigger slider initialization
12775    this.setup();
12776
12777    // begin auto slideshow
12778    this.begin();
12779
12780    // add event listeners
12781    if (this.element.addEventListener) {
12782        this.element.addEventListener('touchstart', this, false);
12783        this.element.addEventListener('touchmove', this, false);
12784        this.element.addEventListener('touchend', this, false);
12785        this.element.addEventListener('touchcancel', this, false);
12786        this.element.addEventListener('webkitTransitionEnd', this, false);
12787        this.element.addEventListener('msTransitionEnd', this, false);
12788        this.element.addEventListener('oTransitionEnd', this, false);
12789        this.element.addEventListener('transitionend', this, false);
12790
12791        window.addEventListener('resize', this, false);
12792    }
12793};
12794
12795SwipeClient.prototype = {
12796    setup: function() {
12797        // get and measure amt of slides
12798        this.slides = this.element.children;
12799        this.length = this.slides.length;
12800
12801        // return immediately if their are less than two slides
12802        if (this.length < 2) {
12803            return null;
12804        }
12805
12806        // determine width of each slide
12807        this.width = Math.ceil(('getBoundingClientRect' in this.container) ? this.container.getBoundingClientRect().width : this.container.offsetWidth);
12808
12809        // Fix width for Android WebView (i.e. PhoneGap)
12810        if (this.width === 0 && typeof window.getComputedStyle === 'function') {
12811            this.width = window.getComputedStyle(this.container, null).width.replace('px','');
12812        }
12813
12814        // return immediately if measurement fails
12815        if (! this.width) {
12816            return null;
12817        }
12818
12819        // hide slider element but keep positioning during setup
12820        var origVisibility = this.container.style.visibility;
12821
12822        this.container.style.visibility = 'hidden';
12823
12824        // dynamic css
12825        this.element.style.width = Math.ceil(this.slides.length * this.width) + 'px';
12826
12827        var index = this.slides.length;
12828
12829        while (index--) {
12830            var el = this.slides[index];
12831
12832            el.style.width = this.width + 'px';
12833            el.style.display = 'table-cell';
12834            el.style.verticalAlign = 'top';
12835        }
12836
12837        // set start position and force translate to remove initial flickering
12838
12839        // 캐싱 사용중일 경우에만 처리
12840        if (this.cache === 'yes') {
12841            // 저장된 세선 스토리지 읽어와 처리
12842            // 각 스와이프의 개별 모듈에 해당되는 세션 스토리지 값
12843            // NaN 보다는 parseInt(null)로 명확하게 구분
12844            var iStorageIndexData = parseInt(null);
12845
12846            // 상품 상세페이지에서 생성된 세션 스토리지 키
12847            var sStorageDetailName = 'sStorageDetail';
12848
12849            // 상품 상세페이지에서 생성된 세션 스토리지 값 (Unix Timestamp)
12850            // NaN 보다는 parseInt(null)로 명확하게 구분
12851            var iStorageDetailData = parseInt(null);
12852
12853            // 현재 시간 Unix Timstamp
12854            var iNowTime = Math.floor(new Date().getTime() / 1000);
12855
12856            // 세션 스토리지 유지 시간
12857            var iSessionTime = 60 * 5;
12858
12859            // 값 할당 (int)
12860            try {
12861                iStorageIndexData = parseInt(sessionStorage.getItem(this.storageId));
12862                iStorageDetailData = parseInt(sessionStorage.getItem(sStorageDetailName));
12863            } catch (e) {
12864            }
12865
12866            // 저장된 값(추가 이미지)이 삭제된 경우 빈 페이지로 스와이프 되므로, 저장된 인덱스에 해당되는 이미지가 없는 경우는 세션 스토리지 삭제
12867            if (typeof($S.aButton[iStorageIndexData]) === 'undefined') {
12868                // 할당된 값 초기화
12869                iStorageIndexData = parseInt(null);
12870
12871                // 실제 세션 스토리지에서도 삭제
12872                try {
12873                    sessionStorage.removeItem(this.storageId);
12874                } catch (e) {
12875                }
12876            }
12877
12878            // 값이 있다면 moveTab을 해야 Circle(페이징 원)까지 변경됨
12879            // 상세페이지에서 생성된 세션 스토리지가 특정 시간이 경과하지 않은 경우에만 처리
12880            // 만약 모듈에서 상품번호 등의 정보(this.storageId)를 가져ì˜
12880¤ì§€ 못한 경우에는 처리하지 않음
12881            if (this.storageId !== '' && isNaN(iStorageIndexData) === false && isNaN(iStorageDetailData) === false && iStorageDetailData + iSessionTime >= iNowTime) {
12882                // 실제 이동 처리
12883                this.moveTab(iStorageIndexData, 0);
12884            } else {
12885                this.slide(this.index, 0);
12886            }
12887        } else {
12888            this.slide(this.index, 0);
12889        }
12890
12891        this.container.style.visibility = origVisibility;
12892    },
12893
12894    slide: function(index, duration) {
12895        // if useing ajax load
12896        try {
12897            if (oMobileSliderData.sPictorialLoad === true) {
12898                if ($S.iAjax === index + 1 && $S.bAjax === true) {
12899                    $S.callAjax();
12900                }
12901            }
12902        } catch (e) {}
12903
12904        var style = this.element.style;
12905
12906        // fallback to default speed
12907        if (duration == undefined) {
12908          duration = this.speed;
12909        }
12910
12911        // set duration speed (0 represents 1-to-1 scrolling)
12912        style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration = duration + 'ms';
12913
12914        // translate to given index position
12915        style.MozTransform = style.webkitTransform = 'translate3d(' + -(index * this.width) + 'px, 0, 0)';
12916        style.msTransform = style.OTransform = 'translateX(' + -(index * this.width) + 'px)';
12917
12918        // set new index to allow for expression arguments
12919        this.index = index;
12920
12921        // 현재 모듈의 인덱스를 세선 스토리지에 저장
12922        // 캐시 사용중이며 인덱스가 있으면서 저장할 스토리지 ID 값이 있는 경우에만 처리
12923        if (this.cache === 'yes' && isNaN(this.index) === false && this.storageId !== '') {
12924            try {
12925                sessionStorage.setItem(this.storageId, this.index);
12926            } catch (e) {
12927            }
12928        }
12929    },
12930
12931    getPos: function() {
12932        // return current index position
12933        return this.index;
12934    },
12935
12936    prev: function(delay, postback) {
12937        // cancel next scheduled automatic transition, if any
12938        this.delay = delay || 0;
12939        this.postback = (postback == undefined) ? true : postback;
12940
12941        clearTimeout(this.interval);
12942
12943        if (this.index) {
12944            this.slide(this.index - 1, this.speed);
12945        } else {
12946            if (this.postback !== false) {
12947                this.slide(this.length - 1, this.speed); //if first slide return to end
12948            }
12949        }
12950    },
12951
12952    next: function(delay, postback) {
12953        // cancel next scheduled automatic transition, if any
12954        this.delay = delay || 0;
12955        this.postback = (postback == undefined) ? true : postback;
12956
12957        clearTimeout(this.interval);
12958
12959        if (this.index < this.length - 1) {
12960            this.slide(this.index + 1, this.speed);
12961        } else {
12962            if (this.postback !== false) {
12963                this.slide(0, this.speed); //if last slide return to start
12964            }
12965        }
12966    },
12967
12968    moveTab: function(iPage, delay, oTarget) {
12969        // control current tab action
12970        // 모바일 상품상세에서 slide영역을 다시 원복함
12971        this.index = iPage;
12972        this.delay = delay || 0;
12973
12974        clearTimeout(this.interval);
12975
12976        this.slide(this.index, this.speed);
12977
12978        if (typeof CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE !== 'undefined') {
12979            CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE.setSwipeImage('', true, iPage, oTarget);
12980        }
12981    },
12982
12983    begin: function() {
12984        var _this = this;
12985
12986        this.interval = (this.delay) ? setTimeout(function() {
12987            _this.next(_this.delay);
12988        }, this.delay) : 0;
12989    },
12990
12991    stop: function() {
12992      this.delay = 0;
12993
12994      clearTimeout(this.interval);
12995    },
12996
12997    resume: function() {
12998      this.delay = this.options.auto || 0;
12999      this.begin();
13000    },
13001
13002    setLength: function(expand) {
13003        this.length = expand;
13004    },
13005
13006    handleEvent: function(e) {
13007        switch (e.type) {
13008            case 'touchstart':
13009                this.onTouchStart(e);
13010                break;
13011            case 'touchmove':
13012                this.onTouchMove(e);
13013                break;
13014            case 'touchcancel':
13015            case 'touchend':
13016                this.onTouchEnd(e);
13017                break;
13018            case 'webkitTransitionEnd':
13019            case 'msTransitionEnd':
13020            case 'oTransitionEnd':
13021            case 'transitionend':
13022                this.transitionEnd(e);
13023                break;
13024            case 'resize':
13025                this.setup();
13026                break;
13027        }
13028    },
13029
13030    transitionEnd: function(e) {
13031      if (this.delay) {
13032          this.begin();
13033      }
13034
13035      this.callback(e, this.index, this.slides[this.index], this);
13036    },
13037
13038    onTouchStart: function(e) {
13039        this.start = {
13040          // get touch coordinates for delta calculations in onTouchMove
13041          pageX: e.touches[0].pageX,
13042          pageY: e.touches[0].pageY,
13043
13044          // set initial timestamp of touch sequence
13045          time: Number(new Date())
13046        };
13047
13048        // used for testing first onTouchMove event
13049        this.isScrolling = undefined;
13050
13051        // reset deltaX
13052        this.deltaX = 0;
13053
13054        // set transition time to 0 for 1-to-1 touch movement
13055        this.element.style.MozTransitionDuration = this.element.style.webkitTransitionDuration = 0;
13056
13057        e.stopPropagation();
13058    },
13059
13060    onTouchMove: function(e) {
13061        // ensure swiping with one touch and not pinching
13062        if (e.touches.length > 1 || e.scale && e.scale !== 1) {
13063            return;
13064        }
13065
13066        this.deltaX = e.touches[0].pageX - this.start.pageX;
13067
13068        // determine if scrolling test has run - one time test
13069        if (typeof this.isScrolling === 'undefined') {
13070            this.isScrolling = !! (this.isScrolling || Math.abs(this.deltaX) < Math.abs(e.touches[0].pageY - this.start.pageY));
13071        }
13072
13073        // if user is not trying to scroll vertically
13074        if (! this.isScrolling) {
13075            // prevent native scrolling
13076            e.preventDefault();
13077
13078            // cancel slideshow
13079            clearTimeout(this.interval);
13080
13081            // increase resistance if first or last slide
13082            this.deltaX =
13083            this.deltaX /
13084            ((! this.index && this.deltaX > 0 // if first slide and sliding left
13085            || this.index == this.length - 1 // or if last slide and sliding right
13086            && this.deltaX < 0 // and if sliding at all
13087            ) ?
13088            (Math.abs(this.deltaX) / this.width + 1) // determine resistance level
13089            : 1); // no resistance if false
13090
13091            // translate immediately 1-to-1
13092            this.element.style.MozTransform = this.element.style.webkitTransform = 'translate3d(' + (this.deltaX - this.index * this.width) + 'px,0,0)';
13093
13094            e.stopPropagation();
13095        }
13096    },
13097
13098    onTouchEnd: function(e) {
13099        // determine if slide attempt triggers next/prev slide
13100        var isValidSlide =
13101            Number(new Date()) - this.start.time < 250 // if slide duration is less than 250ms
13102            && Math.abs(this.deltaX) > 20 // and if slide amt is greater than 20px
13103            || Math.abs(this.deltaX) > this.width/2, // or if slide amt is greater than half the width
13104
13105        // determine if slide attempt is past start and end
13106        isPastBounds =
13107            ! this.index && this.deltaX > 0 // if first slide and slide amt is greater than 0
13108            || this.index == this.length - 1 && this.deltaX < 0; // or if last slide and slide amt is less than 0
13109
13110        // if not scrolling vertically
13111        if (! this.isScrolling) {
13112            // call slide function with slide end value based on isValidSlide and isPastBounds tests
13113            this.slide(this.index + (isValidSlide && ! isPastBounds ? (this.deltaX < 0 ? 1 : -1) : 0), this.speed);
13114        }
13115
13116        e.stopPropagation();
13117    }
13118};
13119
13120/**
13121 * 모바일 상품 더보기 모듈
13122 * @package app/Mobile
13123 * @subpackage Front/Disp/Product
13124 * @version 2.2
13125 *
13126 *
13127 * version 2.2 변경사항
13128 * 1. cache = yes 설정으로 더보기 리스트 유지
13129 * 2. 사용자 html 수정 유무에 상관없이 리스팅
13130 * 3. api에 $review_cnt 추가
13131 */
13132var $M = {
13133    /*
13134     * current module name
13135     */
13136    sModule: 'xans-product-listnormal',
13137    /*
13138     * current module name
13139     */
13140    sMore: 'xans-product-listmore',
13141
13142    /*
13143     * 더보기 버튼에 대한 중복 실행을 막기 위한 flag
13144     */
13145    bLoading: false,
13146
13147    /*
13148     * 모듈별로 object 값
13149     */
13150    oModuleLoading: {},
13151
13152    /*
13153     * init
13154     */
13155    init: function() {
13156        if (this.sModule == 'xans-product-listnormal') {
13157            // 일반상품에 대해 더보기 기능 적용시 페이징 모듈 자동 삭제
13158            EC$('.xans-product-normalpaging').remove();
13159        }
13160    },
13161    /*
13162     * show more
13163     * @param int iActive 모듈 key
13164     * @param int iDisplayGroup 추천/신상품 분류
13165     * @param int iCategoryNo 카테고리 번호
13166     * @param int iCount 주석변수 상품 수
13167     * @param int iSortMethod 정렬방법
13168     * @param string sSupplierCode 공급사코드
13169     * @param bool bInitMore 더보기 기능 초기화 여부
13170     * @param string 품절상품 표시 여부
13171     */
13172    displayMore: function(iActive, iDisplayGroup, iCategoryNo, iCount, iSortMethod, bCache, sSupplierCode, bInitMore, sSoldoutDisplay) {
13173
13174        if (this.oModuleLoading[iDisplayGroup] === true) {
13175            // 로딩 중에는 실행 안함
13176            return;
13177        }
13178
13179        var EC_MORE = (function() {
13180            var sTargetModuleName,
13181                sLiTemplate,
13182                sFirstLiTemplate,
13183                $moreButton,
13184                $currentPageText,
13185                sCurrentPageCookieName,
13186                iRequestPageNum;
13187
13188            /**
13189             * 추가될 상품 정보가 append될 모듈명
13190             * @returns {string}
13191             */
13192            function getTargetModuleName()
13193            {
13194                if (iActive > 0) {
13195                    return $M.sModule + '-' + iActive;
13196                } else {
13197                    return $M.sModule;
13198                }
13199            }
13200            /**
13201             * LI 템플릿을 리턴합니다.
13202             * @returns {string}
13203             */
13204            function getLiTemplate(sPos)
13205            {
13206                var sModuleHtmlForVDOM = CAFE24.FRONT_XANS_TEMPLATE.getTemplateForVDOM(sTargetModuleName);
13207                var oLiObejct = EC$(sModuleHtmlForVDOM).find('ul').first().children('li');
13208                // 재고플러스 사용시 재고현황 API 로드여부 attribute값 삭제
13209                oLiObejct.find('[module="ec-product-wms-stock-manage"]').removeAttr('hasLoaded');
13210                var $li = EC$.fn[sPos].apply(oLiObejct);
13211                var sLiHtmlForVDOM = EC$('<ul>').append($li).html();
13212
13213                return CAFE24.FRONT_XANS_TEMPLATE.convertVDomHtmlToHTML(sLiHtmlForVDOM);
13214            }
13215            /**
13216             * "더보기" 버튼 모듈
13217             * @returns {jQuery}
13218             */
13219            function getMoreButtonElement()
13220            {
13221                if (iActive > 0) {
13222                    return EC$('.' + $M.sMore + '-' + iActive);
13223                } else {
13224                    return EC$('.' + $M.sMore);
13225                }
13226            }
13227            /**
13228             * "현재페이지 표시" 영역
13229             * @returns {jQuery}
13230             */
13231            function getCurrentPageTextElement()
13232            {
13233                if (iDisplayGroup > 1) {
13234                    return EC$('#more_current_page_' + iDisplayGroup);
13235                } else {
13236                    return EC$('#more_current_page');
13237                }
13238            }
13239            /**
13240             * "캐쉬된 현재페이지" 쿠키명
13241             * @returns {string}
13242             */
13243            function getCachedCurrentPageCookieName()
13244            {
13245                var aCookieName = ['mobile_more_current_page'];
13246                if (iCategoryNo > 0) {
13247                    aCookieName.push(iCategoryNo);
13248                }
13249                if (iDisplayGroup > 1) {
13250                    aCookieName.push(iDisplayGroup);
13251                }
13252                return aCookieName.join('_');
13253            }
13254            /**
13255             * 요청할 페이지 번호를 구하여 리턴합니다.
13256             * @return int
13257             *      "더보기 유지 기능 사용" + "더보기 초기화"인 경우 현재 쿠키에 저장된 페이지 번호
13258             *      그 외에는 다음에 가져올 페이지 번호
13259             */
13260            function getRequestPageNum()
13261            {
13262                if (bCache === true && bInitMore === true) {
13263                    // "더보기 유지 기능 사용" + "더보기 초기화"인 경우
13264                    var sCookieCurrentPage = EC$.cookie(sCurrentPageCookieName);
13265                    if (isResetPage() === true) {
13266                        EC$.cookie(sCurrentPageCookieName, 1, -1);
13267                        $currentPageText.text(1);
13268                        $moreButton.data('current_page', 1);
13269                        return 1;
13270                    }
13271
13272                    if (sCookieCurrentPage) {
13273                        return parseInt(sCookieCurrentPage, 10);
13274                    } else {
13275                        return 1;
13276                    }
13277
13278                } else {
13279                    // 그 외
13280                    var iCurrentPage = $moreButton.data('current_page');
13281
13282                    if (iCurrentPage === undefined) {
13283                        iCurrentPage = 1;
13284                    }
13285
13286                    return iCurrentPage + 1;
13287                }
13288            }
13289            /**
13290             * 다음 페이지 상품 정보를 가져올 수 있는 ajax URL을 리턴합니다.
13291             * @returns string
13292             */
13293            function getAjaxUrl()
13294            {
13295
13296                var aParam = {
13297                    cate_no: iCategoryNo,
13298                    display_group: iDisplayGroup,
13299                    supplier_code: sSupplierCode,
13300                    sort_method: iSortMethod,
13301                    page: iRequestPageNum,
13302                    count: iCount,
13303                    bInitMore: (bInitMore === true) ? 'T' : 'F',
13304                    ec_soldout_display: sSoldoutDisplay
13305                };
13306
13307                return CAFE24.MOBILE_UTIL.setAjaxParam(aParam, $M.sModule);
13308            }
13309            /**
13310             * 다음 페이지 상품 정보를 UL Element에 추가해줍니다.
13311             * @param array aData 상품 정보
13312             */
13313            function appendMoreData(aData)
13314            {
13315                EC_MORE.hideMoreButton();
13316
13317                var aHtml = [];
13318                var sTemplate = sLiTemplate;
13319                EC$(aData).each(function(iIndex, aVar) {
13320                    if (iIndex === 0) {
13321                        sTemplate = sFirstLiTemplate;
13322                    } else {
13323                        sTemplate = sLiTemplate;
13324                    }
13325                    aHtml.push(CAFE24.FRONT_XANS_INTERPRETER.fetch(sTemplate, aVar));
13326                });
13327                var sHtml = aHtml.join('');
13328
13329                EC$('.' + sTargetModuleName).each(function() {
13330                    EC$(this).find('ul').first().append(sHtml);
13331                });
13332
13333                // 재고현황 API 로드
13334                if (typeof CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS !== 'undefined') {
13335                    CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.loadStock('ec-product-wms-stock-manage');
13336                }
13337
13338                $currentPageText.text(iRequestPageNum);
13339                $moreButton.data('current_page', iRequestPageNum);
13340
13341                // GE 판매제한: 더보기로 추가된 상품에 판매제한 라벨 재적용 (ECQAUNIT-74655)
13342                // appendMoreData 는 더보기 클릭(ajax)/더보기 유지(storage) 두 경로 공통 진입점
13343                if (typeof CAPP_ASYNC_METHODS !== 'undefined'
13344                    && CAPP_ASYNC_METHODS.hasOwnProperty('GlobaleSellability') === true
13345                    && CAPP_ASYNC_METHODS['GlobaleSellability'].isUse() === true) {
13346                    CAPP_ASYNC_METHODS['GlobaleSellability'].refresh();
13347                }
13348
13349                // GE 통화/환율: 더보기로 추가된 상품 가격을 presentment 로 변환 재적용 (ECQAUNIT-74657)
13350                if (typeof CAPP_ASYNC_METHODS !== 'undefined'
13351                    && CAPP_ASYNC_METHODS.hasOwnProperty('GlobalePrice') === true
13352                    && CAPP_ASYNC_METHODS['GlobalePrice'].isUse() === true) {
13353                    CAPP_ASYNC_METHODS['GlobalePrice'].refresh();
13354                }
13355
13356            }
13357
13358            /**
13359             * 최근 페이지 저장
13360             */
13361            function setCurrentPageCookie()
13362            {
13363                // 캐시 기능 사용이면 쿠키에 현재 페이지 저장
13364                if (bCache === true) {
13365                    EC$.cookie(sCurrentPageCookieName, iRequestPageNum, { expires: 1 });
13366                }
13367            }
13368
13369            /**
13370             * '더보기' 버튼을 숨김 처리합니다.
13371             */
13372            function hideMoreButton()
13373            {
13374                $moreButton.hide();
13375            }
13376
13377            /**
13378             * '더보기' 버튼을 노출 처리합니다.
13379             */
13380            function showMoreButton()
13381            {
13382                $moreButton.show();
13383            }
13384
13385            /**
13386             * Ajax 요청 여부를 리턴합니다.
13387             * @return bool true이면 ajax 요청, false이면 ajax 요청 안함
13388             */
13389            function isCallAjax()
13390            {
13391                if (bInitMore === true && iRequestPageNum <= 1) {
13392                    // 더보기 유지 기능 동작이고 iRequestPageNum 값이 1이하이면 요청 안함
13393                    return false;
13394                }
13395
13396                return true;
13397            }
13398
13399            function setMoreAction(data)
13400            {
13401                if (data.rtn_data.end === true) {
13402                    EC_MORE.hideMoreButton();
13403                }
13404                else {
13405                    setTimeout(EC_MORE.showMoreButton,300);
13406                }
13407
13408                if (data.is_new_product === true) {
13409                    CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT.setReviewTalkCnt();
13410                }
13411            }
13412
13413            /**
13414             * 페이지 초기화여부 반환
13415             * @returns {boolean}
13416             */
13417            function isResetPage()
13418            {
13419                return getStorageList(iCategoryNo || 1, iDisplayGroup || 1) === null;
13420            }
13421
13422            /**
13423             * 스토리지에 저장된 데이터 반환
13424             * @param {number} iCategoryNo
13425             * @param {number} iDisplayGroup
13426             * @returns {object}
13427             */
13428            function getStorageList(iCategoryNo, iDisplayGroup)
13429            {
13430                var sStorageListName = getStorageKey(iCategoryNo, iDisplayGroup);
13431                var oStorageListData = null;
13432
13433                try {
13434                    oStorageListData = JSON.parse(sessionStorage.getItem(sStorageListName));
13435                } catch (e) {
13436                    return null;
13437                }
13438
13439                if (oStorageListData === null) {
13440                    return null;
13441                }
13442
13443                if (isValidStorage(oStorageListData) === true) {
13444                    sessionStorage.removeItem(sStorageListName);
13445                    return null;
13446                }
13447
13448                return oStorageListData;
13449            }
13450
13451            /**
13452             * 스토리지 유효성 검사 (시간만료, 정렬순위 변경, 동일모듈이지만 다른 카운트를 사용하는경우)
13453             * @param {object} oStorageListData
13454             * @returns {boolean}
13455             */
13456            function isValidStorage(oStorageListData)
13457            {
13458                var iNowTime = Math.floor(new Date().getTime() / 1000);
13459                var iSessionTime = 60 * 5;
13460
13461                return parseInt(oStorageListData['iStorageTime']) + iSessionTime < iNowTime ||
13462                    oStorageListData['iSortMethod'] !== iSortMethod ||
13463                    oStorageListData['iCount'] !== iCount;
13464            }
13465
13466            /**
13467             * 다른모듈 데이터를 삭제.
13468             * @param {number} iCategoryNo
13469             * @param {number} iDisplayGroup
13470             * @returns {void}
13471             */
13472            function clearOtherStorage(iCategoryNo, iDisplayGroup)
13473            {
13474                var sStorageListName = getStorageKey(iCategoryNo, iDisplayGroup);
13475
13476                // 현재 모듈 데이터 외 모듈 데이터 삭제
13477                for (var i = 0; i < sessionStorage.length; i++) {
13478                    var sKey = sessionStorage.key(i);
13479                    if (sKey !== sStorageListName && sKey.indexOf(getStoragePrefixKey()) === 0) {
13480                        sessionStorage.removeItem(sKey);
13481                    }
13482                }
13483            }
13484
13485            /**
13486             * 스토리지 키 반환
13487             * @param {number} iCategoryNo
13488             * @param {number} iDisplayGroup
13489             * @returns {string}
13490             */
13491            function getStorageKey(iCategoryNo, iDisplayGroup)
13492            {
13493                return getStoragePrefixKey() + '_' + iCategoryNo + '_' + iDisplayGroup;
13494            }
13495
13496            /**
13497             * 스토리지 키 접두사 반환
13498             * @returns {string}
13499             */
13500            function getStoragePrefixKey()
13501            {
13502                return 'mobile_more_' + ($M.sModule === 'xans-product-listnormal' ? 'listnormal' : 'listmain');
13503            }
13504
13505            sTargetModuleName = getTargetModuleName();
13506            sFirstLiTemplate = getLiTemplate('first');
13507            sLiTemplate = getLiTemplate('last');
13508            $moreButton = getMoreButtonElement();
13509            $currentPageText = getCurrentPageTextElement();
13510            sCurrentPageCookieName = getCachedCurrentPageCookieName();
13511            iRequestPageNum = getRequestPageNum();
13512
13513            return {
13514                isCallAjax: isCallAjax,
13515                getAjaxUrl: getAjaxUrl,
13516                appendMoreData: appendMoreData,
13517                hideMoreButton: hideMoreButton,
13518                showMoreButton: showMoreButton,
13519                setMoreAction: setMoreAction,
13520                getStorageList: getStorageList,
13521                getStorageKey: getStorageKey,
13522                setCurrentPageCookie: setCurrentPageCookie,
13523                clearOtherStorage: clearOtherStorage
13524            };
13525        })();
13526
13527        // ajax
13528        if (EC_MORE.isCallAjax() === true) {
13529
13530            var aParamData = {};
13531            if (EC$('#ec-product-searchdata-form').length > 0) {
13532
13533                EC$('#ec-product-searchdata-catenum').val(iCategoryNo);
13534                CAFE24.FRONT_PRODUCT_SEARCH_DATA.setSearchPriceData();
13535
13536                EC$('#ec-product-searchdata-form .ec-product-searchdata-form:checked').each(function(idx) {
13537                    var sValues = decodeURIComponent(EC$(this).val());
13538                    if (EC$(this).val() !== sValues) {
13539                        EC$(this).val(encodeURIComponent(sValues));
13540                    } else {
13541                        EC$(this).val(encodeURIComponent(EC$(this).val()));
13542                    }
13543                });
13544
13545                EC$('#ec-product-searchdata-form .ec-product-searchdata-form.ec_search_selected').each(function() {
13546                    if (EC$(this).prop('type') !== 'checkbox') {
13547                        EC$('<input>').attr({type: 'hidden',name: 'search_form[option_data][]',value: encodeURIComponent(EC$(this).attr('sValue'))}).appendTo('#ec-product-searchdata-form');
13548                    }
13549                });
13550
13551                aParamData = EC$('#ec-product-searchdata-form').serialize();
13552
13553
13554            }
13555
13556            var iGetCategory = iCategoryNo;
13557            var iGetDisplay = iDisplayGroup;
13558
13559            if (iGetCategory === 0) {
13560                iGetCategory = 1;
13561            }
13562
13563            if (iGetDisplay === 0) {
13564                iGetDisplay = 1;
13565            }
13566
13567            var oStorageListData = EC_MORE.getStorageList(iGetCategory, iGetDisplay);
13568
13569            // 현재 시간 Unix Timstamp
13570            var iNowTime = Math.floor(new Date().getTime() / 1000);
13571
13572            if (bInitMore === true && oStorageListData !== null) {
13573                // 더보기를 한번이라도 눌렀고, 스토리지 데이터가 반환된다면 스토리지 데이터로 사용
13574                EC_MORE.appendMoreData(oStorageListData.rtn_data.data);
13575                EC_MORE.setMoreAction(oStorageListData);
13576                EC_MORE.setCurrentPageCookie();
13577                return;
13578            }
13579
13580            EC$.ajax({
13581                type: 'get',
13582                url: EC_MORE.getAjaxUrl(),
13583                data: aParamData,
13584                dataType: 'json',
13585                success: function(data) {
13586                    if (data.rtn_code === '1000') {
13587                        EC_MORE.appendMoreData(data.rtn_data.data);
13588                        EC_MORE.setMoreAction(data);
13589
13590                        if (bInitMore === false) {
13591                            data.iStorageTime = iNowTime;
13592                            data.iSortMethod = iSortMethod;
13593                            data.iCount = iCount;
13594
13595                            if (oStorageListData !== null) {
13596                                // 초기 구동이 아니면서 세션 스토리지에 데이터가 있는 경우에는 append
13597                                data.rtn_data.data = oStorageListData.rtn_data.data.concat(data.rtn_data.data);
13598                            }
13599                        }
13600
13601                        // 최종 생성된 데이터 세션 스토리지에 저장
13602                        try {
13603                            EC_MORE.clearOtherStorage(iGetCategory, iGetDisplay);
13604                            sessionStorage.setItem(EC_MORE.getStorageKey(iGetCategory, iGetDisplay), JSON.stringify(data));
13605                            // 세션스토리지 용량이 초과되지않은경우에만 최근본페이지 갱신.
13606                            EC_MORE.setCurrentPageCookie();
13607                            ReferenceCurrencyPrice.init();
13608                        } catch (e) {
13609                        }
13610                        if (CAPP_ASYNC_METHODS.hasOwnProperty('Soldouticon') === true && CAPP_ASYNC_METHODS["Soldouticon"].isUse() === true) {
13611                            CAPP_ASYNC_METHODS["Soldouticon"].execute();
13612                        }
13613                    } else {
13614                        alert('상품을 추가로 더 불러오는 과정에 문제가 발생했습니다. 지속적으로 발생할 경우 운영자에게 문의하세요.');
13615
13616                        EC_MORE.hideMoreButton();
13617
13618                        return false;
13619                    }
13620                },
13621                error: function (xhr, status, error) {
13622                    return false;
13623                },
13624                beforeSend: function () {
13625                    $M.oModuleLoading[iDisplayGroup] = true;
13626                },
13627                complete: function () {
13628                    $M.oModuleLoading[iDisplayGroup] = false;
13629                }
13630            });
13631        }
13632    } ,
13633    setDisplayPageMore: function(iActive, iDisplayGroup, iCategoryNo, iCount, iSortMethod, bCache, sSupplierCode, bInitMore, sSoldoutDisplay) {
13634        this.displayMore(iActive, iDisplayGroup, iCategoryNo, iCount, iSortMethod, bCache, sSupplierCode, true, sSoldoutDisplay);
13635    }
13636};
13637
13638/**
13639 * 모바일 상품 스와이프 모듈
13640 * @package app/Shop
13641 * @subpackage Front/Disp/Product
13642 * @since 2014. 2. 12.
13643 * @update 2014. 5. 29.
13644 * @version 2.2
13645 *
13646 * 2.2 개선사항
13647 * 1. 데이터 ajax 로딩 추가
13648 * 2. multi, single 형태 추가
13649 */
13650var $S = {
13651    /*
13652     * current module name
13653     */
13654    sModule: 'xans-product-listmain',
13655
13656    /*
13657     * swipe action name
13658     */
13659    sModuleSwipe: '',
13660
13661    /*
13662     * mode
13663     */
13664    sMode: 'multi',
13665
13666    /*
13667     * slider
13668     */
13669    bSlider: false,
13670
13671    /*
13672     * swipeable
13673     */
13674    sSwipeable: 'yes',
13675
13676    /*
13677     * sParam
13678     */
13679    sParam: '',
13680
13681    /*
13682     * grid
13683     */
13684    sGrid: 'grid3',
13685
13686    /*
13687     * grid array
13688     */
13689    aGrid: {'grid2': 2, 'grid3': 3, 'grid4': 4, 'grid5': 5},
13690
13691    /*
13692     * start slide
13693     */
13694    iStart: 0,
13695
13696    /*
13697     * page
13698     */
13699    iPage: 1,
13700
13701    /*
13702     * page block
13703     */
13704    iPageBlock: 3,
13705
13706    /*
13707     * line
13708     */
13709    iLine: 1,
13710
13711    /*
13712     * limit circle
13713     */
13714    iLimit: 9,
13715
13716    /*
13717     * active div
13718     */
13719    iActive: 0,
13720
13721    /*
13722     * save li element
13723     */
13724    aElement: [],
13725
13726    /*
13727     * save circle element
13728     */
13729    aButton: [],
13730
13731    /*
13732     * product class
13733     */
13734    $product: null,
13735
13736    /*
13737     * product ul
13738     */
13739    $productModule: null,
13740
13741    /*
13742     * product list li
13743     */
13744    $productList: null,
13745
13746    /*
13747     * ajax loading
13748     */
13749    bAjax: true,
13750
13751    /*
13752     * generate dom
13753     */
13754    bGenerate: false,
13755
13756    /*
13757     * ajax count
13758     */
13759    iAjax: 0,
13760
13761    /*
13762     * auto slide interval
13763     */
13764    iAutoSlideInterval: 0,
13765
13766    /*
13767     *  paging ui
13768     */
13769    sPagingType: 'circle',
13770
13771    iProductTotal: 0,
13772
13773    /*
13774     * cache 사용여부
13775     */
13776    sCache: 'no',
13777
13778    /*
13779     * init
13780     */
13781    init: function() {
13782        // set param
13783        this.setParam();
13784
13785         // set obejct
13786        this.setObject();
13787
13788        // set block
13789        this.setBlock();
13790
13791        // validate
13792        if (this.validate() === false) return;
13793
13794         // generate
13795        this.generate();
13796
13797        // load swipe
13798        this.load();
13799    },
13800
13801    /*
13802     * set param
13803     */
13804    setParam: function() {
13805        try
13806        {
13807            this.sModuleSwipe = this.sModule.replace(/-/g, "_");
13808            this.iAjax = oMobileSliderData.iSliderLimit;
13809        }
13810        catch (e) { }
13811    },
13812
13813    /*
13814     * set block
13815     */
13816    setBlock: function() {
13817        // set block num
13818        this.iPageBlock = (this.sMode == 'multi') ? this.iLine * this.aGrid[this.sGrid] : 1;
13819    },
13820
13821    /*
13822     * set obejct
13823     */
13824    setObject: function() {
13825        try
13826        {
13827            // current module class
13828            this.sActiveProduct = this.iActive > 0 ? this.sModule + '-'+this.iActive : this.sModule;
13829
13830            // div
13831            this.$product = $('.' + this.sActiveProduct);
13832
13833            // div > ul
13834            this.$productModule = this.$product.find('ul').first();
13835            this.$productModule.css('webkit-backface-visibility', 'hidden');
13836
13837            // div > ul > li > ul > li
13838            this.$productList = this.$productModule.find('>li');
13839        }
13840        catch (e) { }
13841    },
13842
13843    /*
13844     * validate
13845     */
13846    validate: function() {
13847        // not use swipe
13848        if (this.sSwipeable != 'yes') return false;
13849
13850        // empty ul
13851        if (this.$productModule.length < 1) return false;
13852
13853        // empty li
13854        if (this.$productList.length < 1) return false;
13855
13856        // mobilemaincategory-slider exception
13857        if (this.$productModule.find('.afterNone').length > 0) return true;
13858
13859        // no condition swipe
13860        if (this.$productList.length <= this.iPageBlock) return false;
13861    },
13862
13863    /*
13864     * ganerate swipe single dom
13865     */
13866    generate: function() {
13867        if (this.sMode == 'single') { this.generateSingle(); }
13868        else { this.generateMulti(); }
13869    },
13870
13871    /*
13872     * prepare for element
13873     */
13874    prepare: function() {
13875        var $prepare = {
13876            /*
13877             * reset element and circle
13878             */
13879            reset: function() {
13880                $S.aElement = [];
13881                $S.aButton = [];
13882            },
13883
13884            /*
13885             * set target id
13886             */
13887            setId: function() {
13888                $S.$product.attr('id', $S.sModule + '-slider-' + $S.iActive);
13889            }
13890        };
13891        $prepare.reset();
13892        $prepare.setId();
13893    },
13894
13895    /*
13896     * ganerate swipe single dom
13897     */
13898    generateSingle: function() {
13899        // prepare
13900        this.prepare();
13901
13902        // make li > ul > li
13903        for (var i=0; i<this.$productList.length; i++) {
13904            this.makeButton(i);
13905        }
13906
13907        // call pagenate
13908        this.makePagenate();
13909    },
13910
13911
13912    /*
13913     * reset grid
13914     */
13915    resetGrid: function() {
13916        for (var sKey in this.aGrid) {
13917            if (this.$productModule.hasClass(sKey) === true) { this.$productModule.empty().removeClass(sKey); }
13918        }
13919    },
13920
13921    /*
13922     * ganerate swipe multi dom
13923     */
13924    generateMulti: function() {
13925        // prepare
13926        this.prepare();
13927
13928        if (this.bGenerate === false) return;
13929
13930        // save li
13931        this.$productList.each(function() { $S.aElement.push($(this).clone(true)); });
13932
13933        // delete li and grid2, gird3, grid4
13934        this.resetGrid();
13935
13936        this.iProductTotal = this.aElement.length;
13937        this.iTotalPage = Math.ceil(this.iProductTotal / this.iPageBlock);
13938
13939        // make li > ul > li
13940        for (var i=0, k=1, j=0; i<this.iProductTotal; i++, k++)
13941        {
13942            // templete for li > ul
13943            var $template = (j == 0) ? $("<li>", { html: $("<ul>", {'class': this.sGrid}) }) : $('<li>', { html: $("<ul>", {'class': this.sGrid}), css: {'display': 'none'} });
13944
13945            // add li > ul
13946            if (k == 1)
13947            {
13948                this.$productModule.append($template);
13949                // <  현재페이지 / 총페이지 >
13950                if (this.sPagingType !== 'number') {
13951                    this.makeButton(j);
13952                }
13953            }
13954
13955            // add li > ul > li
13956            this.$product.children('ul').children('li').eq(j).children('ul').append(this.aElement[i]);
13957
13958            // see block
13959            if (k == this.iPageBlock)
13960            {
13961                k = 0;
13962                j++;
13963            }
13964        }
13965
13966        if (this.sPagingType === 'number') {
13967            this.makeNumber();
13968        }
13969        // not necessary pagenate
13970        if (i < (parseInt(this.iPageBlock) + 1)) return;
13971
13972        // call pagenate
13973        this.makePagenate();
13974    },
13975
13976    makeButton: function(iCnt) {
13977        // ECQAINT-14112 롤링 및 넘버링 타입은 '모바일 환경설정'의 기본 사양에 따라 최대 갯수 5개로 설정
13978        if (this.sPagingType == 'rolling' || this.sPagingType == 'numbering') {
13979            this.iLimit = 5;
13980        } else if (this.sPagingType !== 'circle') {
13981            this.iLimit = 4;
13982        }
13983
13984        var iNum = iCnt + 1,
13985        sSelected = (iCnt == 0) ? 'selected' : '',
13986        iPage = Math.ceil(iNum / this.iLimit),
13987        sLimitStyle = (iNum > this.iLimit) ? 'style="display:none"' : '',
13988        sName = this.sActiveProduct + '_page_'+iPage+'_'+iNum;
13989
13990        if (this.sPagingType === 'fix') {
13991            var sSelected = (iCnt == 0) ? 'this' : 'other';
13992            this.divPaginateName = 'typeList';
13993            this.aButton.push('<li name="'+sName+'" ' + sLimitStyle +'><a class="' + sSelected + '" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.moveTab(' + iCnt + ', ' + this.iAutoSlideInterval +');return false;">' + iNum +'</a></li>');
13994        } else if (this.sPagingType === 'numbering') {
13995            this.divPaginateName = 'typeNumber';
13996        } else if (this.sPagingType === 'rolling') {
13997            this.divPaginateName = 'typeRoll';
13998            this.aButton.push('<li class="' + sSelected + '" name="' + sName + '"><a href="#none" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.moveTab(' + iCnt + ', ' + this.iAutoSlideInterval +');return false;">' + iNum + '</a></li>');
13999        } else {
14000            // circle
14001            this.divPaginateName = 'typeSwipe';
14002            this.aButton.push('<button name="'+sName+'" type="button" ' + sLimitStyle +' class="circle  ' + sSelected + '" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.moveTab(' + iCnt + ', ' + this.iAutoSlideInterval +', $(this));return false;"><span>' + iNum +'번째 리스트</span></button>');
14003        }
14004    },
14005
14006    /*
14007     * make fix number
14008     */
14009    makeNumber: function() {
14010        this.divPaginateName = 'typeTotal';
14011        sName = this.sModule+'-'+this.iActive+'_page';
14012        this.aButton.push('<span name="' + sName + '" class="page"><strong>1</strong> / <span>' + this.iTotalPage + '</span></span>');
14013    },
14014
14015    /*
14016     * make pagenation
14017     */
14018    makePagenate: function() {
14019        var sSwipeId = this.sModule + '-swipe-button-' + this.iActive;
14020        var sPaginateStyle = '';
14021        var aBtn = [];
14022        if (this.sPagingType === 'fix') {
14023            aBtn.push('<p class="prev" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.prev();return false;"><a href="#none"><span>이전 페이지</span></a></p>');
14024            aBtn.push('<ol id='+ sSwipeId +'>'+this.aButton.join('')+'</ol>');
14025            aBtn.push('<p class="next" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.next();return false;"><a href="#none"><span>다음 페이지</span></a></p>');
14026        } else if (this.sPagingType === 'numbering') {
14027            aBtn.push('<p><strong>1</strong> / <span>' + this.$productList.length + '</span></p>');
14028        } else if (this.sPagingType === 'rolling') {
14029            sPaginateStyle = 'position:static;';
14030            aBtn.push('<ol id='+ sSwipeId +' class="grid' + this.$productList.length + '">'+this.aButton.join('')+'</ol>');
14031        } else if (this.sPagingType === 'number') {
14032            aBtn.push('<p class="prev" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.prev();return false;"><a href="#none"><span>이전 페이지</span></a></p>');
14033            aBtn.push(this.aButton.join(''));
14034            aBtn.push('<p class="next" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.next();return false;"><a href="#none"><span>다음 페이지</span></a></p>');
14035        } else {
14036            aBtn.push('<button type="button" class="prev" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.prev();return false;"><span>이전 리스트</span></button>');
14037            aBtn.push('<span id="' + sSwipeId + '">' + this.aButton.join('') +'</span>');
14038            aBtn.push('<button type="button" class="next" onclick="$' + this.sModuleSwipe + '_slider_' + this.iActive + '.next();return false;"><span>다음 리스트</span></button>');
14039        }
14040
14041        var sPaginateForm = '<div class="paginate ec-base-paginate '+this.divPaginateName+'" style="' + sPaginateStyle + '">' + aBtn.join('') + '</div>';
14042
14043        if ($S.bSlider === false) { this.$product.append(sPaginateForm); }
14044    },
14045
14046    /*
14047     * call ajax
14048     */
14049    callAjax: function() {
14050        this.iPage++;
14051        this.setAjaxParam();
14052
14053        var $ajaxLoadContainer = {
14054            load: function() {
14055                var $load = '<div class="loading"><img src="//img.echosting.cafe24.com/design/skin/mobile/img_loading.gif" alt="" /></div>',
14056                    $dimmed = '<div class="dimmed"></div>';
14057                $('body').append($load + $dimmed);
14058            },
14059            remove: function() {
14060                $('body').find('div.loading, div.dimmed').remove();
14061            }
14062        };
14063
14064        $.ajax({
14065            type: "get",
14066            url: this.sParam,
14067            dataType: "json",
14068            success: function(data) {
14069                try {
14070                    if (data.rtn_code == '1000') {
14071                        $(data.rtn_data.data).each(function(index, node) {
14072                            // new index
14073                            var newElementIndex = $S.iAjax + index;
14074                            // append new element
14075                            $S.$productModule.append(CAFE24.MOBILE_UTIL.convertNode(node));
14076                            // set onerror img
14077                            CAFE24.MOBILE_UTIL.setDefaultImage();
14078                            // element setting
14079                            $S.$product.find('li').eq(newElementIndex).css({
14080                                width: $(window).width() + 'px',
14081                                display: 'table-cell',
14082                                'vertical-align': 'top'
14083                            }).bind('click', function() { globalPictorlControl($S.$product); });
14084                        });
14085
14086                        var len = data.rtn_data.data.length, currentSlider = '$' + $S.sModuleSwipe + '_slider_' + $S.iActive;
14087
14088                        // set swipe scale
14089                        $S.$productModule.width($S.$productModule.width() + ($(window).width() * len));
14090                        // add ajax condition
14091                        $S.iAjax += len;
14092                        // stop ajax control
14093                        if (len < oMobileSliderData.iSliderLimit) { $S.bAjax = false; }
14094                    } else {
14095                        alert('상품을 추가로 더 불러오는 과정에 문제가 발생했습니다. 지속적으로 발생할 경우 운영자에게 문의하세요.');
14096                        return false;
14097                    }
14098                } catch (e) {
14099                    $ajaxLoadContainer.remove();
14100                }
14101            },
14102            error: function(xhr,status,error) {
14103                //alert('네크워크나 상품API연동에 문제가 있습니다. 지속적으로 발생할 경우 운영자에게 문의하세요.');
14104                return false;
14105            },
14106            beforeSend: function() {
14107                $ajaxLoadContainer.load();
14108            },
14109            complete: function() {
14110                $ajaxLoadContainer.remove();
14111                // set swipe module length && excute next slider
14112                var currentSlider = '$' + $S.sModuleSwipe + '_slider_' + $S.iActive;
14113                eval(currentSlider + '.setLength(' + $S.iAjax + ');');
14114            }
14115        });
14116    },
14117
14118    /*
14119     * set Param
14120     */
14121    setAjaxParam: function() {
14122        var aParam = [];
14123
14124        aParam['cate_no'] = oMobileSliderData.iCategoryNo;
14125        aParam['page'] = this.iPage;
14126        aParam['count'] = oMobileSliderData.iSliderLimit;
14127
14128        this.sParam = CAFE24.MOBILE_UTIL.setAjaxParam(aParam, this.sModule);
14129    },
14130
14131    /*
14132     * load swipe js
14133     */
14134    load: function() {
14135        try
14136        {
14137            var aSwipeVars = [],
14138                $swipe = document.getElementById('' + this.sModule + '-slider-' + this.iActive + ''),
14139                $now = this.$product.find('div.swipePage').find('span.now');
14140
14141            if (this.sPagingType !== 'circle') {
14142                this.$product.find('.typeSwipe .prev, .typeSwipe .next').show();
14143            }
14144
14145            // 상품의 고유한 값(상품 번호 및 카테고리 번호 등)을 지정
14146            // 이렇게 하지 않으면 스와이프 모듈을 하나로 인식하여 처리되기 때문
14147            var sProductInfo = '';
14148
14149            // try-catch로 모듈의 상품 정보를 불러와서 처리하고, 정보가 없으면 처리하지 않음
14150            try {
14151                sProductInfo = this.$productModule.find('li').first().attr('data-param').replace(/\?/gi, '').replace(/\&\=/gi, '_');
14152            } catch (e) {
14153            }
14154
14155            aSwipeVars.push('$' + this.sModuleSwipe + '_slider_' + this.iActive + ' = new SwipeClient($swipe, {');
14156            aSwipeVars.push('    startSlide: ' + this.iStart + ',');
14157            aSwipeVars.push('    auto: ' + this.iAutoSlideInterval + ',');
14158            aSwipeVars.push('    cache: \'' + this.sCache + '\',');
14159            aSwipeVars.push('    elementId: \'' + this.sModuleSwipe + '_slider_' + sProductInfo + '\',');
14160            aSwipeVars.push('    callback: function(e, pos, ele, obj) {');
14161            aSwipeVars.push('        if (obj.container.id == "xans-layout-mobilemaincategory-slider-0") { globalCategorySetUi(mode = "init", pos); }');
14162            aSwipeVars.push('        try { if (globalPictorialLoad === true) { globalPictorialSetUi($S.$product, pos) } } catch(e) {}');
14163            aSwipeVars.push('        var iSelectedPos = pos + 1;');
14164            aSwipeVars.push('        if ($S.bSlider === true) { $now.text(iSelectedPos); }');
14165            aSwipeVars.push(this.getSwipeButtonDisplay());
14166            aSwipeVars.push('    }');
14167            aSwipeVars.push('});');
14168
14169            eval(aSwipeVars.join(''));
14170        }
14171        catch (e) { }
14172    },
14173
14174    getSwipeButtonDisplay: function() {
14175        var sSelected = 'selected';
14176        var sChildSelector = '';
14177        if (this.sPagingType === 'fix') {
14178            sSelected = 'this';
14179            sChildSelector = ' > a';
14180        }
14181
14182        var sSwipeVars = '';
14183        if (this.sPagingType === 'number') {
14184            sSwipeVars = '        $("[name^=\'' + this.sActiveProduct + '_page\'] > strong").text(iSelectedPos);';
14185        } else if (this.sPagingType === 'numbering') {
14186            sSwipeVars = '$(".' + this.divPaginateName + ' > p > strong").text(iSelectedPos);';
14187        } else if (this.sPagingType === 'rolling') {
14188            sSwipeVars = '         $("[name^=\'' + this.sActiveProduct + '_page\']").removeClass(\'' + sSelected + '\');';
14189            sSwipeVars += '        $("[name=\'' + this.sActiveProduct + '_page_1_"+iSelectedPos+"\']").addClass(\'' + sSelected + '\');';
14190        } else {
14191            sSwipeVars = '         var iPage = pos === ' + this.iTotalPage + ' ? Math.ceil(' + this.iTotalPage + ' / $S.iLimit) : Math.ceil(iSelectedPos / $S.iLimit);';
14192
14193            /*
14194                ECHOSTING-251668 show/hide 조건 삭제
14195
14196                sSwipeVars += '        if ((pos % $S.iLimit === 0) || (iSelectedPos % $S.iLimit === 0 || iSelectedPos === ' + this.iTotalPage + ')) {';
14197                sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page\']").hide();';
14198                sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page_"+iPage+"\']").show();';
14199                sSwipeVars += '        }';
14200                sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page\']' + sChildSelector + '").removeClass(\'' + sSelected + '\');';
14201                sSwipeVars += '        $("[name=\'' + this.sActiveProduct + '_page_"+iPage+"_"+iSelectedPos+"\']' + sChildSelector + '").addClass(\'' + sSelected + '\');';
14202            */
14203
14204            sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page\']").hide();';
14205            sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page_"+iPage+"\']").show();';
14206            sSwipeVars += '        $("[name^=\'' + this.sActiveProduct + '_page\']' + sChildSelector + '").removeClass(\'' + sSelected + '\');';
14207            sSwipeVars += '        $("[name=\'' + this.sActiveProduct + '_page_"+iPage+"_"+iSelectedPos+"\']' + sChildSelector + '").addClass(\'' + sSelected + '\');';
14208        }
14209        return sSwipeVars;
14210    }
14211
14212};
14213
14214EC$(function() {
14215    sAttribute = 'ec-data-src';
14216    if (EC$('img['+sAttribute+']').length > 0) {
14217        CAFE24.lazyload();
14218    }
14219});
14220
14221/**
14222 * IntersectionObserver와 MutationObserver를 이용한 Lazyload
14223 * @constructor
14224 */
14225CAFE24.lazyload = function() {
14226    var oConfig = {
14227        rootMargin: '0px 0px 50px 0px',
14228        threshold: 0
14229    };
14230
14231    var placeholder = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=';
14232    EC$('img['+sAttribute+']').attr('src', placeholder);
14233
14234    /**
14235     * IntersectionObserver에 객체를 등록하는 메소드
14236     * @type {IntersectionObserver|*}
14237     */
14238    var oIntersection = new IntersectionObserver(function (oEntry, self) {
14239        var iEntryLength = oEntry.length;
14240        for (var i = 0; i < iEntryLength; i++) {
14241            if (oEntry[i].target.tagName !== 'IMG') {
14242                continue;
14243            }
14244            if (oEntry[i].target.hasAttribute(sAttribute) === false) {
14245                continue;
14246            }
14247            oEntry[i].target.src = placeholder;
14248            if (oEntry[i].isIntersecting) {
14249                preloadImage(oEntry[i].target);
14250                self.unobserve(oEntry[i].target);
14251            }
14252        }
14253        // 상품목록에 블럭형 레이이아웃이 존재할때만 이미지 로딩 이후 호출
14254        if (typeof resizeContent === 'function') {
14255            resizeContent();
14256        }
14257    }, oConfig);
14258
14259    /**
14260     * MutationObserver에 객체를 등록하는 메소드
14261     * @type {MutationObserver}
14262     */
14263    var oMutation = new MutationObserver(function (oMutationElement) {
14264        var iMutationLength = oMutationElement.length;
14265        for (var i = 0; i < iMutationLength; i++) {
14266            if (oMutationElement[i].addedNodes.length > 0) {
14267                oMutationElement[i].addedNodes.forEach(function (currnetValue) {
14268                    registIntersection(currnetValue);
14269                });
14270            }
14271        }
14272    });
14273
14274    /**
14275     * Mutation에서 검출된 객체를 Intersection으로 등록하는 메소드
14276     * @param oParentElement
14277     */
14278    function registIntersection(oParentElement) {
14279        if (typeof oParentElement.querySelectorAll !== 'function') {
14280            return;
14281        }
14282        var oImage = oParentElement.querySelectorAll('img['+sAttribute+']');
14283        for (var i=0; i < oImage.length; i++) {
14284            oIntersection.observe(oImage[i]);
14285        }
14286    }
14287
14288    /**
14289     * 실제 이미지 교체 메소드
14290     * @param img
14291     */
14292    function preloadImage(img) {
14293        var src = img.getAttribute(sAttribute);
14294        if (!src) return;
14295        img.src = src;
14296        img.removeAttribute(sAttribute);
14297    }
14298
14299    var oNodeList = document.body.childNodes;
14300    var oMutationConfig = {
14301        childList: true,
14302        subtree: true
14303    };
14304    var iNodeListLength = oNodeList.length;
14305    if (iNodeListLength === 0) {
14306        return;
14307    }
14308    for (var i = 0; i < iNodeListLength; i++) {
14309        registIntersection(oNodeList[i]);
14310        oMutation.observe(oNodeList[i], oMutationConfig);
14311    }
14312};
14313
14314var EC_lazyload = CAFE24.lazyload;
14315
14316/*!
14317 * Shim for MutationObserver interface
14318 * Author: Graeme Yeates (github.com/megawac)
14319 * Repository: https://github.com/megawac/MutationObserver.js
14320 * License: WTFPL V2, 2004 (wtfpl.net).
14321 * Though credit and staring the repo will make me feel pretty, you can modify and redistribute as you please.
14322 * Attempts to follow spec (https://www.w3.org/TR/dom/#mutation-observers) as closely as possible for native javascript
14323 * See https://github.com/WebKit/webkit/blob/master/Source/WebCore/dom/MutationObserver.cpp for current webkit source c++ implementation
14324 */
14325
14326/**
14327 * prefix bugs:
14328 - https://bugs.webkit.org/show_bug.cgi?id=85161
14329 - https://bugzilla.mozilla.org/show_bug.cgi?id=749920
14330 * Don't use WebKitMutationObserver as Safari (6.0.5-6.1) use a buggy implementation
14331 */
14332window.MutationObserver = window.MutationObserver || (function(undefined) {
14333        "use strict";
14334        /**
14335         * @param {function(Array.<MutationRecord>, MutationObserver)} listener
14336         * @constructor
14337         */
14338        function MutationObserver(listener) {
14339            /**
14340             * @type {Array.<Object>}
14341             * @private
14342             */
14343            this._watched = [];
14344            /** @private */
14345            this._listener = listener;
14346        }
14347
14348        /**
14349         * Start a recursive timeout function to check all items being observed for mutations
14350         * @type {MutationObserver} observer
14351         * @private
14352         */
14353        function startMutationChecker(observer) {
14354            (function check() {
14355                var mutations = observer.takeRecords();
14356
14357                if (mutations.length) { // fire away
14358                    // calling the listener with context is not spec but currently consistent with FF and WebKit
14359                    observer._listener(mutations, observer);
14360                }
14361                /** @private */
14362                observer._timeout = setTimeout(check, MutationObserver._period);
14363            })();
14364        }
14365
14366        /**
14367         * Period to check for mutations (~32 times/sec)
14368         * @type {number}
14369         * @expose
14370         */
14371        MutationObserver._period = 30;
14372
14373        /**
14374         * Exposed API
14375         * @expose
14376         * @final
14377         */
14378        MutationObserver.prototype = {
14379            /**
14380             * see https://dom.spec.whatwg.org/#dom-mutationobserver-observe
14381             * not going to throw here but going to follow the current spec config sets
14382             * @param {Node|null} $target
14383             * @param {Object|null} config : MutationObserverInit configuration dictionary
14384             * @expose
14385             * @return undefined
14386             */
14387            observe: function($target, config) {
14388                /**
14389                 * Using slightly different names so closure can go ham
vendor: 3,935 bytes, lines 14390-14497
14390                 * @type {!Object} : A custom mutation config
14391                 */
14392                var settings = {
14393                    attr: !! (config.attributes || config.attributeFilter || config.attributeOldValue),
14394
14395                    // some browsers enforce that subtree must be set with childList, attributes or characterData.
14396                    // We don't care as spec doesn't specify this rule.
14397                    kids: !! config.childList,
14398                    descendents: !! config.subtree,
14399                    charData: !! (config.characterData || config.characterDataOldValue)
14400                };
14401
14402                var watched = this._watched;
14403
14404                // remove already observed target element from pool
14405                for (var i = 0; i < watched.length; i++) {
14406                    if (watched[i].tar === $target) watched.splice(i, 1);
14407                }
14408
14409                if (config.attributeFilter) {
14410                    /**
14411                     * converts to a {key: true} dict for faster lookup
14412                     * @type {Object.<String,Boolean>}
14413                     */
14414                    settings.afilter = reduce(config.attributeFilter, function(a, b) {
14415                        a[b] = true;
14416                        return a;
14417                    }, {});
14418                }
14419
14420                watched.push({
14421                    tar: $target,
14422                    fn: createMutationSearcher($target, settings)
14423                });
14424
14425                // reconnect if not connected
14426                if (!this._timeout) {
14427                    startMutationChecker(this);
14428                }
14429            },
14430
14431            /**
14432             * Finds mutations since last check and empties the "record queue" i.e. mutations will only be found once
14433             * @expose
14434             * @return {Array.<MutationRecord>}
14435             */
14436            takeRecords: function() {
14437                var mutations = [];
14438                var watched = this._watched;
14439
14440                for (var i = 0; i < watched.length; i++) {
14441                    watched[i].fn(mutations);
14442                }
14443
14444                return mutations;
14445            },
14446
14447            /**
14448             * @expose
14449             * @return undefined
14450             */
14451            disconnect: function() {
14452                this._watched = []; // clear the stuff being observed
14453                clearTimeout(this._timeout); // ready for garbage collection
14454                /** @private */
14455                this._timeout = null;
14456            }
14457        };
14458
14459        /**
14460         * Simple MutationRecord pseudoclass. No longer exposing as its not fully compliant
14461         * @param {Object} data
14462         * @return {Object} a MutationRecord
14463         */
14464        function MutationRecord(data) {
14465            var settings = { // technically these should be on proto so hasOwnProperty will return false for non explicitly props
14466                type: null,
14467                target: null,
14468                addedNodes: [],
14469                removedNodes: [],
14470                previousSibling: null,
14471                nextSibling: null,
14472                attributeName: null,
14473                attributeNamespace: null,
14474                oldValue: null
14475            };
14476            for (var prop in data) {
14477                if (has(settings, prop) && data[prop] !== undefined) settings[prop] = data[prop];
14478            }
14479            return settings;
14480        }
14481
14482        /**
14483         * Creates a func to find all the mutations
14484         *
14485         * @param {Node} $target
14486         * @param {!Object} config : A custom mutation config
14487         */
14488        function createMutationSearcher($target, config) {
14489            /** type {Elestuct} */
14490            var $oldstate = clone($target, config); // create the cloned datastructure
14491
14492            /**
14493             * consumes array of mutations we can push to
14494             *
14495             * @param {Array.<MutationRecord>} mutations
14496             */
14497            return function
vendor: 16,374 bytes, lines 14497-14825
14497(mutations) {
14498                var olen = mutations.length, dirty;
14499
14500                if (config.charData && $target.nodeType === 3 && $target.nodeValue !== $oldstate.charData) {
14501                    mutations.push(new MutationRecord({
14502                        type: "characterData",
14503                        target: $target,
14504                        oldValue: $oldstate.charData
14505                    }));
14506                }
14507
14508                // Alright we check base level changes in attributes... easy
14509                if (config.attr && $oldstate.attr) {
14510                    findAttributeMutations(mutations, $target, $oldstate.attr, config.afilter);
14511                }
14512
14513                // check childlist or subtree for mutations
14514                if (config.kids || config.descendents) {
14515                    dirty = searchSubtree(mutations, $target, $oldstate, config);
14516                }
14517
14518                // reclone data structure if theres changes
14519                if (dirty || mutations.length !== olen) {
14520                    /** type {Elestuct} */
14521                    $oldstate = clone($target, config);
14522                }
14523            };
14524        }
14525
14526        /* attributes + attributeFilter helpers */
14527
14528        // Check if the environment has the attribute bug (#4) which cause
14529        // element.attributes.style to always be null.
14530        var hasAttributeBug = document.createElement("i");
14531        hasAttributeBug.style.top = 0;
14532        hasAttributeBug = hasAttributeBug.attributes.style.value != "null";
14533
14534        /**
14535         * Gets an attribute value in an environment without attribute bug
14536         *
14537         * @param {Node} el
14538         * @param {Attr} attr
14539         * @return {String} an attribute value
14540         */
14541        function getAttributeSimple(el, attr) {
14542            // There is a potential for a warning to occur here if the attribute is a
14543            // custom attribute in IE<9 with a custom .toString() method. This is
14544            // just a warning and doesn't affect execution (see #21)
14545            return attr.value;
14546        }
14547
14548        /**
14549         * Gets an attribute value with special hack for style attribute (see #4)
14550         *
14551         * @param {Node} el
14552         * @param {Attr} attr
14553         * @return {String} an attribute value
14554         */
14555        function getAttributeWithStyleHack(el, attr) {
14556            // As with getAttributeSimple there is a potential warning for custom attribtues in IE7.
14557            return attr.name !== "style" ? attr.value : el.style.cssText;
14558        }
14559
14560        var getAttributeValue = hasAttributeBug ? getAttributeSimple : getAttributeWithStyleHack;
14561
14562        /**
14563         * fast helper to check to see if attributes object of an element has changed
14564         * doesnt handle the textnode case
14565         *
14566         * @param {Array.<MutationRecord>} mutations
14567         * @param {Node} $target
14568         * @param {Object.<string, string>} $oldstate : Custom attribute clone data structure from clone
14569         * @param {Object} filter
14570         */
14571        function findAttributeMutations(mutations, $target, $oldstate, filter) {
14572            var checked = {};
14573            var attributes = $target.attributes;
14574            var attr;
14575            var name;
14576            var i = attributes.length;
14577            while (i--) {
14578                attr = attributes[i];
14579                name = attr.name;
14580                if (!filter || has(filter, name)) {
14581                    if (getAttributeValue($target, attr) !== $oldstate[name]) {
14582                        // The pushing is redundant but gzips very nicely
14583                        mutations.push(MutationRecord({
14584                            type: "attributes",
14585                            target: $target,
14586                            attributeName: name,
14587                            oldValue: $oldstate[name],
14588                            attributeNamespace: attr.namespaceURI // in ie<8 it incorrectly will return undefined
14589                        }));
14590                    }
14591                    checked[name] = true;
14592                }
14593            }
14594            for (name in $oldstate) {
14595                if (!(checked[name])) {
14596                    mutations.push(MutationRecord({
14597                        target: $target,
14598                        type: "attributes",
14599                        attributeName: name,
14600                        oldValue: $oldstate[name]
14601                    }));
14602                }
14603            }
14604        }
14605
14606        /**
14607         * searchSubtree: array of mutations so far, element, element clone, bool
14608         * synchronous dfs comparision of two nodes
14609         * This function is applied to any observed element with childList or subtree specified
14610         * Sorry this is kind of confusing as shit, tried to comment it a bit...
14611         * codereview.stackexchange.com/questions/38351 discussion of an earlier version of this func
14612         *
14613         * @param {Array} mutations
14614         * @param {Node} $target
14615         * @param {!Object} $oldstate : A custom cloned node from clone()
14616         * @param {!Object} config : A custom mutation config
14617         */
14618        function searchSubtree(mutations, $target, $oldstate, config) {
14619            // Track if the tree is dirty and has to be recomputed (#14).
14620            var dirty;
14621            /*
14622             * Helper to identify node rearrangment and stuff...
14623             * There is no gaurentee that the same node will be identified for both added and removed nodes
14624             * if the positions have been shuffled.
14625             * conflicts array will be emptied by end of operation
14626             */
14627            function resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes) {
14628                // the distance between the first conflicting node and the last
14629                var distance = conflicts.length - 1;
14630                // prevents same conflict being resolved twice consider when two nodes switch places.
14631                // only one should be given a mutation event (note -~ is used as a math.ceil shorthand)
14632                var counter = -~((distance - numAddedNodes) / 2);
14633                var $cur;
14634                var oldstruct;
14635                var conflict;
14636                while ((conflict = conflicts.pop())) {
14637                    $cur = $kids[conflict.i];
14638                    oldstruct = $oldkids[conflict.j];
14639
14640                    // attempt to determine if there was node rearrangement... won't gaurentee all matches
14641                    // also handles case where added/removed nodes cause nodes to be identified as conflicts
14642                    if (config.kids && counter && Math.abs(conflict.i - conflict.j) >= distance) {
14643                        mutations.push(MutationRecord({
14644                            type: "childList",
14645                            target: node,
14646                            addedNodes: [$cur],
14647                            removedNodes: [$cur],
14648                            // haha don't rely on this please
14649                            nextSibling: $cur.nextSibling,
14650                            previousSibling: $cur.previousSibling
14651                        }));
14652                        counter--; // found conflict
14653                    }
14654
14655                    // Alright we found the resorted nodes now check for other types of mutations
14656                    if (config.attr && oldstruct.attr) findAttributeMutations(mutations, $cur, oldstruct.attr, config.afilter);
14657                    if (config.charData && $cur.nodeType === 3 && $cur.nodeValue !== oldstruct.charData) {
14658                        mutations.push(MutationRecord({
14659                            type: "characterData",
14660                            target: $cur,
14661                            oldValue: oldstruct.charData
14662                        }));
14663                    }
14664                    // now look @ subtree
14665                    if (config.descendents) findMutations($cur, oldstruct);
14666                }
14667            }
14668
14669            /**
14670             * Main worker. Finds and adds mutations if there are any
14671             * @param {Node} node
14672             * @param {!Object} old : A cloned data structure using internal clone
14673             */
14674            function findMutations(node, old) {
14675                var $kids = node.childNodes;
14676                var $oldkids = old.kids;
14677                var klen = $kids.length;
14678                // $oldkids will be undefined for text and comment nodes
14679                var olen = $oldkids ? $oldkids.length : 0;
14680                // if (!olen && !klen) return; // both empty; clearly no changes
14681
14682                // we delay the intialization of these for marginal performance in the expected case (actually quite signficant on large subtrees when these would be otherwise unused)
14683                // map of checked element of ids to prevent registering the same conflict twice
14684                var map;
14685                // array of potential conflicts (ie nodes that may have been re arranged)
14686                var conflicts;
14687                var id; // element id from getElementId helper
14688                var idx; // index of a moved or inserted element
14689
14690                var oldstruct;
14691                // current and old nodes
14692                var $cur;
14693                var $old;
14694                // track the number of added nodes so we can resolve conflicts more accurately
14695                var numAddedNodes = 0;
14696
14697                // iterate over both old and current child nodes at the same time
14698                var i = 0, j = 0;
14699                // while there is still anything left in $kids or $oldkids (same as i < $kids.length || j < $oldkids.length;)
14700                while (i < klen || j < olen) {
14701                    // current and old nodes at the indexs
14702                    $cur = $kids[i];
14703                    oldstruct = $oldkids[j];
14704                    $old = oldstruct && oldstruct.node;
14705
14706                    if ($cur === $old) { // expected case - optimized for this case
14707                        // check attributes as specified by config
14708                        if (config.attr && oldstruct.attr) /* oldstruct.attr instead of textnode check */findAttributeMutations(mutations, $cur, oldstruct.attr, config.afilter);
14709                        // check character data if node is a comment or textNode and it's being observed
14710                        if (config.charData && oldstruct.charData !== undefined && $cur.nodeValue !== oldstruct.charData) {
14711                            mutations.push(MutationRecord({
14712                                type: "characterData",
14713                                target: $cur,
14714                                oldValue: oldstruct.charData
14715                            }));
14716                        }
14717
14718                        // resolve conflicts; it will be undefined if there are no conflicts - otherwise an array
14719                        if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
14720
14721                        // recurse on next level of children. Avoids the recursive call when there are no children left to iterate
14722                        if (config.descendents && ($cur.childNodes.length || oldstruct.kids && oldstruct.kids.length)) findMutations($cur, oldstruct);
14723
14724                        i++;
14725                        j++;
14726                    } else { // (uncommon case) lookahead until they are the same again or the end of children
14727                        dirty = true;
14728                        if (!map) { // delayed initalization (big perf benefit)
14729                            map = {};
14730                            conflicts = [];
14731                        }
14732                        if ($cur) {
14733                            // check id is in the location map otherwise do a indexOf search
14734                            if (!(map[id = getElementId($cur)])) { // to prevent double checking
14735                                // mark id as found
14736                                map[id] = true;
14737                                // custom indexOf using comparitor checking oldkids[i].node === $cur
14738                                if ((idx = indexOfCustomNode($oldkids, $cur, j)) === -1) {
14739                                    if (config.kids) {
14740                                        mutations.push(MutationRecord({
14741                                            type: "childList",
14742                                            target: node,
14743                                            addedNodes: [$cur], // $cur is a new node
14744                                            nextSibling: $cur.nextSibling,
14745                                            previousSibling: $cur.previousSibling
14746                                        }));
14747                                        numAddedNodes++;
14748                                    }
14749                                } else {
14750                                    conflicts.push({ // add conflict
14751                                        i: i,
14752                                        j: idx
14753                                    });
14754                                }
14755                            }
14756                            i++;
14757                        }
14758
14759                        if ($old &&
14760                            // special case: the changes may have been resolved: i and j appear congurent so we can continue using the expected case
14761                            $old !== $kids[i]
14762                        ) {
14763                            if (!(map[id = getElementId($old)])) {
14764                                map[id] = true;
14765                                if ((idx = indexOf($kids, $old, i)) === -1) {
14766                                    if (config.kids) {
14767                                        mutations.push(MutationRecord({
14768                                            type: "childList",
14769                                            target: old.node,
14770                                            removedNodes: [$old],
14771                                            nextSibling: $oldkids[j + 1], // praise no indexoutofbounds exception
14772                                            previousSibling: $oldkids[j - 1]
14773                                        }));
14774                                        numAddedNodes--;
14775                                    }
14776                                } else {
14777                                    conflicts.push({
14778                                        i: idx,
14779                                        j: j
14780                                    });
14781                                }
14782                            }
14783                            j++;
14784                        }
14785                    }// end uncommon case
14786                }// end loop
14787
14788                // resolve any remaining conflicts
14789                if (conflicts) resolveConflicts(conflicts, node, $kids, $oldkids, numAddedNodes);
14790            }
14791            findMutations($target, $oldstate);
14792            return dirty;
14793        }
14794
14795        /**
14796         * Utility
14797         * Cones a element into a custom data structure designed for comparision. https://gist.github.com/megawac/8201012
14798         *
14799         * @param {Node} $target
14800         * @param {!Object} config : A custom mutation config
14801         * @return {!Object} : Cloned data structure
14802         */
14803        function clone($target, config) {
14804            var recurse = true; // set true so childList we'll always check the first level
14805            return (function copy($target) {
14806                var elestruct = {
14807                    /** @type {Node} */
14808                    node: $target
14809                };
14810
14811                // Store current character data of target text or comment node if the config requests
14812                // those properties to be observed.
14813                if (config.charData && ($target.nodeType === 3 || $target.nodeType === 8)) {
14814                    elestruct.charData = $target.nodeValue;
14815                }
14816                // its either a element, comment, doc frag or document node
14817                else {
14818                    // Add attr only if subtree is specified or top level and avoid if
14819                    // attributes is a document object (#13).
14820                    if (config.attr && recurse && $target.nodeType === 1) {
14821                        /**
14822                         * clone live attribute list to an object structure {name: val}
14823                         * @type {Object.<string, string>}
14824                         */
14825                        elestruct.attr = reduce($target.attributes, function
14825(memo, attr) {
14826                            if (!config.afilter || config.afilter[attr.name]) {
14827                                memo[attr.name] = getAttributeValue($target, attr);
14828                            }
14829                            return memo;
14830                        }, {});
14831                    }
14832
14833                    // whether we should iterate the children of $target node
14834                    if (recurse && ((config.kids || config.charData) || (config.attr && config.descendents))) {
14835                        /** @type {Array.<!Object>} : Array of custom clone */
14836                        elestruct.kids = map($target.childNodes, copy);
14837                    }
14838
14839                    recurse = config.descendents;
14840                }
14841                return elestruct;
14842            })($target);
14843        }
14844
14845        /**
14846         * indexOf an element in a collection of custom nodes
14847         *
14848         * @param {NodeList} set
14849         * @param {!Object} $node : A custom cloned node
14850         * @param {number} idx : index to start the loop
14851         * @return {number}
14852         */
14853        function indexOfCustomNode(set, $node, idx) {
14854            return indexOf(set, $node, idx, JSCompiler_renameProperty("node"));
14855        }
14856
14857        // using a non id (eg outerHTML or nodeValue) is extremely naive and will run into issues with nodes that may appear the same like <li></li>
14858        var counter = 1; // don't use 0 as id (falsy)
14859        /** @const */
14860        var expando = "mo_id";
14861
14862        /**
14863         * Attempt to uniquely id an element for hashing. We could optimize this for legacy browsers but it hopefully wont be called enough to be a concern
14864         *
14865         * @param {Node} $ele
14866         * @return {(string|number)}
14867         */
14868        function getElementId($ele) {
14869            try {
14870                return $ele.id || ($ele[expando] = $ele[expando] || counter++);
14871            } catch (o_O) { // ie <8 will throw if you set an unknown property on a text node
14872                try {
14873                    return $ele.nodeValue; // naive
14874                } catch (shitie) { // when text node is removed: https://gist.github.com/megawac/8355978 :(
14875                    return counter++;
14876                }
14877            }
14878        }
14879
14880        /**
14881         * **map** Apply a mapping function to each item of a set
14882         * @param {Array|NodeList} set
14883         * @param {Function} iterator
14884         */
14885        function map(set, iterator) {
14886            var results = [];
14887            for (var index = 0; index < set.length; index++) {
14888                results[index] = iterator(set[index], index, set);
14889            }
14890            return results;
14891        }
14892
14893        /**
14894         * **Reduce** builds up a single result from a list of values
14895         * @param {Array|NodeList|NamedNodeMap} set
14896         * @param {Function} iterator
14897         * @param {*} [memo] Initial value of the memo.
14898         */
14899        function reduce(set, iterator, memo) {
14900            for (var index = 0; index < set.length; index++) {
14901                memo = iterator(memo, set[index], index, set);
14902            }
14903            return memo;
14904        }
14905
14906        /**
14907         * **indexOf** find index of item in collection.
14908         * @param {Array|NodeList} set
14909         * @param {Object} item
14910         * @param {number} idx
14911         * @param {string} [prop] Property on set item to compare to item
14912         */
14913        function indexOf(set, item, idx, prop) {
14914            for (/*idx = ~~idx*/; idx < set.length; idx++) {// start idx is always given as this is internal
14915                if ((prop ? set[idx][prop] : set[idx]) === item) return idx;
14916            }
14917            return -1;
14918        }
14919
14920        /**
14921         * @param {Object} obj
14922         * @param {(string|number)} prop
14923         * @return {boolean}
14924         */
14925        function has(obj, prop) {
14926            return obj[prop] !== undefined; // will be nicely inlined by gcc
14927        }
14928
14929        // GCC hack see https://stackoverflow.com/a/23202438/1517919
14930        function JSCompiler_renameProperty(a) {
14931            return a;
14932        }
14933
14934        return MutationObserver;
14935    })(void 0);
14936
14937/**
14938 * Copyright 2016 Google Inc. All Rights Reserved.
14939 *
14940 * Licensed under the W3C SOFTWARE AND DOCUMENT NOTICE AND LICENSE.
14941 *
14942 *  https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document
14943 *
14944 */
14945(function(window, document) {
14946    'use strict';
14947
14948// Exits early if all IntersectionObserver and IntersectionObserverEntry
14949// features are natively supported.
14950    if ('IntersectionObserver' in window &&
14951        'IntersectionObserverEntry' in window &&
14952        'intersectionRatio' in window.IntersectionObserverEntry.prototype) {
14953
14954        // Minimal polyfill for Edge 15's lack of `isIntersecting`
14955        // See: https://github.com/w3c/IntersectionObserver/issues/211
14956        if (!('isIntersecting' in window.IntersectionObserverEntry.prototype)) {
14957            Object.defineProperty(window.IntersectionObserverEntry.prototype,
14958                'isIntersecting', {
14959                    get: function () {
14960                        return this.intersectionRatio > 0;
14961                    }
14962                });
14963        }
14964        return;
14965    }
14966
14967    /**
14968     * An IntersectionObserver registry. This registry exists to hold a strong
14969     * reference to IntersectionObserver instances currently observering a target
14970     * element. Without this registry, instances without another reference may be
14971     * garbage collected.
14972     */
14973    var registry = [];
14974
14975
14976    /**
14977     * Creates the global IntersectionObserverEntry constructor.
14978     * https://w3c.github.io/IntersectionObserver/#intersection-observer-entry
14979     * @param {Object} entry A dictionary of instance properties.
14980     * @constructor
14981     */
14982    function IntersectionObserverEntry(entry) {
14983        this.time = entry.time;
14984        this.target = entry.target;
14985        this.rootBounds = entry.rootBounds;
14986        this.boundingClientRect = entry.boundingClientRect;
14987        this.intersectionRect = entry.intersectionRect || getEmptyRect();
14988        this.isIntersecting = !!entry.intersectionRect;
14989
14990        // Calculates the intersection ratio.
14991        var targetRect = this.boundingClientRect;
14992        var targetArea = targetRect.width * targetRect.height;
14993        var intersectionRect = this.intersectionRect;
14994        var intersectionArea = intersectionRect.width * intersectionRect.height;
14995
14996        // Sets intersection ratio.
14997        if (targetArea) {
14998            this.intersectionRatio = intersectionArea / targetArea;
14999        } else {
15000            // If area is zero and is intersecting, sets to 1, otherwise to 0
15001            this.intersectionRatio = this.isIntersecting ? 1 : 0;
15002        }
15003    }
15004
15005
15006    /**
15007     * Creates the global IntersectionObserver constructor.
15008     * https://w3c.github.io/IntersectionObserver/#intersection-observer-interface
15009     * @param {Function} callback The function to be invoked after intersection
15010     *     changes have queued. The function is not invoked if the queue has
15011     *     been emptied by calling the `takeRecords` method.
15012     * @param {Object=} opt_options Optional configuration options.
15013     * @constructor
15014     */
15015    function IntersectionObserver(callback, opt_options) {
15016
15017        var options = opt_options || {};
15018
15019        if (typeof callback !== 'function') {
15020            throw new Error('callback must be a function');
15021        }
15022
15023        if (options.root && options.root.nodeType != 1) {
15024            throw new Error('root must be an Element');
15025        }
15026
15027        // Binds and throttles `this._checkForIntersections`.
15028        this._checkForIntersections = throttle(
15029            this._checkForIntersections.bind(this), this.THROTTLE_TIMEOUT);
15030
15031        // Private properties.
15032        this._callback = callback;
15033        this._observationTargets = [];
15034        this._queuedEntries = [];
15035        this._rootMarginValues = this._parseRootMargin(options.rootMargin);
15036
15037        // Public properties.
15038        this.thresholds = this._initThresholds(options.threshold);
15039        this.root = options.root || null;
15040        this.rootMargin = this._rootMarginValues.map(function(margin) {
15041            return margin.value + margin.unit;
15042        }).join(' ');
15043    }
15044
15045
15046    /**
15047     * The minimum interval within which the document will be checked for
15048     * intersection changes.
15049     */
15050    IntersectionObserver.prototype.THROTTLE_TIMEOUT = 100;
15051
15052
15053    /**
15054     * The frequency in which the polyfill polls for intersection changes.
15055     * this can be updated on a per instance basis and must be set prior to
15056     * calling `observe` on the first target.
15057     */
15058    IntersectionObserver.prototype.POLL_INTERVAL = null;
15059
15060    /**
15061     * Use a mutation observer on the root element
15062     * to detect intersection changes.
15063     */
15064    IntersectionObserver.prototype.USE_MUTATION_OBSERVER = true;
15065
15066
15067    /**
15068     * Starts observing a target element for intersection changes based on
15069     * the thresholds values.
15070     * @param {Element} target The DOM element to observe.
15071     */
15072    IntersectionObserver.prototype.observe = function(target) {
15073        var isTargetAlreadyObserved = this._observationTargets.some(function(item) {
15074            return item.element == target;
15075        });
15076
15077        if (isTargetAlreadyObserved) {
15078            return;
15079        }
15080
15081        if (!(target && target.nodeType == 1)) {
15082            throw new Error('target must be an Element');
15083        }
15084
15085        this._registerInstance();
15086        this._observationTargets.push({element: target, entry: null});
15087        this._monitorIntersections();
15088        this._checkForIntersections();
15089    };
15090
15091
15092    /**
15093     * Stops observing a target element for intersection changes.
15094     * @param {Element} target The DOM element to observe.
15095     */
15096    IntersectionObserver.prototype.unobserve = function(target) {
15097        this._observationTargets =
15098            this._observationTargets.filter(function(item) {
15099
15100                return item.element != target;
15101            });
15102        if (!this._observationTargets.length) {
15103            this._unmonitorIntersections();
15104            this._unregisterInstance();
15105        }
15106    };
15107
15108
15109    /**
15110     * Stops observing all target elements for intersection changes.
15111     */
15112    IntersectionObserver.prototype.disconnect = function() {
15113        this._observationTargets = [];
15114        this._unmonitorIntersections();
15115        this._unregisterInstance();
15116    };
15117
15118
15119    /**
15120     * Returns any queue entries that have not yet been reported to the
15121     * callback and clears the queue. This can be used in conjunction with the
15122     * callback to obtain the absolute most up-to-date intersection information.
15123     * @return {Array} The currently queued entries.
15124     */
15125    IntersectionObserver.prototype.takeRecords = function() {
15126        var records = this._queuedEntries.slice();
15127        this._queuedEntries = [];
15128        return records;
15129    };
15130
15131
15132    /**
15133     * Accepts the threshold value from the user configuration object and
15134     * returns a sorted array of unique threshold values. If a value is not
15135     * between 0 and 1 and error is thrown.
15136     * @private
15137     * @param {Array|number=} opt_threshold An optional threshold value or
15138     *     a list of threshold values, defaulting to [0].
15139     * @return {Array} A sorted list of unique and valid threshold values.
15140     */
15141    IntersectionObserver.prototype._initThresholds = function(opt_threshold) {
15142        var threshold = opt_threshold || [0];
15143        if (!Array.isArray(threshold)) threshold = [threshold];
15144
15145        return threshold.sort().filter(function(t, i, a) {
15146            if (typeof t !== 'number' || isNaN(t) || t < 0 || t > 1) {
15147                throw new Error('threshold must be a number between 0 and 1 inclusively');
15148            }
15149            return t !== a[i - 1];
15150        });
15151    };
15152
15153
15154    /**
15155     * Accepts the rootMargin value from the user configuration object
15156     * and returns an array of the four margin values as an object c
15156ontaining
15157     * the value and unit properties. If any of the values are not properly
15158     * formatted or use a unit other than px or %, and error is thrown.
15159     * @private
15160     * @param {string=} opt_rootMargin An optional rootMargin value,
15161     *     defaulting to '0px'.
15162     * @return {Array<Object>} An array of margin objects with the keys
15163     *     value and unit.
15164     */
15165    IntersectionObserver.prototype._parseRootMargin = function(opt_rootMargin) {
15166        var marginString = opt_rootMargin || '0px';
15167        var margins = marginString.split(/\s+/).map(function(margin) {
15168            var parts = /^(-?\d*\.?\d+)(px|%)$/.exec(margin);
15169            if (!parts) {
15170                throw new Error('rootMargin must be specified in pixels or percent');
15171            }
15172            return {value: parseFloat(parts[1]), unit: parts[2]};
15173        });
15174
15175        // Handles shorthand.
15176        margins[1] = margins[1] || margins[0];
15177        margins[2] = margins[2] || margins[0];
15178        margins[3] = margins[3] || margins[1];
15179
15180        return margins;
15181    };
15182
15183
15184    /**
15185     * Starts polling for intersection changes if the polling is not already
15186     * happening, and if the page's visibilty state is visible.
15187     * @private
15188     */
15189    IntersectionObserver.prototype._monitorIntersections = function() {
15190        if (!this._monitoringIntersections) {
15191            this._monitoringIntersections = true;
15192
15193            // If a poll interval is set, use polling instead of listening to
15194            // resize and scroll events or DOM mutations.
15195            if (this.POLL_INTERVAL) {
15196                this._monitoringInterval = setInterval(
15197                    this._checkForIntersections, this.POLL_INTERVAL);
15198            }
15199            else {
15200                addEvent(window, 'resize', this._checkForIntersections, true);
15201                addEvent(document, 'scroll', this._checkForIntersections, true);
15202
15203                if (this.USE_MUTATION_OBSERVER && 'MutationObserver' in window) {
15204                    this._domObserver = new MutationObserver(this._checkForIntersections);
15205                    this._domObserver.observe(document, {
15206                        attributes: true,
15207                        childList: true,
15208                        characterData: true,
15209                        subtree: true
15210                    });
15211                }
15212            }
15213        }
15214    };
15215
15216
15217    /**
15218     * Stops polling for intersection changes.
15219     * @private
15220     */
15221    IntersectionObserver.prototype._unmonitorIntersections = function() {
15222        if (this._monitoringIntersections) {
15223            this._monitoringIntersections = false;
15224
15225            clearInterval(this._monitoringInterval);
15226            this._monitoringInterval = null;
15227
15228            removeEvent(window, 'resize', this._checkForIntersections, true);
15229            removeEvent(document, 'scroll', this._checkForIntersections, true);
15230
15231            if (this._domObserver) {
15232                this._domObserver.disconnect();
15233                this._domObserver = null;
15234            }
15235        }
15236    };
15237
15238
15239    /**
15240     * Scans each observation target for intersection changes and adds them
15241     * to the internal entries queue. If new entries are found, it
15242     * schedules the callback to be invoked.
15243     * @private
15244     */
15245    IntersectionObserver.prototype._checkForIntersections = function() {
15246        var rootIsInDom = this._rootIsInDom();
15247        var rootRect = rootIsInDom ? this._getRootRect() : getEmptyRect();
15248
15249        this._observationTargets.forEach(function(item) {
15250            var target = item.element;
15251            var targetRect = getBoundingClientRect(target);
15252            var rootContainsTarget = this._rootContainsTarget(target);
15253            var oldEntry = item.entry;
15254            var intersectionRect = rootIsInDom && rootContainsTarget &&
15255                this._computeTargetAndRootIntersection(target, rootRect);
15256
15257            var newEntry = item.entry = new IntersectionObserverEntry({
15258                time: now(),
15259                target: target,
15260                boundingClientRect: targetRect,
15261                rootBounds: rootRect,
15262                intersectionRect: intersectionRect
15263            });
15264
15265            if (!oldEntry) {
15266                this._queuedEntries.push(newEntry);
15267            } else if (rootIsInDom && rootContainsTarget) {
15268                // If the new entry intersection ratio has crossed any of the
15269                // thresholds, add a new entry.
15270                if (this._hasCrossedThreshold(oldEntry, newEntry)) {
15271                    this._queuedEntries.push(newEntry);
15272                }
15273            } else {
15274                // If the root is not in the DOM or target is not contained within
15275                // root but the previous entry for this target had an intersection,
15276                // add a new record indicating removal.
15277                if (oldEntry && oldEntry.isIntersecting) {
15278                    this._queuedEntries.push(newEntry);
15279                }
15280            }
15281        }, this);
15282
15283        if (this._queuedEntries.length) {
15284            this._callback(this.takeRecords(), this);
15285        }
15286    };
15287
15288
15289    /**
15290     * Accepts a target and root rect computes the intersection between then
15291     * following the algorithm in the spec.
15292     * TODO(philipwalton): at this time clip-path is not considered.
15293     * https://w3c.github.io/IntersectionObserver/#calculate-intersection-rect-algo
15294     * @param {Element} target The target DOM element
15295     * @param {Object} rootRect The bounding rect of the root after being
15296     *     expanded by the rootMargin value.
15297     * @return {?Object} The final intersection rect object or undefined if no
15298     *     intersection is found.
15299     * @private
15300     */
15301    IntersectionObserver.prototype._computeTargetAndRootIntersection =
15302        function(target, rootRect) {
15303
15304            // If the element isn't displayed, an intersection can't happen.
15305            if (window.getComputedStyle(target).display == 'none') return;
15306
15307            var targetRect = getBoundingClientRect(target);
15308            var intersectionRect = targetRect;
15309            var parent = getParentNode(target);
15310            var atRoot = false;
vendor: 9,839 bytes, lines 15311-15581
15311
15312            while (!atRoot) {
15313                var parentRect = null;
15314                var parentComputedStyle = parent.nodeType == 1 ?
15315                    window.getComputedStyle(parent) : {};
15316
15317                // If the parent isn't displayed, an intersection can't happen.
15318                if (parentComputedStyle.display == 'none') return;
15319
15320                if (parent == this.root || parent == document) {
15321                    atRoot = true;
15322                    parentRect = rootRect;
15323                } else {
15324                    // If the element has a non-visible overflow, and it's not the <body>
15325                    // or <html> element, update the intersection rect.
15326                    // Note: <body> and <html> cannot be clipped to a rect that's not also
15327                    // the document rect, so no need to compute a new intersection.
15328                    if (parent != document.body &&
15329                        parent != document.documentElement &&
15330                        parentComputedStyle.overflow != 'visible') {
15331                        parentRect = getBoundingClientRect(parent);
15332                    }
15333                }
15334
15335                // If either of the above conditionals set a new parentRect,
15336                // calculate new intersection data.
15337                if (parentRect) {
15338                    intersectionRect = computeRectIntersection(parentRect, intersectionRect);
15339
15340                    if (!intersectionRect) break;
15341                }
15342                parent = getParentNode(parent);
15343            }
15344            return intersectionRect;
15345        };
15346
15347
15348    /**
15349     * Returns the root rect after being expanded by the rootMargin value.
15350     * @return {Object} The expanded root rect.
15351     * @private
15352     */
15353    IntersectionObserver.prototype._getRootRect = function() {
15354        var rootRect;
15355        if (this.root) {
15356            rootRect = getBoundingClientRect(this.root);
15357        } else {
15358            // Use <html>/<body> instead of window since scroll bars affect size.
15359            var html = document.documentElement;
15360            var body = document.body;
15361            rootRect = {
15362                top: 0,
15363                left: 0,
15364                right: html.clientWidth || body.clientWidth,
15365                width: html.clientWidth || body.clientWidth,
15366                bottom: html.clientHeight || body.clientHeight,
15367                height: html.clientHeight || body.clientHeight
15368            };
15369        }
15370        return this._expandRectByRootMargin(rootRect);
15371    };
15372
15373
15374    /**
15375     * Accepts a rect and expands it by the rootMargin value.
15376     * @param {Object} rect The rect object to expand.
15377     * @return {Object} The expanded rect.
15378     * @private
15379     */
15380    IntersectionObserver.prototype._expandRectByRootMargin = function(rect) {
15381        var margins = this._rootMarginValues.map(function(margin, i) {
15382            return margin.unit == 'px' ? margin.value :
15383                margin.value * (i % 2 ? rect.width : rect.height) / 100;
15384        });
15385        var newRect = {
15386            top: rect.top - margins[0],
15387            right: rect.right + margins[1],
15388            bottom: rect.bottom + margins[2],
15389            left: rect.left - margins[3]
15390        };
15391        newRect.width = newRect.right - newRect.left;
15392        newRect.height = newRect.bottom - newRect.top;
15393
15394        return newRect;
15395    };
15396
15397
15398    /**
15399     * Accepts an old and new entry and returns true if at least one of the
15400     * threshold values has been crossed.
15401     * @param {?IntersectionObserverEntry} oldEntry The previous entry for a
15402     *    particular target element or null if no previous entry exists.
15403     * @param {IntersectionObserverEntry} newEntry The current entry for a
15404     *    particular target element.
15405     * @return {boolean} Returns true if a any threshold has been crossed.
15406     * @private
15407     */
15408    IntersectionObserver.prototype._hasCrossedThreshold =
15409        function(oldEntry, newEntry) {
15410
15411            // To make comparing easier, an entry that has a ratio of 0
15412            // but does not actually intersect is given a value of -1
15413            var oldRatio = oldEntry && oldEntry.isIntersecting ?
15414                oldEntry.intersectionRatio || 0 : -1;
15415            var newRatio = newEntry.isIntersecting ?
15416                newEntry.intersectionRatio || 0 : -1;
15417
15418            // Ignore unchanged ratios
15419            if (oldRatio === newRatio) return;
15420
15421            for (var i = 0; i < this.thresholds.length; i++) {
15422                var threshold = this.thresholds[i];
15423
15424                // Return true if an entry matches a threshold or if the new ratio
15425                // and the old ratio are on the opposite sides of a threshold.
15426                if (threshold == oldRatio || threshold == newRatio ||
15427                    threshold < oldRatio !== threshold < newRatio) {
15428                    return true;
15429                }
15430            }
15431        };
15432
15433
15434    /**
15435     * Returns whether or not the root element is an element and is in the DOM.
15436     * @return {boolean} True if the root element is an element and is in the DOM.
15437     * @private
15438     */
15439    IntersectionObserver.prototype._rootIsInDom = function() {
15440        return !this.root || containsDeep(document, this.root);
15441    };
15442
15443
15444    /**
15445     * Returns whether or not the target element is a child of root.
15446     * @param {Element} target The target element to check.
15447     * @return {boolean} True if the target element is a child of root.
15448     * @private
15449     */
15450    IntersectionObserver.prototype._rootContainsTarget = function(target) {
15451        return containsDeep(this.root || document, target);
15452    };
15453
15454
15455    /**
15456     * Adds the instance to the global IntersectionObserver registry if it isn't
15457     * already present.
15458     * @private
15459     */
15460    IntersectionObserver.prototype._registerInstance = function() {
15461        if (registry.indexOf(this) < 0) {
15462            registry.push(this);
15463        }
15464    };
15465
15466
15467    /**
15468     * Removes the instance from the global IntersectionObserver registry.
15469     * @private
15470     */
15471    IntersectionObserver.prototype._unregisterInstance = function() {
15472        var index = registry.indexOf(this);
15473        if (index != -1) registry.splice(index, 1);
15474    };
15475
15476
15477    /**
15478     * Returns the result of the performance.now() method or null in browsers
15479     * that don't support the API.
15480     * @return {number} The elapsed time since the page was requested.
15481     */
15482    function now() {
15483        return window.performance && performance.now && performance.now();
15484    }
15485
15486
15487    /**
15488     * Throttles a function and delays its executiong, so it's only called at most
15489     * once within a given time period.
15490     * @param {Function} fn The function to throttle.
15491     * @param {number} timeout The amount of time that must pass before the
15492     *     function can be called again.
15493     * @return {Function} The throttled function.
15494     */
15495    function throttle(fn, timeout) {
15496        var timer = null;
15497        return function () {
15498            if (!timer) {
15499                timer = setTimeout(function() {
15500                    fn();
15501                    timer = null;
15502                }, timeout);
15503            }
15504        };
15505    }
15506
15507
15508    /**
15509     * Adds an event handler to a DOM node ensuring cross-browser compatibility.
15510     * @param {Node} node The DOM node to add the event handler to.
15511     * @param {string} event The event name.
15512     * @param {Function} fn The event handler to add.
15513     * @param {boolean} opt_useCapture Optionally adds the even to the capture
15514     *     phase. Note: this only works in modern browsers.
15515     */
15516    function addEvent(node, event, fn, opt_useCapture) {
15517        if (typeof node.addEventListener === 'function') {
15518            node.addEventListener(event, fn, opt_useCapture || false);
15519        }
15520        else if (typeof node.attachEvent === 'function') {
15521            node.attachEvent('on' + event, fn);
15522        }
15523    }
15524
15525
15526    /**
15527     * Removes a previously added event handler from a DOM node.
15528     * @param {Node} node The DOM node to remove the event handler from.
15529     * @param {string} event The event name.
15530     * @param {Function} fn The event handler to remove.
15531     * @param {boolean} opt_useCapture If the event handler was added with this
15532     *     flag set to true, it should be set to true here in order to remove it.
15533     */
15534    function removeEvent(node, event, fn, opt_useCapture) {
15535        if (typeof node.removeEventListener === 'function') {
15536            node.removeEventListener(event, fn, opt_useCapture || false);
15537        }
15538        else if (typeof node.detatchEvent === 'function') {
15539            node.detatchEvent('on' + event, fn);
15540        }
15541    }
15542
15543
15544    /**
15545     * Returns the intersection between two rect objects.
15546     * @param {Object} rect1 The first rect.
15547     * @param {Object} rect2 The second rect.
15548     * @return {?Object} The intersection rect or undefined if no intersection
15549     *     is found.
15550     */
15551    function computeRectIntersection(rect1, rect2) {
15552        var top = Math.max(rect1.top, rect2.top);
15553        var bottom = Math.min(rect1.bottom, rect2.bottom);
15554        var left = Math.max(rect1.left, rect2.left);
15555        var right = Math.min(rect1.right, rect2.right);
15556        var width = right - left;
15557        var height = bottom - top;
15558
15559        return (width >= 0 && height >= 0) && {
15560            top: top,
15561            bottom: bottom,
15562            left: left,
15563            right: right,
15564            width: width,
15565            height: height
15566        };
15567    }
15568
15569
15570    /**
15571     * Shims the native getBoundingClientRect for compatibility with older IE.
15572     * @param {Element} el The element whose bounding rect to get.
15573     * @return {Object} The (possibly shimmed) rect of the element.
15574     */
15575    function getBoundingClientRect(el) {
15576        var rect;
15577
15578        try {
15579            rect = el.getBoundingClientRect();
15580        } catch (err) {
15581            // Ignore Windows 7 IE11 "Unspecified error"
15582            // https://github.com/w3c/IntersectionObserver/pull/205
15583        }
15584
15585        if (!rect) return getEmptyRect();
15586
15587        // Older IE
15588        if (!(rect.width && rect.height)) {
15589            rect = {
15590                top: rect.top,
15591                right: rect.right,
15592                bottom: rect.bottom,
15593                left: rect.left,
15594                width: rect.right - rect.left,
15595                height: rect.bottom - rect.top
15596            };
15597        }
15598        return rect;
15599    }
15600
15601
15602    /**
15603     * Returns an empty rect object. An empty rect is returned when an element
15604     * is not in the DOM.
15605     * @return {Object} The empty rect.
15606     */
15607    function getEmptyRect() {
15608        return {
15609            top: 0,
15610            bottom: 0,
15611            left: 0,
15612            right: 0,
15613            width: 0,
15614            height: 0
15615        };
15616    }
15617
15618    /**
15619     * Checks to see if a parent element contains a child elemnt (including inside
15620     * shadow DOM).
15621     * @param {Node} parent The parent element.
15622     * @param {Node} child The child element.
15623     * @return {boolean} True if the parent node contains the child node.
15624     */
15625    function containsDeep(parent, child) {
15626        var node = child;
15627        while (node) {
15628            if (node == parent) return true;
15629
15630            node = getParentNode(node);
15631        }
15632        return false;
15633    }
15634
15635
15636    /**
15637     * Gets the parent node of an element or its host element if the parent node
15638     * is a shadow root.
15639     * @param {Node} node The node whose parent to get.
15640     * @return {Node|null} The parent node or null if no parent exists.
15641     */
15642    function getParentNode(node) {
15643        var parent = node.parentNode;
15644
15645        if (parent && parent.nodeType == 11 && parent.host) {
15646            // If the parent is a shadow root, return the host element.
15647            return parent.host;
15648        }
15649        return parent;
15650    }
15651
15652
15653// Exposes the constructors globally.
15654    window.IntersectionObserver = IntersectionObserver;
15655    window.IntersectionObserverEntry = IntersectionObserverEntry;
15656
15657}(window, document));
15658
15659if (window.NodeList && !NodeList.prototype.forEach) {
15660    NodeList.prototype.forEach = function (callback, thisArg) {
15661        thisArg = thisArg || window;
15662        for (var i = 0; i < this.length; i++) {
15663            callback.call(thisArg, this[i], i, this);
15664        }
15665    };
15666}
15667
15668CAFE24.SMART_BANNER_DEFAULT = {
15669
15670    /**
15671     * ECHOSTING-331346 : 프론트화면에서 스마트배너 갱신시 화면 리로드
15672     * @returns {boolean}
15673     */
15674    reloadFrontPage: function () {
15675        addEventListener('message', function(e) {
15676
15677            if (e.origin.indexOf(EC_FRONT_JS_CONFIG_MANAGE.sDefaultAppDomain) < 0) {
15678                return false;
15679            }
15680
15681            var jsonData = JSON.parse(e.data);
15682
15683            if (jsonData == '' || jsonData.type == '') {
15684                return false;
15685            }
15686
15687            if (jsonData.type == 'frontReload') {
15688                window.location.reload();
15689                return true;
15690            }
15691
15692        }, false);
15693    }
15694};
15695
15696var SMART_BANNER_DEFAULT = CAFE24.getDeprecatedNamespace('SMART_BANNER_DEFAULT');
15697
15698EC$(function () {
15699
15700    try {
15701        // 스마트배너 모듈명이 존재하는지 확인
15702        var smartBannerModuleCount = EC$("div[module*='smart-banner-admin'],div[app4you-smart-banner*='smart-banner-admin']").length;
15703
15704        if (!smartBannerModuleCount) {
15705            return false;
15706        }
15707
15708        // SDK 가 로드되지 않은경우 필요값 설정
15709        if (typeof CAFE24API === "undefined") {
15710            CAFE24API = {
15711                MALL_ID: EC_FRONT_JS_CONFIG_MANAGE.sMallId,
15712                SHOP_NO: CAFE24.SDE_SHOP_NUM
15713            };
15714        }
15715
15716        // 스마트배너 모듈명이 존재할경우 ScriptTag Load
15717        var defaultAppScripts = document.createElement("script");
15718        defaultAppScripts.type = "text/javascript";
15719        defaultAppScripts.src = EC_FRONT_JS_CONFIG_MANAGE.sSmartBannerScriptUrl;
15720        EC$("head").append(defaultAppScripts);
15721
15722        // ECHOSTING-331346 : 프론트화면에서 스마트배너 갱신시 화면 리로드
15723        CAFE24.SMART_BANNER_DEFAULT.reloadFrontPage();
15724
15725    } catch (e) {
15726        if (typeof(e) === 'object' && e.stack && window.console) {
15727            console.log(e);
15728        }
15729    }
15730});
15731
15732CAFE24.KAKAO_PIXEL_BRIDGE = (function() {
15733    var bUseKakaoPixel = false;
15734    var oKakaoPixelInstance;
15735
15736    return {
15737
15738        /**
15739         * 카카오 픽셀 정보 세팅
15740         * @param sKakaoPixelId
15741         */
15742        init: function (sKakaoPixelId) {
15743            if (typeof kakaoPixel !== 'function' || typeof sKakaoPixelId === 'undefined') {
15744                return;
15745            }
15746
15747            if (CAFE24.KAKAO_PIXEL_BRIDGE.bUseKakaoPixel === true) {
15748                return;
15749            }
15750
15751            try {
15752                CAFE24.KAKAO_PIXEL_BRIDGE.oKakaoPixelInstance = kakaoPixel(sKakaoPixelId);
15753                CAFE24.KAKAO_PIXEL_BRIDGE.bUseKakaoPixel = true;
15754            } catch (error) {
15755                CAFE24.KAKAO_PIXEL_BRIDGE.bUseKakaoPixel = false;
15756            }
15757        },
15758
15759        /**
15760         * 상품 번호 반환
15761         * @param sCheckedProduct 선택된 상품
15762         * @returns {string}
15763         */
15764        getProductNo: function (sCheckedProduct) {
15765            return sCheckedProduct.split(':')[0];
15766        },
15767
15768        /**
15769         * 카카오픽셀 validation
15770         * @param sAction 이벤트 액션명
15771         * @returns {boolean}
15772         */
15773        getValidation: function(sAction)
15774        {
15775            return CAFE24.KAKAO_PIXEL_BRIDGE.bUseKakaoPixel === true && sAction in CAFE24.KAKAO_PIXEL_BRIDGE.oKakaoPixelInstance === true;
15776        },
15777
15778        /**
15779         * 기본 데이터 세팅
15780         * @param iProductNo 상품 번호
15781         * @returns {object}
15782         */
15783        getDefaultData: function(iProductNo) {
15784            var oData = {};
15785
15786            if (typeof iProductNo !== 'undefined') {
15787                oData['products'] = CAFE24.KAKAO_PIXEL_BRIDGE.getProductData([iProductNo]);
15788            }
15789
15790            return oData;
15791        },
15792
15793        /**
15794         * 상품 데이터 반환
15795         * @param {Array} aProductNo 상품번호
15796         * @returns {Array}
15797         */
15798        getProductData: function(aProductNo) {
15799            var aProductList = [];
15800
15801            if (Array.isArray(aProductNo) === false) {
15802                return aProductList;
15803            }
15804
15805            aProductNo.forEach(function(iProductNo) {
15806                aProductList.push({id: iProductNo});
15807            });
15808
15809            return aProductList;
15810        },
15811
15812        /**
15813         * 장바구니 등록 이벤트시 데이터 전송 처리
15814         * @param iProductNo 상품번호
15815         */
15816        addBasket: function (iProductNo) {
15817            if (CAFE24.KAKAO_PIXEL_BRIDGE.getValidation('addToCart') === false) {
15818                return;
15819            }
15820
15821            var oData = CAFE24.KAKAO_PIXEL_BRIDGE.getDefaultData(iProductNo);
15822            try {
15823                CAFE24.KAKAO_PIXEL_BRIDGE.oKakaoPixelInstance.addToCart(oData);
15824            } catch (error) {}
15825        },
15826
15827        /**
15828         * 관심상품 등록 이벤트시 데이터 전송 처리
15829         * @param iProductNo 상품번호
15830         */
15831        addWishList: function (iProductNo) {
15832            if (CAFE24.KAKAO_PIXEL_BRIDGE.getValidation('addToWishList') === false) {
15833                return;
15834            }
15835
15836            var oData = CAFE24.KAKAO_PIXEL_BRIDGE.getDefaultData(iProductNo);
15837            try {
15838                CAFE24.KAKAO_PIXEL_BRIDGE.oKakaoPixelInstance.addToWishList(oData);
15839            } catch (error) {}
15840        }
15841
15842    };
15843})();
15844
15845var EC_KakaoPixelBridge = CAFE24.getDeprecatedNamespace('KAKAO_PIXEL_BRIDGE');
15846CAPP_SHOP_FRONT_COMMON_UTIL = {
15847    findTargetFrame: function()
15848    {
15849        //팝업창 일경우에는 바로 opener를 반환
15850        if (CAPP_SHOP_FRONT_COMMON_UTIL.isPopupFromThisShopFront() === true) {
15851            return window.opener;
15852        }
15853
15854        try {
15855            var bIsIframe = false;
15856            var sUrl = document.location.pathname + document.location.search;
15857
15858            //parent의 프레임내용에서 현재주소와 동일 url을 가진 아이프레임이 있다면 아이프레임에서 실행된것으로 판단하고 parent를 반환
15859            EC$(parent.document).find('iframe').each(function() {
15860                if (sUrl === EC$(this).attr('src')) {
15861                    bIsIframe = true;
15862                    return false;
15863                }
15864            });
15865            if (bIsIframe === true) {
15866                return parent;
15867            }
15868        } catch (e) {}
15869
15870        //그 이외(일반페이지, 프레임셋)에서는 현재페이지에서 이동되는것으로 함
15871        return document;
15872    },
15873
15874    /**
15875     * 기존 코드와의 호환성 때문에 남겨둠
15876     * @return bool
15877     * @deprecated
15878     */
15879    isAdminOpener: function()
15880    {
15881        return this.isPopupFromThisShopFront();
15882    },
15883
15884    /**
15885     * 현재 창이 동일 쇼핑몰 내의 프론트에서 열려진 팝업창인지 리턴
15886     * @return bool 동일 쇼핑몰 내의 프론트에서 열려진 팝업창이면 true, 아니면 false
15887     */
15888    isPopupFromThisShopFront: function()
15889    {
15890        try {
15891            // 팝업창이 아니면 false 리턴
15892            if (window.opener === null) {
15893                return false;
15894            }
15895
15896            // 현재 창의 도메인과 opener의 도메인이 다르면 false 리턴
15897            if (window.location.host !== window.opener.location.host) {
15898                return false;
15899            }
15900
15901            // 어드민으로부터 열려진 경우 false 리턴
15902            var regAdminUrl = /^(\/admin\/php\/|\/disp\/admin\/)/;
15903            if (regAdminUrl.test(window.opener.location.pathname) === true) {
15904                return false;
15905            }
15906
15907            // 프론트로부터 열려진 경우이므로 true 리턴
15908            return true;
15909
15910        } catch (e) {
15911            // window.opener에 접근 불가능한 케이스는 이미 본 창이 닫혔거나 도메인이 다른 것이므로 false 리턴
15912            return false;
15913
15914        }
15915    },
15916
15917    /**
15918     * url에서 파라미터 가져오기
15919     * @param string name 파라미터명
15920     * @return string 파라미터 값
15921     */
15922     getParameterByName: function (name) {
15923        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
15924        var regexS = "[\\?&]" + name + "=([^&#]*)";
15925        var regex = new RegExp(regexS);
15926        var results = regex.exec(window.location.href);
15927
15928        if (results == null) {
15929            return '';
15930        } else {
15931            return decodeURIComponent(results[1].replace(/\+/g, " "));
15932        }
15933    },
15934
15935    historyBack: function(sMsg)
15936    {
15937        if (typeof(sMsg) !== 'undefined' && sMsg !== '') {
15938            alert(sMsg);
15939        }
15940
15941        if (this.isPopupFromThisShopFront() === true) {
15942            opener = window;
15943            window.close();
15944        } else {
15945            history.back();
15946        }
15947    },
15948
15949    /**
15950     * ECHOSTING-627626 네이버페이 navercheckout 진입을 POST 폼 제출로 처리한다.
15951     * - 기존 GET 네비게이션(location.href/window.open) 대신 POST 폼으로 CA_JS 광고 폼 데이터(analycis_form_data)를 동봉
15952     *   (~5KB, 최대 50KB → 쿼리스트링 URL 길이 한계 회피)
15953     * - 기존 쿼리 파라미터는 hidden 으로 이관. CA_JS 값은 버튼 클릭 시점에 취득(예외격리, REQ-008)
15954     * - 대상 창(oTargetWin)의 document 에 폼을 만들어 제출 → target/window.name 조작 없이 해당 창을 이동
15955     * @param {string} sUrl navercheckout URL (쿼리 포함 가능)
15956     * @param {object} oTargetWin 이동 대상 window (self/opener/parent). 미지정 시 현재 창
15957     * @param {boolean} bNewWindow 새 창(window.open) 여부
15958     */
15959    submitNaverCheckout: function(sUrl, oTargetWin, bNewWindow)
15960    {
15961        var sAction = sUrl;
15962        var sQuery = '';
15963        var iPos = sUrl.indexOf('?');
15964        if (iPos >= 0) {
15965            sAction = sUrl.substring(0, iPos);
15966            sQuery = sUrl.substring(iPos + 1);
15967        }
15968
15969        // 새 창이면 현재 document 에 만들고 target 으로 새 창 지정, 아니면 대상 창 document 에 생성
15970        var oDoc = document;
15971        if (bNewWindow !== true && oTargetWin && oTargetWin.document && oTargetWin !== window) {
15972            try {
15973                oDoc = oTargetWin.document;
15974            } catch (e) {
15975                oDoc = document;
15976            }
15977        }
15978
15979        var oForm = oDoc.createElement('form');
15980        oForm.method = 'POST';
15981        oForm.action = sAction;
15982
15983        // 기존 쿼리 파라미터 hidden 이관
15984        if (sQuery) {
15985            var aPairs = sQuery.split('&');
15986            for (var i = 0; i < aPairs.length; i++) {
15987                if (!aPairs[i]) { continue; }
15988                var iEq = aPairs[i].indexOf('=');
15989                var sName = iEq >= 0 ? aPairs[i].substring(0, iEq) : aPairs[i];
15990                var sVal = iEq >= 0 ? aPairs[i].substring(iEq + 1) : '';
15991                try { sVal = decodeURIComponent(sVal); } catch (e) {}
15992                CAPP_SHOP_FRONT_COMMON_UTIL._appendHiddenInput(oForm, sName, sVal);
15993            }
15994        }
15995
15996        // CA_JS 광고 폼 데이터(버튼 클릭 시점 취득, 비민감) — 예외격리
15997        try {
15998            if (typeof CA_JS !== 'undefined' && typeof CA_JS.GET_ANLYTICS_FORM_DATA === 'function') {
15999                var oFormData = CA_JS.GET_ANLYTICS_FORM_DATA();
16000                if (oFormData) {
16001                    CAPP_SHOP_FRONT_COMMON_UTIL._appendHiddenInput(oForm, 'analycis_form_data', JSON.stringify(oFormData));
16002                }
16003            }
16004        } catch (e) {}
16005
16006        if (bNewWindow === true) {
16007            var sName = 'navercheckout_' + (new Date()).getTime();
16008            window.open('', sName);
16009            oForm.target = sName;
16010        }
16011
16012        oDoc.body.appendChild(oForm);
16013        oForm.submit();
16014        if (oForm.parentNode) {
16015            oForm.parentNode.removeChild(oForm);
16016        }
16017    },
16018
16019    /**
16020     * ECHOSTING-627626 폼에 hidden input 추가 (IE 호환, 폼과 동일 document 사용)
16021     * @param {object} oForm 대상 form
16022     * @param {string} sName 필드명
16023     * @param {string} sValue 값
16024     */
16025    _appendHiddenInput: function(oForm, sName, sValue)
16026    {
16027        var oDoc = oForm.ownerDocument || document;
16028        var oInput;
16029        try {
16030            oInput = oDoc.createElement('<input name="' + sName + '">');
16031        } catch (e) {
16032            oInput = oDoc.createElement('input');
16033            oInput.setAttribute('name', sName);
16034        }
16035        oInput.setAttribute('type', 'hidden');
16036        oInput.value = sValue;
16037        oForm.appendChild(oInput);
16038    },
16039
16040    /**
16041     * [ECQAUNIT-75276] 서버 발행 알럿(몰 언어 문구)을 jet-translator 로 현재 선택 언어로 번역해 표시.
16042     *   서버 __() 는 몰 언어 기준이라 국가선택기 선택 언어와 다를 수 있다.
16043     *   엔진 미로드/현재언어==소스언어/번역 실패 시 원문 그대로 표시한다.
16044     *   (basket.js Basket._alertTranslated(ECQAINT-79580)를 전 프론트 공통으로 이동 — 담기확인창
16045     *    바로구매/관심상품 주문 등 basket.js 미로드 페이지의 주문 exec 알럿도 동일 처리)
16046     * @param {string} sMsg 알럿 원문
16047     */
16048    alertTranslated: function(sMsg)
16049    {
16050        try {
16051            var fnNorm = function(sLocale) {
16052                sLocale = (sLocale == null) ? '' : String(sLocale);
16053                var oZhMap = {'zh_CN': 'zh-CN', 'zh_TW': 'zh-TW', 'zh-CN': 'zh-CN', 'zh-TW': 'zh-TW'};
16054                if (oZhMap.hasOwnProperty(sLocale)) return oZhMap[sLocale];
16055                return sLocale.split(/[_-]/)[0];
16056            };
16057            var oJT = (typeof JetTranslator === 'undefined') ? null : JetTranslator;
16058            var oShop = (typeof CAFE24 !== 'undefined' && CAFE24.SHOP) ? CAFE24.SHOP : null;
16059            var aCookie = /(?:^|; )ec_front_language=([^;]*)/.exec(document.cookie);
16060            var sCur = fnNorm(aCookie ? decodeURIComponent(aCookie[1]) : '');
16061            var sSrc = fnNorm((oShop && typeof oShop.getLanguage === 'function') ? oShop.getLanguage() : '');
16062            if (!oJT || typeof oJT.translateTexts !== 'function' || sCur === '' || sCur === sSrc) {
16063                alert(sMsg);
16064                return;
16065            }
16066            oJT.translateTexts([sMsg], sCur).then(function(aRes) {
16067                alert((aRes || [])[0] || sMsg);
16068            }).catch(function() {
16069                alert(sMsg);
16070            });
16071        } catch (e) {
16072            // 번역 경로 실패 시 원문 표시로 폴백 — 예외는 진행 차단 없이 기록만
16073            if (typeof console !== 'undefined' && console.debug) console.debug(e);
16074            alert(sMsg);
16075        }
16076    }
16077};
16078
16079/**
16080 * console debug
16081 */
16082var EC_SHOP_FRONT_DEBUG = {
16083    bConsoleOut: false,
16084    log: function()
16085    {
16086        if (this.bConsoleOut === false) {
16087            return;
16088        }
16089        if (window.console) {
16090            console.log.apply(console, arguments);
16091        }
16092    },
16093    on: function()
16094    {
16095        this.bConsoleOut = true;
16096        localStorage.setItem('EC_SHOP_FRONT_DEBUG', '1');
16097        console.log("%c-- debug mode ON --", "color:rgb(249, 249, 249); font-size: 15px;");
16098    },
16099    off: function()
16100    {
16101        this.bConsoleOut = false;
16102        localStorage.removeItem('EC_SHOP_FRONT_DEBUG');
16103        console.log("%c-- debug mode OFF --", "color:rgb(249, 249, 249); font-size: 15px;");
16104    }
16105};
16106
16107// localStorage 기반 자동 활성화
16108if (localStorage.getItem('EC_SHOP_FRONT_DEBUG') === '1') {
16109    EC_SHOP_FRONT_DEBUG.bConsoleOut = true;
16110}
16111EC$(function() {
16112    /**
16113     * 이미지 롤오버
16114     * */
16115    EC$('img[id^="cate_img_"]')
16116        .parent()
16117        .mouseover(function() {
16118            var $img = EC$(this).find('img');
16119
16120            if (!$img.attr('org_src')) $img.attr('org_src', $img.attr('src'));
16121
16122            $img.attr('src', $img.attr('rollover'));
16123        })
16124        .mouseout(function() {
16125            var $img = EC$(this).find('img');
16126
16127            $img.attr('src', $img.attr('org_src'));
16128        });
16129        
16130    /**
16131     * 카테고리 상세분류를 보기위한 처리
16132     * 모바일은 온마우스 안됨
16133     * -구스킨은 레이어 무조건 노출중이라사용안함 
16134     */
16135    if (mobileWeb != true) {
16136        EC$('.xans-product-displaycategory .button').hover(
16137            function() {
16138                EC$(this).addClass('selected');
16139            },
16140            function() {
16141                EC$(this).removeClass('selected');
16142            }
16143        );
16144    } else {
16145        try {
16146            EC$(document).on('click', '.icoClose', function (v) {
16147                EC$('.xans-product-displaycategory .button').removeClass('selected');
16148                // event bubbling으로 추가
16149                return false;
16150            });
16151            EC$(document).on('click', '.xans-product-displaycategory .button', function (v) {
16152                EC$('.xans-product-displaycategory .button').removeClass('selected');
16153                EC$(this).closest('div .button').addClass('selected');
16154            });
16155        } catch (e) {}
16156    }
16157    
16158    /**
16159     * 서브카테고리 display - mouseOver
16160     * */
16161    /*
16162    EC$('.xans-product-listcategory a').mouseover(function(){
16163        
16164        var pNode = EC$(this).parents('li');
16165        var sHref = EC$(this).attr('href')
16166        sHref = sHref.substr(sHref.indexOf('?'));
16167        var sUrl = '/product/sub_category.html'+sHref; 
16168
16169        EC$.get(sUrl, '', function(result) {
16170            if (result != '') {
16171                EC$('#product-listcategory-read').remove();
16172                EC$(pNode).append('<div id="product-listcategory-read">'+result+'</div>');
16173                
16174                EC$('.xans-product-subcategory').css('left', '100px');
16175                subTop = EC$('.xans-product-subcategory').css('top').replace('px','') - 20;
16176                EC$('.xans-product-subcategory').css('top', subTop);
16177                EC$('.xans-product-subcategory').mouseover(function() {
16178                    EC$('.xans-product-subcategory').show();
16179                });
16180                
16181            }
16182        });
16183    });
16184
16185    EC$('.xans-product-listcategory a').mouseout(function(){
16186        //EC$('#product-listcategory-read').remove();
16187    });
16188    
16189    EC$('[id^="sub_cate"]').mouseout(function(){
16190        EC$(this).css('display:none;');
16191    });  
16192    */
16193});
16194
16195EC$(function() {
16196    ReferenceCurrencyPrice.init();
16197});
16198
16199var ReferenceCurrencyPrice = {
16200    sOriginReferCurrency : null,
16201    sReferCurrency : null,
16202    aCurrencyRate : null,
16203    aCurrencyInfo : null,
16204    sRefPrice : 'eRefPrice',
16205    sRefPriceUnitHead : 'eRefPriceUnitHead',
16206    sRefPriceUnitTail : 'eRefPriceUnitTail',
16207
16208    init : function () {
16209        var self = this;
16210        if (CAFE24.CURRENCY_INFO.isUseReferenceCurrency() !== true) { return; }
16211        this.getReferCurrency();
16212
16213        if (this.sOriginReferCurrency !== this.sReferCurrency) {
16214            this.setShopPrice();
16215            this.setCurrencyUnit();
16216        }
16217
16218    },
16219    getReferCurrency : function () {
16220        var self = this;
16221        this.sOriginReferCurrency = CAFE24.CURRENCY_INFO.getOriginReferenceCurrency();
16222        this.sReferCurrency = EC$.cookie('EC_REFER_CURRENCY_' + CAFE24.SDE_SHOP_NUM);
16223
16224        var CURRENCY_RATE = localStorage.getItem('EC_CURRENCY_RATE');
16225        this.aCurrencyRate = JSON.parse(CURRENCY_RATE);
16226        this.aCurrencyInfo = CAFE24.CURRENCY_INFO.getCurrencyList(this.sReferCurrency);
16227    },
16228    setShopPrice : function () {
16229        var self = this;
16230        var rate = CAFE24.SHOP_PRICE_FORMAT.detachFormat(ReferenceCurrencyPrice.aCurrencyRate[ReferenceCurrencyPrice.sOriginReferCurrency]["rates"][ReferenceCurrencyPrice.sReferCurrency]);
16231
16232        EC$('.' + ReferenceCurrencyPrice.sRefPrice).each(function() {
16233            if (EC$(this).attr('changed') === 'changed') { return; }
16234            if (rate == 0) {
16235                var fRefPrice = 0;
16236            } else {
16237                var fOriginRefPrice = CAFE24.SHOP_PRICE_FORMAT.detachFormat(EC$(this).text());
16238                var fRefPrice = fOriginRefPrice / rate;
16239            }
16240
16241            EC$(this).text(CAFE24.SHOP_PRICE.toPrice(fRefPrice, ReferenceCurrencyPrice.aCurrencyInfo));
16242            EC$(this).attr('changed', 'changed');
16243        });
16244
16245    },
16246    setCurrencyUnit : function () {
16247        var self = this;
16248
16249        //화폐단위
16250        var UnitFormat = this.aCurrencyInfo['currency_symbol'];
16251        //통화단위
16252        if (CAFE24.SHOP_CURRENCY_INFO[CAFE24.SDE_SHOP_NUM].aShopSubCurrencyInfo.display_type === 'M') {
16253            UnitFormat = this.sReferCurrency;
16254        }
16255        this.setUnitHead(UnitFormat);
16256        this.setUnitTail();
16257
16258    },
16259    setUnitHead : function (UnitFormat) {
16260        var self = this;
16261        EC$('.' + this.sRefPriceUnitHead).each(function() {
16262            if (EC$(this).attr('changed') === 'changed') { return; }
16263
16264            EC$(this).html(EC$(this).text().replace(/[^(\s]+/, UnitFormat));
16265            EC$(this).attr('changed', 'changed');
16266        });
16267
16268    },
16269    setUnitTail : function () {
16270        var self = this;
16271        EC$('.' + this.sRefPriceUnitTail).each(function() {
16272            if (EC$(this).attr('changed') === 'changed') { return; }
16273
16274            EC$(this).text(EC$(this).text().replace(/[^)\s]+/, ''));
16275            EC$(this).attr('changed', 'changed');
16276        });
16277
16278    }
16279
16280};
16281EC$(function() {
16282    // 엔터키 감지 후 해시태그 자동완성에 대한 처리
16283    EC$(this).keydown(function(event) {
16284        var oTarget = EC$('.autoDrop').find('li.selected');
16285
16286        if (event.keyCode === 13 && oTarget.length > 0) {
16287            event.preventDefault();
16288
16289            location.href = oTarget.children().attr('href');
16290        }
16291    });
16292
16293    // 검색 input에 대한 ↑, ↓키 입력시 커서 이동 방지
16294    EC$('.keyword').keydown(function(event) {
16295        if (event.keyCode === 38 || event.keyCode === 40) {
16296            event.preventDefault();
16297        }
16298    });
16299
16300    var bIsAutoDropFocus = false;
16301    EC$('.keyword, #keyword').focusout(function() {
16302        if (bIsAutoDropFocus === false) {
16303            EC$('ul.autoDrop,.autoList').hide();
16304            EC$('div.suggest > ul').hide();
16305        }
16306    });
16307
16308    EC$('ul.autoDrop, div.suggest > ul').mouseenter(function () {
16309        bIsAutoDropFocus = true;
16310    }).mouseleave(function() {
16311        bIsAutoDropFocus = false;
16312    });
16313
16314    FwValidator.Handler.setRequireErrorMsg('keyword', __('검색어를 입력해주세요'));
16315
16316    var oSearchForm = EC$('#searchForm');
16317    var oSearchFormKeyword = oSearchForm.find('#keyword');
16318
16319    var SEARCHREGISTER = {
16320
16321        eSearchType: function()
16322        {
16323            if (this.checkSearchType() === true) {
16324                EC$('#except_keyword_wrap_id').show();
16325            } else {
16326                EC$('#except_keyword_wrap_id').hide();
16327            }
16328        },
16329
16330        eSubmit: function()
16331        {
16332
16333            oSearchFormKeyword.removeAttr('fw-filter');
16334
16335            if (this.checkSearchType() === true && this.checkExceptKeyword() === false) {
16336                return false;
16337            }
16338
16339            var iCategoryNo = 0;
16340
16341            if (EC$("#category_no").length > 0) {
16342                iCategoryNo = EC$("#category_no option").index(EC$("#category_no option:selected"));
16343            }
16344
16345            if (this.checkPrice() === false && this.getKeyword() === null) {
16346                if (iCategoryNo === 0) {
16347                    oSearchFormKeyword.attr('fw-filter', 'isFill');
16348                }
16349            }
16350
16351            return true;
16352        },
16353
16354        checkSearchType: function () {
16355            if (EC$("#search_type").length < 1) {
16356                return true;
16357            }
16358            if (EC$("#search_type option:selected").val() === 'product_name') {
16359                return true;
16360            } else {
16361                return false;
16362            }
16363        },
16364
16365        checkExceptKeyword: function ()
16366        {
16367            var sKeyword = this.getKeyword();
16368
16369            var sExceptKeyWord = CAFE24.UTIL.trim(EC$('#exceptkeyword').val());
16370            if (sExceptKeyWord.length === 0) {
16371                return true;
16372            }
16373
16374
16375            if (sKeyword === null) {
16376                alert(__('제외검색어 입력 시 검색조건에 상품명을 반드시 입력하셔야 합니다.'));
16377                return false;
16378            }
16379
16380            var iFindWord = sKeyword.indexOf(sExceptKeyWord);
16381            if (iFindWord !== -1) {
16382                alert(__('제외검색어가 검색어에 포함되어 있어 검색할 수 없습니다.\n다시 입력해주세요.'));
16383                return false;
16384            }
16385
16386            return true;
16387        },
16388
16389        getKeyword: function ()
16390        {
16391            var sKeyWord = CAFE24.UTIL.trim(oSearchFormKeyword.val());
16392            if (sKeyWord.length === 0) {
16393                return null;
16394            }
16395            return sKeyWord;
16396        },
16397
16398        checkPrice: function ()
16399        {
16400          var iProduct_price_min = CAFE24.UTIL.trim(EC$('#product_price1').val());
16401          var iProduct_price_max = CAFE24.UTIL.trim(EC$('#product_price2').val());
16402
16403          if (iProduct_price_min.length === 0 && iProduct_price_max.length === 0) {
16404              return false;
16405          }
16406          return true;
16407        }
16408    };
16409
16410    SEARCHREGISTER.eSearchType();
16411
16412    EC$('#searchForm').submit(function(e) {
16413        if (SEARCHREGISTER.eSubmit() !== true) {
16414            return false;
16415        }
16416
16417        if (FwValidator.inspection('searchForm').passed !== true) {
16418            return false;
16419        }
16420
16421        return true;
16422    });
16423
16424    EC$('#search_type').change(function(e) {
16425        SEARCHREGISTER.eSearchType();
16426    });
16427
16428    EC$('#btn_search').click(function() {
16429        EC$('#searchBarForm').submit();
16430    });
16431
16432    EC$('input[name="keyword"]').on('keypress.ec-keyword-event', function(e) {
16433        if (e.keyCode == 13) {
16434            if (SEARCH_BANNER.isValidSearchAction(this) === false) {
16435                alert(__('검색어를 입력해주세요'));
16436                return false;
16437            }
16438            EC$(this).parents('form').submit();
16439        }
16440    });
16441
16442    EC$('[id=searchBarForm]').submit(function(e) {
16443        if (SEARCH_BANNER.isValidSearchAction(EC$(this).find('#keyword')) === false) {
16444            alert(__('검색어를 입력해주세요'));
16445            return false;
16446        }
16447
16448        if (mobileWeb === true || EC_MOBILE || EC_MOBILE_DEVICE) {
16449            $Recentword.saveRecentWord(EC$(this).find('#keyword').val());
16450        }
16451    });
16452
16453    EC$('.btn_order').click(function() {
16454        $type = EC$(this).attr('rel');
16455        EC$('#order_by').val($type);
16456
16457        EC$('#searchForm').submit();
16458    });
16459
16460    EC$('.btn_view').click(function() {
16461        $view = EC$(this).attr('rel');
16462
16463        if ($view != 'list') {
16464            $sAction = '/product/search_'+$view+'.html';
16465        } else {
16466            $sAction = '/product/search.html';
16467        }
16468
16469        EC$('#view_type').val($view);
16470        EC$('#searchForm').attr('action', $sAction);
16471        EC$('#searchForm').submit();
16472    });
16473
16474    // 검색어 관련 작업
16475    var aSearchKey = ReWriteSearchKey();
16476    if (aSearchKey !== false) {
16477        if (aSearchKey) {//ECHOSTING-44000
16478           var oSearchHeader = EC$(".xans-layout-searchheader").parent("form");
16479           oSearchHeader.find("#banner_action").val(aSearchKey.banner_action);
16480           oSearchHeader.find("#keyword").val(aSearchKey.msb_contents);
16481        }
16482    }
16483
16484    if (EC_MOBILE || EC_MOBILE_DEVICE) {
16485        EC$('#search_cancel').on('click', function() {
16486            EC$('html, body').css({'overflowY': 'auto', height: 'auto', width: '100%'});
16487            EC$('.dimmed').toggle();
16488            EC$('.xans-layout-searchheader').hide();
16489        });
16490
16491        EC$('.xans-layout-searchheader .searchInput').find('button.btnDelete').on('click', function() {
16492            var oForm = EC$(this).parents('form');
16493            EC$('input#keyword', '.xans-layout-searchheader').val('').focus();
16494            EC$('input#banner_action').val(''); //ECQAINT-8961 Delete버튼 클릭시 value 초기화
16495            oForm.find('#ec-product-searchdata-keyword_drop,.autoList').hide();
16496            oForm.find('#ec-product-searchdata-auto-list').hide();
16497        });
16498
16499        // 검색페이지에서 삭제
16500        EC$('.xans-search-form').find('button.btnDelete').on('click', function() {
16501            EC$('#searchForm').find('input#keyword').val('').focus();
16502        });
16503
16504        EC$('.header .search button').on('click', function() {
16505            if (EC$('#search_box').length > 0) {
16506                EC$('html, body').css({'overflowY': 'hidden', height: '100%', width: '100%'});
16507                EC$('.dimmed').toggle();
16508                EC$('#header .xans-layout-searchheader').toggle();
16509            } else {
16510                EC$('#header .xans-layout-searchheader').toggle();
16511            }
16512        });
16513        // 비동기 최근검색어
16514        EC$(document).on('click', '.recent_keyword_remove', function(){;
16515            $Recentword.removeCookie(EC$(this).attr('index'));
16516            EC$(this).parent('li').remove();
16517        });
16518        EC$(document).on('click', '.recent_keyword_remove_all', function(){
16519            $Recentword.removeAll();
16520            EC$('.xans-search-recentkeyword').find('li').remove();
16521            EC$('.xans-search-recentkeyword').find('p').removeClass();
16522        });
16523    }
16524
16525    // 예약상품 검색어 적용시 pc버젼에도 검색어 삭제 기능이 붙어서 기능 추가
16526    EC$('[name=keyword]').parent().find('.btnDelete').on('click', function() {
16527        EC$(this).parent().find('[name=keyword]').val('').focus().trigger('input');
16528        EC$('input#banner_action').val('');
16529    })
16530    // 검색어가 있을 경우에만 삭제버튼 추가
16531    EC$('[name=keyword]').on('input', function() {
16532        if (EC$(this).val() === '') {
16533            EC$(this).parent().find('.btnDelete').addClass('displaynone');
16534        } else {
16535            EC$(this).parent().find('.btnDelete').removeClass('displaynone')
16536        }
16537    }).trigger('input');
16538});
16539
16540function ReWriteSearchKey()
16541{
16542    if (typeof(sSearchBannerUseFlag) === "undefined") return false;
16543    if (sSearchBannerUseFlag == 'F') return false;
16544    if (typeof(aSearchBannerData) === "undefined") return false;
16545    if (aSearchBannerData.length === 0) return false;
16546    if (sSearchBannerType != 'F') return aSearchBannerData[Math.floor(Math.random() * aSearchBannerData.length)];
16547
16548    var aResultData = null;
16549    var sSearchKey = EC$.cookie('iSearchKey');
16550    var iSearchKey = 0;
16551
16552//    if ( sSearchKey !== null ) {//ECHOSTING-44000
16553    if (sSearchKey != undefined) {
16554        iSearchKey = parseInt(sSearchKey) + parseInt(1);
16555        if (iSearchKey >= aSearchBannerData.length) {
16556             iSearchKey = 0;
16557        }
16558    }
16559    EC$.cookie('iSearchKey', iSearchKey, {path: '/'});
16560
16561    return aSearchBannerData[iSearchKey];
16562}
16563
16564
16565var popProduct = {
16566
16567    selProduct: function(product_no,iPrdImg, sPrdName,sPrdPrice, sPrdTaxText, sCategoryName, iCategoryNo)
16568    {
16569        if (this.isGiftProduct(product_no) === false) {
16570            alert(sErrorMessage);
16571            return false;
16572        }
16573
16574        try {
16575            EC$('#aPrdLink', opener.document).attr('href', this.getUrl(product_no)).show();
16576            EC$('#aPrdNameLink', opener.document).attr('href', this.getUrl(product_no));
16577            EC$('#product_no', opener.document).val(product_no);
16578            EC$('#iPrdImg', opener.document).attr('src', iPrdImg);
16579            EC$('#sPrdName', opener.document).html(sPrdName.replace(/[\"]/g, '"'));
16580            EC$('#sPrdPrice', opener.document).html(sPrdPrice);
16581            EC$('#sPrdCommonImg', opener.document).html('');
16582
16583            if (EC$('#sPrdTaxText', opener.document).length > 0) {
16584                EC$('#sPrdTaxText', opener.document).html(sPrdTaxText);
16585            }
16586
16587            EC$('#iPrdView', opener.document).removeClass('displaynone').css('display', 'inline');
16588        } catch (e) {}
16589
16590        // ECHOSTING-61590
16591        var iSelectedOptionIndex = EC$('#subject', opener.document).prop('selectedIndex');
16592        EC$('#subject option', opener.document).remove();
16593        EC$('input[name^="fix_title_form_"]', opener.document).each(function (iIndex) {
16594            var sSubject = popProduct.getConvertString(EC$(this).val(), sPrdName, sCategoryName);
16595            // ECHOSTING-636244 XSS 방지 — 문자열 결합 대신 opener.document 컨텍스트의 DOM API로 조립
16596            EC$('<option>', opener.document).attr('value', sSubject).text(sSubject).appendTo(EC$('#subject', opener.document));
16597        });
16598        EC$('#subject', opener.document).prop('selectedIndex', iSelectedOptionIndex);
16599        EC$('#cate_no', opener.document).val(iCategoryNo);
16600
16601        /**
16602         * thunmail이미지에 링크가 걸렸을경우 링크 처리
16603         */
16604        var eAnchor = opener.document.getElementById('iPrdImg').parentNode;
16605        if ('A' === eAnchor.tagName.toUpperCase()) {
16606            eAnchor.href = this.getUrl(product_no);
16607        }
16608        window.close();
16609    },
16610
16611    getUrl: function(product_no)
16612    {
16613        var aPrdLink = opener.document.getElementById('aPrdLink').href;
16614        var iUrlIndex = aPrdLink.indexOf('product_no=');
16615
16616        var aPrdLinkSplit = aPrdLink.split('product_no=');
16617
16618        var aPrdParamSplit = aPrdLinkSplit[1].split('&');
16619
16620        aPrdParamSplit.shift();
16621
16622        return aPrdLink.substr(0, iUrlIndex)+'product_no='+product_no+(aPrdParamSplit.length > 0 ? '&'+aPrdParamSplit.join('&') : '');
16623    },
16624    // ECHOSTING-61590
16625    getConvertString: function(sSubject, sPrdName, sCategoryName)
16626    {
16627        sSubject = sSubject.replace('PRODUCT_NAME', sPrdName);
16628        return sSubject.replace('CATEGORY_NAME', sCategoryName);
16629    },
16630    isGiftProduct: function(iProductNum)
16631    {
16632        if (typeof aGiftReview === 'object') {
16633            if (aGiftReview[iProductNum] === 'F') {
16634                return false;
16635    }
16636        }
16637        return true;
16638    },
16639    END: function() {}
16640};
16641
16642/**
16643 * 상품 검색 배너
16644 */
16645var SEARCH_BANNER = {
16646    /**
16647     * 검색어가 정상적으로 입력되었는지 확인
16648     * @param {object} obj 검색폼 내부의 특정 엘리먼트가 필요합니다. (주로 검색어 input 혹은 submit 버튼)
16649     * @returns bool
16650     */
16651    isValidSearchAction : function(obj)
16652    {
16653        let bIsCalendarInput = true;
16654        // 달력이 있다면 둘중 하나만 입력해도 ok
16655        if (EC$('#ec-product-searchdata-calendar').length > 0) {
16656            bIsCalendarInput = CAFE24.UTIL.trim(EC$(obj).parents('form').find('#ec-product-searchdata-calendar').val()) !== '';
16657        }
16658        // 달력이 없다면 검색어
16659        // 헤더나 사이드의 검색어는 id가 keyword이나, 검색페이지의 검색어는 id가 ec-product-searchdata-keyword
16660        let bIsSearchKeywordInput = CAFE24.UTIL.trim(EC$(obj).parents('form').find('#keyword,#ec-product-searchdata-keyword').val()) !== '';
16661        return bIsCalendarInput || bIsSearchKeywordInput;
16662    },
16663    /**
16664     * 상품 검색 Submit
16665     */
16666    submitSearchBanner: function(obj)
16667    {
16668        var form = EC$(obj).parents('form');
16669
16670        if (form.find('#banner_action').val() != '') {
16671            // ECHOSTING-98878 상품검색키워드로 검색시에 폼전송이 되어 연결페이지로 이동이 안되고 검색페이지로 이동되는 오류 수정
16672            form.submit(function () {
16673                return false;
16674            });
16675            // 배너 연결 페이지 이동
16676            let sTargetUrl = form.find('#banner_action').val();
16677            if (form.find('#ec-product-searchdata-calendar').length > 0 && CAFE24.UTIL.trim(form.find('#ec-product-searchdata-calendar').val()) !== '') {
16678                sTargetUrl = sTargetUrl + '&search_period=' + form.find('#ec-product-searchdata-calendar').val();
16679            }
16680            location.replace(sTargetUrl);
16681        } else {
16682            if (SEARCH_BANNER.isValidSearchAction(obj) === false) {
16683                alert(__('검색어를 입력해주세요'));
16684                form.find('#keyword').focus();
16685                return;
16686            }
16687
16688            form.submit();
16689        }
16690    },
16691
16692    /**
16693     * 검색어 입력폼 클릭
16694     */
16695    clickSearchForm: function(obj)
16696    {
16697        var $oObject = EC$(obj);
16698        //ECHOSTING-105207 상품검색 키워드설정시 모바일에서 검색 결과 없음
16699        var $oForm = $oObject.parents('form');
16700        var $oBannerAction = $oForm.find('#banner_action');
16701        var $oAutoDrop = $oForm.find('#ec-product-searchdata-keyword_drop,.autoList');
16702
16703        if ($oBannerAction && $oBannerAction.length > 0 && $oBannerAction.val() != '') {
16704            if (EC_MOBILE || EC_MOBILE_DEVICE) {
16705                // ECHOSTING-98878 상품검색키워드로 검색시에 폼전송이 되어 연결페이지로 이동이 안되고 검색페이지로 이동되는 오류 수정
16706                $oForm.submit(function () {
16707                    return false;
16708                });
16709                // 배너 연결 페이지 이동
16710                location.replace($oBannerAction.val());
16711            }
16712            $oBannerAction.val('');
16713        }
16714        $oAutoDrop.hide();
16715        $oObject.val('').trigger('input');
16716    }
16717};
16718
16719/**
16720 * 최근검색어
16721 */
16722var $Recentword = {
16723    // recent length
16724    recentNum: 10,
16725
16726    // cookie expires
16727    expires: 10,
16728
16729    // duplication key
16730    duplicateKey: 0,
16731
16732    // recent string
16733    string: '',
16734
16735    // recent string
16736    prefix: 'RECENT_WORD_' + EC_SDE_SHOP_NUM + '_',
16737
16738    // sModuel
16739    sModule: 'xans-search-recentkeyword',
16740
16741    // recent
16742    $recent: null,
16743
16744    // recent list
16745    $recentList: null,
16746
16747    // list size
16748    size: 0,
16749
16750    // remove
16751    $remove: null,
16752    /**
16753     * save recent word
16754     */
16755
16756    init: function()
16757    {
16758        this.setObj();
16759        this.action();
16760        this.dimmed();
16761    },
16762
16763    dimmed: function()
16764    {
16765        try {
16766            EC$('.xans-layout-searchheader').after('<div class="dimmed"></div>');
16767        } catch (e) { }
16768    },
16769
16770    setObj: function()
16771    {
16772        this.$recent = EC$('.' + this.sModule);
16773
16774        this.$recentList = this.$recent.find('ul').find('li');
16775
16776        this.size = this.$recentList.length;
16777
16778        this.$remove = this.$recent.find('p');
16779    },
16780
16781    action: function()
16782    {
16783        var $hot = EC$('.xans-search-hotkeyword'), $title = EC$('#keyword_title');
16784
16785        if (EC$('.xans-layout-searchheader').find('ul.searchTab').hasClass('displaynone') === false) {
16786            this.$recent.hide();
16787            $title.hide();
16788        } else {
16789            $hot.hide();
16790        }
16791
16792        EC$('.xans-layout-searchheader').find('ul.searchTab').find('li').click(function() {
16793           var index = EC$(this).index();
16794           EC$(this).addClass('selected').siblings().removeClass('selected');
16795           if (index == 0) { $Recentword.$recent.hide(); $hot.show(); }
16796           else { $Recentword.$recent.show(); $hot.hide(); }
16797        });
16798    },
16799
16800    saveRecentWord: function(s)
16801    {
16802        this.string = s;
16803
16804        // 중복처리
16805        if (this.duplication() === false) { this.cookieOrder(); }
16806
16807        // 저장
16808        this.save();
16809    },
16810
16811    save: function()
16812    {
16813        var bFull = true;
16814        for (var i=1; i<=this.recentNum; i++) {
16815            if (EC$.cookie(this.prefix + i) == null) {
16816                bFull = false;
16817                this.add(i);
16818                break;
16819            }
16820        }
16821
16822        if (bFull == true) {
16823            this.removeFrist();
16824            this.add(this.recentNum);
16825        }
16826    },
16827
16828    duplication: function()
16829    {
16830        for (var k=1; k<=this.recentNum; k++) {
16831            if (EC$.cookie(this.prefix + k) == this.string) {
16832                this.duplicateKey = k;
16833                EC$.cookie(this.prefix + k, null, { path: '/' });
16834                return false;
16835            }
16836        }
16837    },
16838
16839    cookieOrder: function()
16840    {
16841        var s = this.duplicateKey + 1;
16842        for (var i=this.duplicateKey; i<=this.recentNum; i++) {
16843            if (EC$.cookie(this.prefix + s) != null) {
16844                this.add(i, EC$.cookie(this.prefix + s));
16845                this.removeCookie(s);
16846                s++;
16847            }
16848        }
16849    },
16850
16851    removeFrist: function()
16852    {
16853        for (var i=2, k=1; i<=this.recentNum; i++,k++) {
16854            EC$.cookie(this.prefix + k, EC$.cookie(this.prefix + i), { expires: this.expires, path: '/'});
16855        }
16856    },
16857
16858    add: function(key, duplicateString)
16859    {
16860        EC$.cookie(this.prefix + key, duplicateString || this.string, { expires: this.expires, path: '/'});
16861    },
16862
16863    removeCookie: function(key)
16864    {
16865        EC$.cookie(this.prefix + key, null, { path: '/' });
16866    },
16867
16868    removeAll: function()
16869    {
16870        for (var i=1; i<=this.recentNum; i++) { EC$.cookie(this.prefix + i, null, { path: '/' }); }
16871        this.setNoList();
16872    },
16873
16874    removeOne: function(key)
16875    {
16876        try {
16877            this.removeCookie(key);
16878            this.$recentList.each(function() { if (EC$(this).data('index') == key) { EC$(this).remove(); } });
16879            this.size--;
16880            if (this.size == 0) { this.setNoList(); }
16881        } catch (e) {
16882
16883        }
16884    },
16885
16886    setNoList: function()
16887    {
16888        try {
16889            this.$recentList.each(function() { EC$(this).remove(); });
16890            this.$remove.removeClass('displaynone');
16891        } catch (e) {
16892
16893        }
16894    }
16895};
16896
16897/*
16898 * 해시태그 json 검색
16899 */
16900var SEARCH_HASHTAG = {
16901    // 해시태그 json ajax url
16902    sAjaxHashtag: '/exec/front/shop/hashtag?type=',
16903
16904    // 해시태그 DB
16905    oJsonDB: null,
16906
16907    // 기본 검색어 uri
16908    sSearchUrl: '/product/search.html?keyword=',
16909
16910    /**
16911     * 엘라스틱 사용 여부 확인 메소드
16912     * @returns {boolean}
16913     */
16914    isElasticInUse: function()
16915    {
16916        // KR버젼
16917        if (typeof bUseElastic !== 'undefined') {
16918            if (bUseElastic === true) {
16919                return true;
16920            }
16921        }
16922
16923        // JP버젼
16924        if (CAFE24.FRONT_PRODUCT_SEARCH_DATA.getCommonObjectValue('V') === 6) {
16925            return CAFE24.FRONT_PRODUCT_SEARCH_DATA.getCommonObjectValue('bIsElasticInUse') === true;
16926        }
16927
16928        return false;
16929    },
16930    // 해시태그 json 파일 호출
16931    // oTarget: 검색 input object
16932    // sType: 검색 대상 타입 (product 또는 category)
16933    // sExternal: 외부에서의 호출 여부 (검색 input이 아닌 다른 영역 - 결과 내 검색)
16934    getHashtag: function(oTarget, sType, sExternal) {
16935        if (this.isElasticInUse() === false) {
16936            return;
16937        }
16938
16939        // 값이 없으면 기본값 할당
16940        if (typeof(sExternal) === 'undefined') {
16941            sExternal = 'F';
16942        }
16943
16944        var self = this;
16945        var sKeyword = CAFE24.UTIL.trim(oTarget.val());
16946        var oDrop = oTarget.parent().find('.autoDrop');
16947        var event = window.event || arguments.callee.caller.arguments[0];
16948
16949        // 외부에서의 호출이면 oDrop의 css가 다르기 때문에 다시 할당
16950        if (sExternal === 'T') {
16951            oDrop = oTarget.closest('.withinInput').find('ul');
16952        }
16953
16954        // 기본 타입 설정
16955        if (typeof(sType) === 'undefined' || sType === '') {
16956            sType = 'product';
16957        }
16958
16959        // 자동완성 영역이 있는 경우만 실행
16960        if (oDrop.length < 1) {
16961            return;
16962        }
16963
16964        if (typeof(mobileWeb) !== 'undefined' && mobileWeb === true) {
16965            // 모바일 검색 필터 레이어 > 결과 내 검색
16966            var oSearchdataWithin = EC$('.ec-product-searchdata-within');
16967
16968            // 결과 내 검색 input의 값이 있다면 class 추가 (반대는 제거)
16969            if (oSearchdataWithin.length > 0) {
16970                if (sKeyword.length > 0) {
16971                    oSearchdataWithin.closest('.xans-product-searchfilterlist').addClass('checked');
16972                } else {
16973                    oSearchdataWithin.closest('.xans-product-searchfilterlist').removeClass('checked');
16974                }
16975            }
16976        }
16977
16978        // 검색 input에서 Enter를 눌렀을 경우
16979        if (event.keyCode === 13) {
16980            // 현재 선택된 자동완성 값을 input에 넣어주고 검색 처리
16981            if (oDrop.find('.selected').length > 0) {
16982                oTarget.val(oDrop.find('.selected').text());
16983
16984                this.setHashtagHide(oDrop);
16985            }
16986
16987            // 검색 버튼이 있는 경우에는 바로 클릭 (이동)
16988            // 모바일 필터에는 바로 검색 버튼이 없음
16989            if (oTarget.attr('id') === '') {
16990                EC$('.withinInput button.btnResearch').click();
16991            }
16992
16993            return;
16994        }
16995
16996        // ↑, ↓키를 눌렀을 경우에는 팝업에 대한 처리만 진행
16997        if (event.keyCode === 38 || event.keyCode === 40) {
16998            oTarget.blur();
16999
17000            this.setKeyArrow(oDrop, event);
17001
17002            setTimeout(function() {
17003                oTarget.focus();
17004            }, 10);
17005
17006            return;
17007        }
17008
17009        // 실제 키워드에 대한 자동완성 처리 부분
17010        if (sKeyword !== '') {
17011            if (mobileWeb === true && EC$('body').hasClass("eMobilePopup") === false && sExternal === 'F') {
17012                EC$('#ec-product-searchdata-auto-list').show();
17013                EC$('body').addClass('eMobilePopup'); // fullsize 레이어팝업 노출시 body에 eMobilePopup 클래스 추가
17014                EC$('body').css('width', '100%');
17015            }
17016            if (this.oJsonDB === null) {
17017                // json 파일 존재여부 체크
17018                EC$.getJSON(this.sAjaxHashtag + sType, function(data) {
17019                    // 파일이 존재할 경우 url 리턴
17020                    // 리턴된 url로 json object 요청
17021                    if (data.url !== false) {
17022                        EC$.getJSON(data.url, function(data) {
17023                            if (data !== false) {
17024                                self.oJsonDB = TAFFY(data);
17025
17026                                self.setHashtagKeyword(oDrop, sKeyword, sExternal);
17027                            }
17028                        });
17029                    }
17030                });
17031            } else {
17032                this.setHashtagKeyword(oDrop, sKeyword, sExternal);
17033            }
17034        } else {
17035            this.setHashtagHide(oDrop);
17036        }
17037    },
17038
17039    // ↑, ↓키 처리 (drop 영역 키보드 컨트롤)
17040    setKeyArrow: function(oDrop, event) {
17041        var oTarget = oDrop.children('li');
17042        var oSelected = oDrop.children('li.selected');
17043        var oScroll = null;
17044
17045        if (oTarget.length > 0) {
17046            oTarget.removeClass('selected');
17047
17048            switch (event.keyCode) {
17049                // ↑
17050                case 38:
17051                    if (oSelected.length === 0 || oSelected.prev().length === 0) {
17052                        oScroll = oTarget.last().addClass('selected');
17053                    } else {
17054                        oScroll = oSelected.prev().addClass('selected');
17055                    }
17056
17057                    break;
17058                // ↓
17059                case 40:
17060                    if (oSelected.length === 0 || oSelected.next().length === 0) {
17061                        oScroll = oTarget.first().addClass('selected');
17062                    } else {
17063                        oScroll = oSelected.next().addClass('selected');
17064                    }
17065
17066                    break;
17067            }
17068
17069            if (oScroll !== null && oSelected.length > 0) {
17070                oDrop.scrollTop(oScroll.position().top + oDrop.scrollTop() - oScroll.height() * 3);
17071            }
17072        }
17073    },
17074
17075    // 검색된 해시태그 리스트 보이기/감추기
17076    setHashtagHide: function(oTarget, bFlag) {
17077        if (typeof(bFlag) === 'undefined' || bFlag === '') {
17078            bFlag = false;
17079        }
17080
17081        if (bFlag === false) {
17082            EC$('.autoList').hide();
17083            oTarget.hide();
17084        } else {
17085            EC$('.autoList').show();
17086            oTarget.show();
17087        }
17088    },
17089
17090    // 저장된 해시태그 json 파일에 대해 키워드로 검색 후 결과 출력
17091    setHashtagKeyword: function(oDrop, sKeyword, sExternal) {
17092        var self = this;
17093        var oJsonSearch = this.oJsonDB({tag: {like: sKeyword}}).order('tag asec').get();
17094
17095        oDrop.html('');
17096
17097        if (oJsonSearch.length !== 0) {
17098            var sSearchUrl = this.sSearchUrl+'%s';
17099            if (oDrop.parents('form').find('.ec-search-calendar').length === 1 && oDrop.parents('form').find('.ec-search-calendar').val() !== '') {
17100                sSearchUrl = sSearchUrl+'&search_period=' + oDrop.parents('form').find('.ec-search-calendar').val();
17101            }
17102            this.setHashtagHide(oDrop, true);
17103
17104            oJsonSearch.forEach(function(oResult) {
17105                // 검색된 키워드에 대해서 bold 처리 (검색 결과에서 검색어로 입력했던 문자만)
17106                if (CAFE24.UTIL.trim(oResult.tag) !== '') {
17107                    if (sExternal === 'T') {
17108                        oDrop.append('<li keyword="' + oResult.tag + '">' + oResult.tag.replace(sKeyword, '<strong>' + sKeyword + '</strong>') + '</li>');
17109                    } else {
17110                        oDrop.append('<li><a href="' + sprintf(sSearchUrl, encodeURI(oResult.tag)) + '">' + oResult.tag.replace(sKeyword, '<strong>' + sKeyword + '</strong>') + '</a></li>');
17111                    }
17112                }
17113            });
17114        } else {
17115            this.setHashtagHide(oDrop);
17116        }
17117    }
17118};
17119var TAFFY,exports,T;!function(){"use strict";var _t_,_e_,_n_,_r_,_i_,_s_,_u_,_o_,_c_,_a_,_l_,_f_,_h_,_T_,_g_,_F_,_p_,_d_,_A_,_v_,_y_,_m_,___,_x_;if(!TAFFY)for(_i_="2.7",_s_=1,_u_="000000",_o_=1e3,_c_={},_x_=function(_t_){var _e_=Array.prototype.slice.call(_t_);return _e_.sort()},_a_=function(_t_){return TAFFY.isArray(_t_)||TAFFY.isObject(_t_)?_t_:JSON.parse(_t_)},_A_=function(_t_,_e_){return _v_(_t_,function(_t_){return _e_.indexOf(_t_)>=0})},_v_=function(_t_,_e_,_n_){var _r_=[];return null==_t_?_r_:Array.prototype.filter&&_t_.filter===Array.prototype.filter?_t_.filter(_e_,_n_):(_l_(_t_,function(_t_,_i_,_s_){_e_.call(_n_,_t_,_i_,_s_)&&(_r_[_r_.length]=_t_)}),_r_)},___=function(_t_){return"[object RegExp]"===Object.prototype.toString.call(_t_)},_m_=function(_t_){var _e_=T.isArray(_t_)?[]:T.isObject(_t_)?{}:null;if(null===_t_)return _t_;for(var _n_ in _t_)_e_[_n_]=___(_t_[_n_])?_t_[_n_].toString():T.isArray(_t_[_n_])||T.
17119isObject(_t_[_n_])?_m_(_t_[_n_]):_t_[_n_];return _e_},_y_=function(_t_){var _e_=JSON.stringify(_t_);return null===_e_.match(/regex/)?_e_:JSON.stringify(_m_(_t_))},_l_=function(_t_,_e_,_n_){var _r_,_i_,_s_,_u_;if(_t_&&(T.isArray(_t_)&&1===_t_.length||!T.isArray(_t_)))_e_(T.isArray(_t_)?_t_[0]:_t_,0);else for(_s_=0,_t_=T.isArray(_t_)?_t_:[_t_],_u_=_t_.length;_u_>_s_&&(_i_=_t_[_s_],T.isUndefined(_i_)&&!_n_||(_r_=_e_(_i_,_s_),_r_!==T.EXIT));_s_++);},_f_=function(_t_,_e_){var _n_,_r_,_i_=0;for(_r_ in _t_)if(_t_.hasOwnProperty(_r_)&&(_n_=_e_(_t_[_r_],_r_,_i_++),_n_===T.EXIT))break},_c_.extend=function(_t_,_e_){_c_[_t_]=function(){return _e_.apply(this,_x_(arguments))}},_h_=function(_t_){var _e_;return T.isString(_t_)&&/[t][0-9]*[r][0-9]*/i.test(_t_)?!0:T.isObject(_t_)&&_t_.___id&&_t_.___s?!0:T.isArray(_t_)?(_e_=!0,_l_(_t_,function(_t_){return _h_(_t_)?void 0:(_e_=!1,TAFFY.EXIT)}),_e_):!1},_g_=function(_t_,_e_){var _n_=!0;return _l_(_e_,function(_e_){switch(T.typeOf(_e_)){case"function":if(!_e_.apply(_t_))return _n_=!1,TAFFY.EXIT;break;case"array":_n_=1===_e_.length?_g_(_t_,_e_[0]):2===_e_.length?_g_(_t_,_e_[0])||_g_(_t_,_e_[1]):3===_e_.length?_g_(_t_,_e_[0])||_g_(_t_,_e_[1])||_g_(_t_,_e_[2]):4===_e_.length?_g_(_t_,_e_[0])||_g_(_t_,_e_[1])||_g_(_t_,_e_[2])||_g_(_t_,_e_[3]):!1,_e_.length>4&&_l_(_e_,function(_e_){_g_(_t_,_e_)&&(_n_=!0)})}}),_n_},_T_=function(_t_){var _e_=[];return T.isString(_t_)&&/[t][0-9]*[r][0-9]*/i.test(_t_)&&(_t_={___id:_t_}),T.isArray(_t_)?(_l_(_t_,function(_t_){_e_.push(_T_(_t_))}),_t_=function(){var _t_=this,_n_=!1;return _l_(_e_,function(_e_){_g_(_t_,_e_)&&(_n_=!0)}),_n_}):T.isObject(_t_)?(T.isObject(_t_)&&_t_.___id&&_t_.___s&&(_t_={___id:_t_.___id}),_f_(_t_,function(_t_,_n_){T.isObject(_t_)||(_t_={is:_t_}),_f_(_t_,function(_t_,_r_){var _i_,_s_=[];_i_="hasAll"===_r_?function(_t_,_e_){_e_(_t_)}:_l_,_i_(_t_,function(_t_){var _e_,_i_=!0;_e_=function(){var _e_,_s_=this[_n_],_u_="==",_o_="!=",_c_="===",_a_="<",_l_=">",_f_="<=",_h_=">=",_T_="!==";return"undefined"==typeof _s_?!1:(0===_r_.indexOf("!")&&_r_!==_o_&&_r_!==_T_&&(_i_=!1,_r_=_r_.substring(1,_r_.length)),_e_="regex"===_r_?_t_.test(_s_):"lt"===_r_||_r_===_a_?_t_>_s_:"gt"===_r_||_r_===_l_?_s_>_t_:"lte"===_r_||_r_===_f_?_t_>=_s_:"gte"===_r_||_r_===_h_?_s_>=_t_:"left"===_r_?0===_s_.indexOf(_t_):"leftnocase"===_r_?0===_s_.toLowerCase().indexOf(_t_.toLowerCase()):"right"===_r_?_s_.substring(_s_.length-_t_.length)===_t_:"rightnocase"===_r_?_s_.toLowerCase().substring(_s_.length-_t_.length)===_t_.toLowerCase():"like"===_r_?_s_.indexOf(_t_)>=0:"likenocase"===_r_?_s_.toLowerCase().indexOf(_t_.toLowerCase())>=0:_r_===_c_||"is"===_r_?_s_===_t_:_r_===_u_?_s_==_t_:_r_===_T_?_s_!==_t_:_r_===_o_?_s_!=_t_:"isnocase"===_r_?_s_.toLowerCase?_s_.toLowerCase()===_t_.toLowerCase():_s_===_t_:"has"===_r_?T.has(_s_,_t_):"hasall"===_r_?T.hasAll(_s_,_t_):"contains"===_r_?TAFFY.isArray(_s_)&&_s_.indexOf(_t_)>-1:-1!==_r_.indexOf("is")||TAFFY.isNull(_s_)||TAFFY.isUndefined(_s_)||TAFFY.isObject(_t_)||TAFFY.isArray(_t_)?T[_r_]&&T.isFunction(T[_r_])&&0===_r_.indexOf("is")?T[_r_](_s_)===_t_:T[_r_]&&T.isFunction(T[_r_])?T[_r_](_s_,_t_):!1:_t_===_s_[_r_],_e_=_e_&&!_i_?!1:_e_||_i_?_e_:!0)},_s_.push(_e_)}),_e_.push(1===_s_.length?_s_[0]:function(){var _t_=this,_e_=!1;return _l_(_s_,function(_n_){_n_.apply(_t_)&&(_e_=!0)}),_e_})})}),_t_=function(){var _t_=this,_n_=!0;return _n_=(1!==_e_.length||_e_[0].apply(_t_))&&(2!==_e_.length||_e_[0].apply(_t_)&&_e_[1].apply(_t_))&&(3!==_e_.length||_e_[0].apply(_t_)&&_e_[1].apply(_t_)&&_e_[2].apply(_t_))&&(4!==_e_.length||_e_[0].apply(_t_)&&_e_[1].apply(_t_)&&_e_[2].apply(_t_)&&_e_[3].apply(_t_))?!0:!1,_e_.length>4&&_l_(_e_,function(_e_){_g_(_t_,_e_)||(_n_=!1)}),_n_}):T.isFunction(_t_)?_t_:void 0},_p_=function(_t_,_e_){var _n_=function(_t_,_n_){var _r_=0;return T.each(_e_,function(_e_){var _i_,_s_,_u_,_o_,_c_;if(_i_=_e_.split(" "),_s_=_i_[0],_u_=1===_i_.length?"logical":_i_[1],"logical"===_u_)_o_=_F_(_t_[_s_]),_c_=_F_(_n_[_s_]),T.each(_o_.length<=_c_.length?_o_:_c_,function(_t_,_e_){return _o_[_e_]<_c_[_e_]?(_r_=-1,TAFFY.EXIT):_o_[_e_]>_c_[_e_]?(_r_=1,TAFFY.EXIT):void 0});else if("logicaldesc"===_u_)_o_=_F_(_t_[_s_]),_c_=_F_(_n_[_s_]),T.each(_o_.length<=_c_.length?_o_:_c_,function(_t_,_e_){return _o_[_e_]>_c_[_e_]?(_r_=-1,TAFFY.EXIT):_o_[_e_]<_c_[_e_]?(_r_=1,TAFFY.EXIT):void 0});else{if("asec"===_u_&&_t_[_s_]<_n_[_s_])return _r_=-1,T.EXIT;if("asec"===_u_&&_t_[_s_]>_n_[_s_])return _r_=1,T.EXIT;if("desc"===_u_&&_t_[_s_]>_n_[_s_])return _r_=-1,T.EXIT;if("desc"===_u_&&_t_[_s_]<_n_[_s_])return _r_=1,T.EXIT}return 0===_r_&&"logical"===_u_&&_o_.length<_c_.length?_r_=-1:0===_r_&&"logical"===_u_&&_o_.length>_c_.length?_r_=1:0===_r_&&"logicaldesc"===_u_&&_o_.length>_c_.length?_r_=-1:0===_r_&&"logicaldesc"===_u_&&_o_.length<_c_.length&&(_r_=1),0!==_r_?T.EXIT:void 0}),_r_};return _t_&&_t_.push?_t_.sort(_n_):_t_},function(){var _t_={},_e_=0;_F_=function(_n_){return _e_>_o_&&(_t_={},_e_=0),_t_["_"+_n_]||function(){var _r_,_i_,_s_,_u_=String(_n_),_o_=[],_c_="_",_a_="";for(_r_=0,_i_=_u_.length;_i_>_r_;_r_++)_s_=_u_.charCodeAt(_r_),_s_>=48&&57>=_s_||46===_s_?("n"!==_a_&&(_a_="n",_o_.push(_c_.toLowerCase()),_c_=""),_c_+=_u_.charAt(_r_)):("s"!==_a_&&(_a_="s",_o_.push(parseFloat(_c_)),_c_=""),_c_+=_u_.charAt(_r_));return _o_.push("n"===_a_?parseFloat(_c_):_c_.toLowerCase()),_o_.shift(),_t_["_"+_n_]=_o_,_e_++,_o_}()}}(),_d_=function(){this.context({results:this.getDBI().query(this.context())})},_c_.extend("filter",function(){var _t_=TAFFY.mergeObj(this.context(),{run:null}),_e_=[];return _l_(_t_.q,function(_t_){_e_.push(_t_)}),_t_.q=_e_,_l_(_x_(arguments),function(_e_){_t_.q.push(_T_(_e_)),_t_.filterRaw.push(_e_)}),this.getroot(_t_)}),_c_.extend("order",function(_t_){_t_=_t_.split(",");var _e_,_n_=[];return _l_(_t_,function(_t_){_n_.push(_t_.replace(/^\s*/,"").replace(/\s*$/,""))}),_e_=TAFFY.mergeObj(this.context(),{sort:null}),_e_.order=_n_,this.getroot(_e_)}),_c_.extend("limit",function(_t_){var _e_,_n_=TAFFY.mergeObj(this.context(),{});return _n_.limit=_t_,_n_.run&&_n_.sort&&(_e_=[],_l_(_n_.results,function(_n_,_r_){return _r_+1>_t_?TAFFY.EXIT:void _e_.push(_n_)}),_n_.results=_e_),this.getroot(_n_)}),_c_.extend("start",function(_t_){var _e_,_n_=TAFFY.mergeObj(this.context(),{});return _n_.start=_t_,_n_.run&&_n_.sort&&!_n_.limit?(_e_=[],_l_(_n_.results,function(_n_,_r_){_r_+1>_t_&&_e_.push(_n_)}),_n_.results=_e_):_n_=TAFFY.mergeObj(this.context(),{run:null,start:_t_}),this.getroot(_n_)}),_c_.extend("update",function(_t_,_e_,_n_){var _r_,_i_=!0,_s_={},_u_=_x_(arguments);return!TAFFY.isString(_t_)||2!==arguments.length&&3!==arguments.length?(_s_=_t_,2===_u_.length&&(_i_=_e_)):(_s_[_t_]=_e_,3===arguments.length&&(_i_=_n_)),_r_=this,_d_.call(this),_l_(this.context().results,function(_t_){var _e_=_s_;TAFFY.isFunction(_e_)?_e_=_e_.apply(TAFFY.mergeObj(_t_,{})):T.isFunction(_e_)&&(_e_=_e_(TAFFY.mergeObj(_t_,{}
17119))),TAFFY.isObject(_e_)&&_r_.getDBI().update(_t_.___id,_e_,_i_)}),this.context().results.length&&this.context({run:null}),this}),_c_.extend("remove",function(_t_){var _e_=this,_n_=0;return _d_.call(this),_l_(this.context().results,function(_t_){_e_.getDBI().remove(_t_.___id),_n_++}),this.context().results.length&&(this.context({run:null}),_e_.getDBI().removeCommit(_t_)),_n_}),_c_.extend("count",function(){return _d_.call(this),this.context().results.length}),_c_.extend("callback",function(_t_,_e_){if(_t_){var _n_=this;setTimeout(function(){_d_.call(_n_),_t_.call(_n_.getroot(_n_.context()))},_e_||0)}return null}),_c_.extend("get",function(){return _d_.call(this),this.context().results}),_c_.extend("stringify",function(){return JSON.stringify(this.get())}),_c_.extend("first",function(){return _d_.call(this),this.context().results[0]||!1}),_c_.extend("last",function(){return _d_.call(this),this.context().results[this.context().results.length-1]||!1}),_c_.extend("sum",function(){var _t_=0,_e_=this;return _d_.call(_e_),_l_(_x_(arguments),function(_n_){_l_(_e_.context().results,function(_e_){_t_+=_e_[_n_]||0})}),_t_}),_c_.extend("min",function(_t_){var _e_=null;return _d_.call(this),_l_(this.context().results,function(_n_){(null===_e_||_n_[_t_]<_e_)&&(_e_=_n_[_t_])}),_e_}),function(){var _t_=function(){var _t_,_e_,_n_;return _t_=function(_t_,_e_,_n_){var _r_,_i_,_s_;switch(2===_n_.length?(_r_=_t_[_n_[0]],_s_="===",_i_=_e_[_n_[1]]):(_r_=_t_[_n_[0]],_s_=_n_[1],_i_=_e_[_n_[2]]),_s_){case"===":return _r_===_i_;case"!==":return _r_!==_i_;case"<":return _i_>_r_;case">":return _r_>_i_;case"<=":return _i_>=_r_;case">=":return _r_>=_i_;case"==":return _r_==_i_;case"!=":return _r_!=_i_;default:throw String(_s_)+" is not supported"}},_e_=function(_t_,_e_){var _n_,_r_,_i_={};for(_n_ in _t_)_t_.hasOwnProperty(_n_)&&(_i_[_n_]=_t_[_n_]);for(_n_ in _e_)_e_.hasOwnProperty(_n_)&&"___id"!==_n_&&"___s"!==_n_&&(_r_=TAFFY.isUndefined(_i_[_n_])?"":"right_",_i_[_r_+String(_n_)]=_e_[_n_]);return _i_},_n_=function(_n_){var _r_,_i_,_s_=_x_(arguments),_u_=_s_.length,_o_=[];if("function"!=typeof _n_.filter){if(!_n_.TAFFY)throw"TAFFY DB or result not supplied";_r_=_n_()}else _r_=_n_;return this.context({results:this.getDBI().query(this.context())}),TAFFY.each(this.context().results,function(_n_){_r_.each(function(_r_){var _c_,_a_=!0;t:for(_i_=1;_u_>_i_&&(_c_=_s_[_i_],_a_="function"==typeof _c_?_c_(_n_,_r_):"object"==typeof _c_&&_c_.length?_t_(_n_,_r_,_c_):!1,_a_);_i_++);_a_&&_o_.push(_e_(_n_,_r_))})}),TAFFY(_o_)()}}();_c_.extend("join",_t_)}(),_c_.extend("max",function(_t_){var _e_=null;return _d_.call(this),_l_(this.context().results,function(_n_){(null===_e_||_n_[_t_]>_e_)&&(_e_=_n_[_t_])}),_e_}),_c_.extend("select",function(){var _t_=[],_e_=_x_(arguments);return _d_.call(this),1===arguments.length?_l_(this.context().results,function(_n_){_t_.push(_n_[_e_[0]])}):_l_(this.context().results,function(_n_){var _r_=[];_l_(_e_,function(_t_){_r_.push(_n_[_t_])}),_t_.push(_r_)}),_t_}),_c_.extend("distinct",function(){var _t_=[],_e_=_x_(arguments);return _d_.call(this),1===arguments.length?_l_(this.context().results,function(_n_){var _r_=_n_[_e_[0]],_i_=!1;_l_(_t_,function(_t_){return _r_===_t_?(_i_=!0,TAFFY.EXIT):void 0}),_i_||_t_.push(_r_)}):_l_(this.context().results,function(_n_){var _r_=[],_i_=!1;_l_(_e_,function(_t_){_r_.push(_n_[_t_])}),_l_(_t_,function(_t_){var _n_=!0;return _l_(_e_,function(_e_,_i_){return _r_[_i_]!==_t_[_i_]?(_n_=!1,TAFFY.EXIT):void 0}),_n_?(_i_=!0,TAFFY.EXIT):void 0}),_i_||_t_.push(_r_)}),_t_}),_c_.extend("supplant",function(_t_,_e_){var _n_=[];return _d_.call(this),_l_(this.context().results,function(_e_){_n_.push(_t_.replace(/\{([^\{\}]*)\}/g,function(_t_,_n_){var _r_=_e_[_n_];return"string"==typeof _r_||"number"==typeof _r_?_r_:_t_}))}),_e_?_n_:_n_.join("")}),_c_.extend("each",function(_t_){return _d_.call(this),_l_(this.context().results,_t_),this}),_c_.extend("map",function(_t_){var _e_=[];return _d_.call(this),_l_(this.context().results,function(_n_){_e_.push(_t_(_n_))}),_e_}),T=function(_t_){var _e_,_n_,_r_,_i_=[],_o_={},_F_=1,_d_={template:!1,onInsert:!1,onUpdate:!1,onRemove:!1,onDBChange:!1,storageName:!1,forcePropertyCase:null,cacheSize:100,name:""},_A_=new Date,_v_=0,_m_=0,___={};return _n_=function(_t_){var _e_=[],_r_=!1;return 0===_t_.length?_i_:(_l_(_t_,function(_t_){T.isString(_t_)&&/[t][0-9]*[r][0-9]*/i.test(_t_)&&_i_[_o_[_t_]]&&(_e_.push(_i_[_o_[_t_]]),_r_=!0),T.isObject(_t_)&&_t_.___id&&_t_.___s&&_i_[_o_[_t_.___id]]&&(_e_.push(_i_[_o_[_t_.___id]]),_r_=!0),T.isArray(_t_)&&_l_(_t_,function(_t_){_l_(_n_(_t_),function(_t_){_e_.push(_t_)})})}),_r_&&_e_.length>1&&(_e_=[]),_e_)},_e_={dm:function(_t_){return _t_&&(_A_=_t_,___={},_v_=0,_m_=0),_d_.onDBChange&&setTimeout(function(){_d_.onDBChange.call(_i_)},0),_d_.storageName&&setTimeout(function(){localStorage.setItem("taffy_"+_d_.storageName,JSON.stringify(_i_))}),_A_},insert:function(_t_,_n_){var _c_=[],_h_=[],_T_=_a_(_t_);return _l_(_T_,function(_t_,_r_){var _a_,_T_;return T.isArray(_t_)&&0===_r_?(_l_(_t_,function(_t_){_c_.push("lower"===_d_.forcePropertyCase?_t_.toLowerCase():"upper"===_d_.forcePropertyCase?_t_.toUpperCase():_t_)}),!0):(T.isArray(_t_)?(_a_={},_l_(_t_,function(_t_,_e_){_a_[_c_[_e_]]=_t_}),_t_=_a_):T.isObject(_t_)&&_d_.forcePropertyCase&&(_T_={},_f_(_t_,function(_e_,_n_){_T_["lower"===_d_.forcePropertyCase?_n_.toLowerCase():"upper"===_d_.forcePropertyCase?_n_.toUpperCase():_n_]=_t_[_n_]}),_t_=_T_),_F_++,_t_.___id="T"+String(_u_+_s_).slice(-6)+"R"+String(_u_+_F_).slice(-6),_t_.___s=!0,_h_.push(_t_.___id),_d_.template&&(_t_=T.mergeObj(_d_.template,_t_)),_i_.push(_t_),_o_[_t_.___id]=_i_.length-1,_d_.onInsert&&(_n_||TAFFY.isUndefined(_n_))&&_d_.onInsert.call(_t_),void _e_.dm(new Date))}),_r_(_h_)},sort:function(_t_){return _i_=_p_(_i_,_t_.split(",")),_o_={},_l_(_i_,function(_t_,_e_){_o_[_t_.___id]=_e_}),_e_.dm(new Date),!0},update:function(_t_,_n_,_r_){var _s_,_u_,_c_,_a_,_l_={};_d_.forcePropertyCase&&(_f_(_n_,function(_t_,_e_){_l_["lower"===_d_.forcePropertyCase?_e_.toLowerCase():"upper"===_d_.forcePropertyCase?_e_.toUpperCase():_e_]=_t_}),_n_=_l_),_s_=_i_[_o_[_t_]],_u_=T.mergeObj(_s_,_n_),_c_={},_a_=!1,_f_(_u_,function(_t_,_e_){(TAFFY.isUndefined(_s_[_e_])||_s_[_e_]!==_t_)&&(_c_[_e_]=_t_,_a_=!0)}),_a_&&(_d_.onUpdate&&(_r_||TAFFY.isUndefined(_r_))&&_d_.onUpdate.call(_u_,_i_[_o_[_t_]],_c_),_i_[_o_[_t_]]=_u_,_e_.dm(new Date))},remove:function(_t_){_i_[_o_[_t_]].___s=!1},removeCommit:function(_t_){var _n_;for(_n_=_i_.length-1;_n_>-1;_n_--)_i_[_n_].___s||(_d_.onRemove&&(_t_||TAFFY.isUndefined(_t_))&&_d_.onRemove.call(_i_[_n_]),_o_[_i_[_n_].___id]=void 0,_i_.splice(_n_,1));_o_={},_l_(_i_,function(_t_,_e_){_o_[_t_.___id]=_e_}),_e_.dm(new Date)},query:function(_t_){var _r_,_s_,_u_,_o_,_c_,_a_;if(_d_.cacheSize&&(_s_="",_l_(_t_.filterRaw,function(_t_){return T.isFunction(_t_)?(_s_="nocache",TAFFY.EXIT):void 0}),""===_s_&&(_s_=_y_(T.mergeObj(_t_,{q:!1,run:!1,sort:!1})))),!_t_.results||!_t_.run||_t_.run&&_e_.dm()>_t_.run){if(_u_=[],_d_.cacheSize&&___[_s_])return ___[_s_].i=_v_++,___[_s_].results;0===_t_.q.length&&0===_t_.index.length?(_l_(_i_,function(_t_){_u_.push(_t_)}),_r_=_u_):(_o_=_n_(_t_.index),_l_(_o_,function(_e_){(0===_t_.q.length||_g_(_e_,_t_.q))&&_u_.push(_e_)}),_r_=_u_)}else _r_=_t_.results;return!(_t_.order.length>0)||_t_.run&&_t_.sort||(_r_=_p_(_r_,_t_.order)),_r_.length&&(_t_.limit&&_t_.limit<_r_.length||_t_.start)&&(_c_=[],_l_(_r_,function(_e_,_n_){if(!_t_.start||_t_.start&&_n_+1>=_t_.start)if(_t_.limit){if(_a_=_t_.start?_n_+1-_t_.start:_n_,_a_<_t_.limit)_c_.push(_e_);else if(_a_>_t_.limit)return TAFFY.EXIT}else _c_.push(_e_)}),_r_=_c_),_d_.cacheSize&&"nocache"!==_s_&&(_m_++,setTimeout(function(){var _t_,_e_;_m_>=2*_d_.cacheSize&&(_m_=0,_t_=_v_-_d_.cacheSize,_e_={},_f_(function(_n_,_r_){_n_.i>=_t_&&(_e_[_r_]=_n_)}),___=_e_)},0),___[_s_]={i:_v_++,results:_r_}),_r_}},_r_=function(){var _t_,_n_;return _t_=TAFFY.mergeObj(TAFFY.mergeObj(_c_,{insert:void 0}),{getDBI:function(){return _e_},getroot:function(_t_){return _r_.call(_t_)},context:function(_t_){return _t_&&(_n_=TAFFY.mergeObj(_n_,_t_.hasOwnProperty("results")?TAFFY.mergeObj(_t_,{run:new Date,sort:new Date}):_t_)),_n_},extend:void 0}),_n_=this&&this.q?this:{limit:!1,start:!1,q:[],filterRaw:[],index:[],order:[],results:!1,run:null,sort:null,settings:_d_},_l_(_x_(arguments),function(_t_){_h_(_t_)?_n_.index.push(_t_):_n_.q.push(_T_(_t_)),_n_.filterRaw.push(_t_)}),_t_},_s_++,_t_&&_e_.insert(_t_),_r_.insert=_e_.insert,_r_.merge=function(_t_,_n_,_i_){var _s_={},_u_=[],_o_={};return _i_=_i_||!1,_n_=_n_||"id",_l_(_t_,function(_t_){var _o_;_s_[_n_]=_t_[_n_],_u_.push(_t_[_n_]),_o_=_r_(_s_).first(),_o_?_e_.update(_o_.___id,_t_,_i_):_e_.insert(_t_,_i_)}),_o_[_n_]=_u_,_r_(_o_)},_r_.TAFFY=!0,_r_.sort=_e_.sort,_r_.settings=function(_t_){return _t_&&(_d_=TAFFY.mergeObj(_d_,_t_),_t_.template&&_r_().update(_t_.template)),_d_},_r_.store=function(_t_){var _e_,_n_=!1;return localStorage&&(_t_&&(_e_=localStorage.getItem("taffy_"+_t_),_e_&&_e_.length>0&&(_r_.insert(_e_),_n_=!0),_i_.length>0&&setTimeout(function(){localStorage.setItem("taffy_"+_d_.storageName,JSON.stringify(_i_))})),_r_.settings({storageName:_t_})),_r_},_r_},TAFFY=T,T.each=_l_,T.eachin=_f_,T.extend=_c_.extend,TAFFY.EXIT="TAFFYEXIT",TAFFY.mergeObj=function(_t_,_e_){var _n_={};return _f_(_t_,function(_e_,_r_){_n_[_r_]=_t_[_r_]}),_f_(_e_,function(_t_,_r_){_n_[_r_]=_e_[_r_]}),_n_},TAFFY.has=function(_t_,_e_){var _n_,_r_=!1;if(_t_.TAFFY)return _r_=_t_(_e_),_r_.length>0?!0:!1;switch(T.typeOf(_t_)){case"object":if(T.isObject(_e_))_f_(_e_,function(_n_,_i_){return _r_!==!0||T.isUndefined(_t_[_i_])||!_t_.hasOwnProperty(_i_)?(_r_=!1,TAFFY.EXIT):void(_r_=T.has(_t_[_i_],_e_[_i_]))});else if(T.isArray(_e_))_l_(_e_,function(_n_,_i_){return _r_=T.has(_t_,_e_[_i_]),_r_?TAFFY.EXIT:void 0});else if(T.isString(_e_))return TAFFY.isUndefined(_t_[_e_])?!1:!0;return _r_;case"array":if(T.isObject(_e_))_l_(_t_,function(_n_,_i_){return _r_=T.has(_t_[_i_],_e_),_r_===!0?TAFFY.EXIT:void 0});else if(T.isArray(_e_))_l_(_e_,function(_n_,_i_){return _l_(_t_,function(_n_,_s_){return _r_=T.has(_t_[_s_],_e_[_i_]),_r_===!0?TAFFY.EXIT:void 0}),_r_===!0?TAFFY.EXIT:void 0});else if(T.isString(_e_)||T.isNumber(_e_))for(_r_=!1,_n_=0;_n_<_t_.length;_n_++)if(_r_=T.has(_t_[_n_],_e_))return!0;return _r_;case"string":if(T.isString(_e_)&&_e_===_t_)return!0;break;default:if(T.typeOf(_t_)===T.typeOf(_e_)&&_t_===_e_)return!0}return!1},TAFFY.hasAll=function(_t_,_e_){var _n_,_r_=TAFFY;return _r_.isArray(_e_)?(_n_=!0,_l_(_e_,function(_e_){return _n_=_r_.has(_t_,_e_),_n_===!1?TAFFY.EXIT:void 0}),_n_):_r_.has(_t_,_e_)},TAFFY.typeOf=function(_t_){var _e_=typeof _t_;return"object"===_e_&&(_t_?"number"!=typeof _t_.length||_t_.propertyIsEnumerable("length")||(_e_="array"):_e_="null"),_e_},TAFFY.getObjectKeys=function(_t_){var _e_=[];return _f_(_t_,function(_t_,_n_){_e_.push(_n_)}),_e_.sort(),_e_},TAFFY.isSameArray=function(_t_,_e_){return TAFFY.isArray(_t_)&&TAFFY.isArray(_e_)&&_t_.join(",")===_e_.join(",")?!0:!1},TAFFY.isSameObject=function(_t_,_e_){var _n_=TAFFY,_r_=!0;return _n_.isObject(_t_)&&_n_.isObject(_e_)&&_n_.isSameArray(_n_.getObjectKeys(_t_),_n_.getObjectKeys(_e_))?_f_(_t_,function(_i_,_s_){return _n_.isObject(_t_[_s_])&&_n_.isObject(_e_[_s_])&&_n_.isSameObject(_t_[_s_],_e_[_s_])||_n_.isArray(_t_[_s_])&&_n_.isArray(_e_[_s_])&&_n_.isSameArray(_t_[_s_],_e_[_s_])||_t_[_s_]===_e_[_s_]?void 0:(_r_=!1,TAFFY.EXIT)}):_r_=!1,_r_},_t_=["String","Number","Object","Array","Boolean","Null","Function","Undefined"],_e_=function(_t_){return function(_e_){return TAFFY.typeOf(_e_)===_t_.toLowerCase()?!0:!1}},_n_=0;_n_<_t_.length;_n_++)_r_=_t_[_n_],TAFFY["is"+_r_]=_e_(_r_)}(),"object"==typeof exports&&(exports.taffy=TAFFY);
17120
17121/*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net)
17122 * Licensed under the MIT License (LICENSE.txt).
17123 *
17124 * Version 3.0.0
17125 */
17126
17127(function (factory) {
17128    if (typeof define === 'function' && define.amd) {
17129        // AMD. Register as an anonymous module.
17130        define(['jquery'], factory);
17131    } else {
17132        // Browser globals
17133        factory(jQuery);
17134    }
17135}(function ($) {
17136    $.fn.bgiframe = function(s) {
17137        s = $.extend({
17138            top         : 'auto', // auto == borderTopWidth
17139            left        : 'auto', // auto == borderLeftWidth
17140            width       : 'auto', // auto == offsetWidth
17141            height      : 'auto', // auto == offsetHeight
17142            opacity     : true,
17143            src         : 'javascript:false;',
17144            conditional : /MSIE 6.0/.test(navigator.userAgent) // expresion or function. return false to prevent iframe insertion
17145        }, s);
17146
17147        // wrap conditional in a function if it isn't already
17148        if (!$.isFunction(s.conditional)) {
17149            var condition = s.conditional;
17150            s.conditional = function() { return condition; };
17151        }
17152
17153        var $iframe = $('<iframe class="bgiframe"frameborder="0"tabindex="-1"src="'+s.src+'"'+
17154                           'style="display:block;position:absolute;z-index:-1;"/>');
17155
17156        return this.each(function() {
17157            var $this = $(this);
17158            if ( s.conditional(this) === false ) { return; }
17159            var existing = $this.children('iframe.bgiframe');
17160            var $el = existing.length === 0 ? $iframe.clone() : existing;
17161            $el.css({
17162                'top': s.top == 'auto' ?
17163                    ((parseInt($this.css('borderTopWidth'),10)||0)*-1)+'px' : prop(s.top),
17164                'left': s.left == 'auto' ?
17165                    ((parseInt($this.css('borderLeftWidth'),10)||0)*-1)+'px' : prop(s.left),
17166                'width': s.width == 'auto' ? (this.offsetWidth + 'px') : prop(s.width),
17167                'height': s.height == 'auto' ? (this.offsetHeight + 'px') : prop(s.height),
17168                'opacity': s.opacity === true ? 0 : undefined
17169            });
17170
17171            if ( existing.length === 0 ) {
17172                $this.prepend($el);
17173            }
17174        });
17175    };
17176
17177    // old alias
17178    $.fn.bgIframe = $.fn.bgiframe;
17179
17180    function prop(n) {
17181        return n && n.constructor === Number ? n + 'px' : n;
17182    }
17183
17184}));
17185/**
17186 * Cookie plugin
17187 *
17188 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
17189 * Dual licensed under the MIT and GPL licenses:
17190 * http://www.opensource.org/licenses/mit-license.php
17191 * http://www.gnu.org/licenses/gpl.html
17192 *
17193 */
17194
17195/**
17196 * Create a cookie with the given name and value and other optional parameters.
17197 *
17198 * @example $.cookie('the_cookie', 'the_value');
17199 * @desc Set the value of a cookie.
17200 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
17201 * @desc Create a cookie with all available options.
17202 * @example $.cookie('the_cookie', 'the_value');
17203 * @desc Create a session cookie.
17204 * @example $.cookie('the_cookie', null);
17205 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
17206 *       used when the cookie was set.
17207 *
17208 * @param String name The name of the cookie.
17209 * @param String value The value of the cookie.
17210 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
17211 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
17212 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
17213 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
17214 *                             when the the browser exits.
17215 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
17216 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
17217 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
17218 *                        require a secure protocol (like HTTPS).
17219 * @type undefined
17220 *
17221 * @name $.cookie
17222 * @cat Plugins/Cookie
17223 * @author Klaus Hartl/[email protected]
17224 */
17225
17226/**
17227 * Get the value of a cookie with the given name.
17228 *
17229 * @example $.cookie('the_cookie');
17230 * @desc Get the value of a cookie.
17231 *
17232 * @param String name The name of the cookie.
17233 * @return The value of the cookie.
17234 * @type String
17235 *
17236 * @name $.cookie
17237 * @cat Plugins/Cookie
17238 * @author Klaus Hartl/[email protected]
17239 */
17240jQuery.cookie = function(name, value, options) {
17241    if (typeof value != 'undefined') { // name and value given, set cookie
17242        options = options || {};
17243        if (value === null) {
17244            value = '';
17245            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
17246            options.expires = -1;
17247        }
17248        var expires = '';
17249        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
17250            var date;
17251            if (typeof options.expires == 'number') {
17252                date = new Date();
17253                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
17254            } else {
17255                date = options.expires;
17256            }
17257            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
17258        }
17259        // NOTE Needed to parenthesize options.path and options.domain
17260        // in the following expressions, otherwise they evaluate to undefined
17261        // in the packed version for some reason...
17262        var path = options.path ? '; path=' + (options.path) : '';
17263        var domain = options.domain ? '; domain=' + (options.domain) : '';
17264        var secure = options.secure ? '; secure' : '';
17265        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
17266    } else { // only name given, get cookie
17267        var cookieValue = null;
17268        if (document.cookie && document.cookie != '') {
17269            var cookies = document.cookie.split(';');
17270            for (var i = 0; i < cookies.length; i++) {
17271                var cookie = jQuery.trim(cookies[i]);
17272                // Does this cookie string begin with the name we want?
17273                if (cookie.substring(0, name.length + 1) == (name + '=')) {
17274                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
17275                    break;
17276                }
17277            }
17278        }
17279        return cookieValue;
17280    }
17281};
17282/* Copyright (c) 2007 Paul Bakaus ([email protected]) and Brandon Aaron ([email protected] || http://brandonaaron.net)
17283 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
17284 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
17285 *
17286 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
17287 * $Rev: 4259 $
17288 *
17289 * Version: 1.2
17290 *
17291 * Requires: jQuery 1.2+
17292 *
17293 */
17294
17295(function($){
17296
17297$.dimensions = {
17298    version: '1.2'
17299};
17300
17301// Create innerHeight, innerWidth, outerHeight and outerWidth methods
17302$.each( [ 'Height', 'Width' ], function(i, name){
17303    if (!$.fn[ 'inner' + name ]) {
17304        // innerHeight and innerWidth
17305        $.fn[ 'inner' + name ] = function() {
17306            if (!this[0]) return;
17307
17308            var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
17309                borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
17310
17311            return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
17312        };
17313
17314        // outerHeight and outerWidth
17315        $.fn[ 'outer' + name ] = function(options) {
17316            if (!this[0]) return;
17317
17318            var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
17319                borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right
17320
17321            options = $.extend({ margin: false }, options || {});
17322
17323            var val = this.is(':visible') ?
17324                this[0]['offset' + name] :
17325                num( this, name.toLowerCase() )
17326                + num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
17327                + num(this, 'padding' + torl) + num(this, 'padding' + borr);
17328
17329            return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
17330        };
17331    }
17332});
17333
17334// Create scrollLeft and scrollTop methods
17335$.each( ['Left', 'Top'], function(i, name) {
17336    if (!$.fn[ 'scroll' + name ]) {
17337        $.fn[ 'scroll' + name ] = function(val) {
17338            if (!this[0]) return;
17339
17340            return val != undefined ?
17341
17342                // Set the scroll offset
17343                this.each(function() {
17344                    this == window || this == document ?
17345                        window.scrollTo(
17346                            name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
17347                            name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
17348                        ) :
17349                        this[ 'scroll' + name ] = val;
17350                }) :
17351
17352                // Return the scroll offset
17353                this[0] == window || this[0] == document ?
17354                    self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
17355                    $.boxModel && document.documentElement[ 'scroll' + name ] ||
17356                    document.body[ 'scroll' + name ] :
17357                    this[0][ 'scroll' + name ];
17358        };
17359    }
17360});
17361
17362if (!$.fn.position) {
17363    $.fn.extend({
17364        position: function() {
17365            var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;
17366
17367            if (elem) {
17368                // Get *real* offsetParent
17369                offsetParent = this.offsetParent();
17370
17371                // Get correct offsets
17372                offset       = this.offset();
17373                parentOffset = offsetParent.offset();
17374
17375                // Subtract element margins
17376                offset.top  -= num(elem, 'marginTop');
17377                offset.left -= num(elem, 'marginLeft');
17378
17379                // Add offsetParent borders
17380                parentOffset.top  += num(offsetParent, 'borderTopWidth');
17381                parentOffset.left += num(offsetParent, 'borderLeftWidth');
17382
17383                // Subtract the two offsets
17384                results = {
17385                    top:  offset.top  - parentOffset.top,
17386                    left: offset.left - parentOffset.left
17387                };
17388            }
17389            return results;
17390        }
17391    });
17392}
17393
17394if (!$.fn.offsetParent) {
17395    $.fn.extend({
17396        offsetParent: function () {
17397            var offsetParent = this[0].offsetParent;
17398            while (offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static'))
17399                offsetParent = offsetParent.offsetParent;
17400            return $(offsetParent);
17401        }
17402    });
17403}
17404
17405if (!$.fn.curCSS) {
17406    $.fn.extend({
17407        curCss : function (element, prop, val) {
17408            return $(element).css(prop, val);
17409        }
17410    });
17411}
17412
17413function num(el, prop) {
17414    return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
17415};
17416
17417})(jQuery);
17418
17419/*
17420 * jQuery Easing v1.1.1 - http://gsgd.co.uk/sandbox/jquery.easing.php
17421 *
17422 * Uses the built in easing capabilities added in jQuery 1.1
17423 * to offer multiple easing options
17424 *
17425 * Copyright (c) 2007 George Smith
17426 * Licensed under the MIT License:
17427 *   http://www.opensource.org/licenses/mit-license.php
17428 */
17429
17430jQuery.extend(jQuery.easing, {
17431    easein: function(x, t, b, c, d) {
17432    return c*(t/=d)*t + b; // in
17433    },
17434    easeinout: function(x, t, b, c, d) {
17435    if (t < d/2) return 2*c*t*t/(d*d) + b;
17436    var ts = t - d/2;
17437    return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;
17438    },
17439    easeout: function(x, t, b, c, d) {
17440    return -c*t*t/(d*d) + 2*c*t/d + b;
17441    },
17442    expoin: function(x, t, b, c, d) {
17443    var flip = 1;
17444    if (c < 0) {
17445    flip *= -1;
17446    c *= -1;
17447    }
17448    return flip * (Math.exp(Math.log(c)/d * t)) + b;
17449    },
17450    expoout: function(x, t, b, c, d) {
17451    var flip = 1;
17452    if (c < 0) {
17453    flip *= -1;
17454    c *= -1;
17455    }
17456    return flip * (-Math.exp(-Math.log(c)/d * (t-d)) + c + 1) + b;
17457    },
17458    expoinout: function(x, t, b, c, d) {
17459    var flip = 1;
17460    if (c < 0) {
17461    flip *= -1;
17462    c *= -1;
17463    }
17464    if (t < d/2) return flip * (Math.exp(Math.log(c/2)/(d/2) * t)) + b;
17465    return flip * (-Math.exp(-2*Math.log(c/2)/d * (t-d)) + c + 1) + b;
17466    },
17467    bouncein: function(x, t, b, c, d) {
17468    return c - jQuery.easing['bounceout'](x, d-t, 0, c, d) + b;
17469    },
17470    bounceout: function(x, t, b, c, d) {
17471    if ((t/=d) < (1/2.75)) {
17472    return c*(7.5625*t*t) + b;
17473    } else if (t < (2/2.75)) {
17474    return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
17475    } else if (t < (2.5/2.75)) {
17476    return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
17477    } else {
17478    return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
17479    }
17480    },
17481    bounceinout: function(x, t, b, c, d) {
17482    if (t < d/2) return jQuery.easing['bouncein'] (x, t*2, 0, c, d) * .5 + b;
17483    return jQuery.easing['bounceout'] (x, t*2-d,0, c, d) * .5 + c*.5 + b;
17484    },
17485    elasin: function(x, t, b, c, d) {
17486    var s=1.70158;var p=0;var a=c;
17487    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
17488    if (a < Math.abs(c)) { a=c; var s=p/4; }
17489    else var s = p/(2*Math.PI) * Math.asin (c/a);
17490    return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
17491    },
17492    elasout: function(x, t, b, c, d) {
17493    var s=1.70158;var p=0;var a=c;
17494    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
17495    if (a < Math.abs(c)) { a=c; var s=p/4; }
17496    else var s = p/(2*Math.PI) * Math.asin (c/a);
17497    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
17498    },
17499    elasinout: function(x, t, b, c, d) {
17500    var s=1.70158;var p=0;var a=c;
17501    if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
17502    if (a < Math.abs(c)) { a=c; var s=p/4; }
17503    else var s = p/(2*Math.PI) * Math.asin (c/a);
17504    if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
17505    return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
17506    },
17507    backin: function(x, t, b, c, d) {
17508    var s=1.70158;
17509    return c*(t/=d)*t*((s+1)*t - s) + b;
17510    },
17511    backout: function(x, t, b, c, d) {
17512    var s=1.70158;
17513    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
17514    },
17515    backinout: function(x, t, b, c, d) {
17516    var s=1.70158;
17517    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
17518    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
17519    }
17520});
17521/*
17522 * Metadata - jQuery plugin for parsing metadata from elements
17523 *
17524 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
17525 *
17526 * Dual licensed under the MIT and GPL licenses:
17527 *   http://www.opensource.org/licenses/mit-license.php
17528 *   http://www.gnu.org/licenses/gpl.html
17529 *
17530 * Revision: $Id$
17531 *
17532 */
17533
17534/**
17535 * Sets the type of metadata to use. Metadata is encoded in JSON, and each property
17536 * in the JSON will become a property of the element itself.
17537 *
17538 * There are three supported types of metadata storage:
17539 *
17540 *   attr:  Inside an attribute. The name parameter indicates *which* attribute.
17541 *
17542 *   class: Inside the class attribute, wrapped in curly braces: { }
17543 *
17544 *   elem:  Inside a child element (e.g. a script tag). The
17545 *          name parameter indicates *which* element.
17546 *
17547 * The metadata for an element is loaded the first time the element is accessed via jQuery.
17548 *
17549 * As a result, you can define the metadata type, use $(expr) to load the metadata into the elements
17550 * matched by expr, then redefine the metadata type and run another $(expr) for other elements.
17551 *
17552 * @name $.metadata.setType
17553 *
17554 * @example <p id="one" class="some_class {item_id: 1, item_label: 'Label'}">This is a p</p>
17555 * @before $.metadata.setType("class")
17556 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
17557 * @desc Reads metadata from the class attribute
17558 *
17559 * @example <p id="one" class="some_class" data="{item_id: 1, item_label: 'Label'}">This is a p</p>
17560 * @before $.metadata.setType("attr", "data")
17561 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
17562 * @desc Reads metadata from a "data" attribute
17563 *
17564 * @example <p id="one" class="some_class"><script>{item_id: 1, item_label: 'Label'}</script>This is a p</p>
17565 * @before $.metadata.setType("elem", "script")
17566 * @after $("#one").metadata().item_id == 1; $("#one").metadata().item_label == "Label"
17567 * @desc Reads metadata from a nested script element
17568 *
17569 * @param String type The encoding type
17570 * @param String name The name of the attribute to be used to get metadata (optional)
17571 * @cat Plugins/Metadata
17572 * @descr Sets the type of encoding to be used when loading metadata for the first time
17573 * @type undefined
17574 * @see metadata()
17575 */
17576
17577(function($) {
17578
17579$.extend({
17580    metadata : {
17581    defaults : {
17582    type: 'class',
17583    name: 'metadata',
17584    cre: /({.*})/,
17585    single: 'metadata'
17586    },
17587    setType: function( type, name ){
17588    this.defaults.type = type;
17589    this.defaults.name = name;
17590    },
17591    get: function( elem, opts ){
17592    var settings = $.extend({},this.defaults,opts);
17593    // check for empty string in single property
17594    if ( !settings.single.length ) settings.single = 'metadata';
17595
17596    var data = $.data(elem, settings.single);
17597    // returned cached data if it already exists
17598    if ( data ) return data;
17599
17600    data = "{}";
17601
17602    if ( settings.type == "class" ) {
17603    var m = settings.cre.exec( elem.className );
17604    if ( m )
17605    data = m[1];
17606    } else if ( settings.type == "elem" ) {
17607    if( !elem.getElementsByTagName )
17608    return undefined;
17609    var e = elem.getElementsByTagName(settings.name);
17610    if ( e.length )
17611    data = $.trim(e[0].innerHTML);
17612    } else if ( elem.getAttribute != undefined ) {
17613    var attr = elem.getAttribute( settings.name );
17614    if ( attr )
17615    data = attr;
17616    }
17617
17618    if ( data.indexOf( '{' ) <0 )
17619    data = "{" + data + "}";
17620
17621    data = eval("(" + data + ")");
17622
17623    $.data( elem, settings.single, data );
17624    return data;
17625    }
17626    }
17627});
17628
17629/**
17630 * Returns the metadata object for the first member of the jQuery object.
17631 *
17632 * @name metadata
17633 * @descr Returns element's metadata object
17634 * @param Object opts An object contianing settings to override the defaults
17635 * @type jQuery
17636 * @cat Plugins/Metadata
17637 */
17638$.fn.metadata = function( opts ){
17639    return $.metadata.get( this[0], opts );
17640};
17641
17642})(jQuery);
17643
17644/**
17645 * FwValidator
17646 *
17647 * @package     jquery
17648 * @subpackage  validator
17649 */
17650
17651var FwValidator = {
17652
17653    /**
17654     * 디버그 모드
17655     */
17656    DEBUG_MODE : false,
17657
17658    /**
17659     * 결과 코드
17660     */
17661    CODE_SUCCESS    : true,
17662    CODE_FAIL       : false,
17663
17664    /**
17665     * 어트리뷰트 명
17666     */
17667    ATTR_FILTER     : 'fw-filter',
17668    ATTR_MSG        : 'fw-msg',
17669    ATTR_LABEL      : 'fw-label',
17670    ATTR_FIREON     : 'fw-fireon',
17671    ATTR_ALONE      : 'fw-alone',
17672
17673    /**
17674     * 응답객체들
17675     */
17676    responses       : {},
17677
17678    /**
17679     * 엘리먼트별 필수 입력 에러 메세지
17680     */
17681    requireMsgs     : {},
17682
17683    /**
17684     * 엘리먼트의 특정 필터별 에러 메세지
17685     */
17686    elmFilterMsgs   : {},
17687
17688    /**
17689     * jQuery 별칭 정의
17690     * EC$ 가 기본으로 로드되지 않는 환경에서 사용시에 대한 처리
17691     */
17692    jQuery          : window.EC$ || window.$,
17693
17694    /**
17695     * Validator 기본 이벤트 등록
17696     */
17697    bind : function(formId, expand) {
17698
17699        var self = this;
17700        var formInfo = this.Helper.getFormInfo(formId);
17701
17702        if (formInfo === false) {
17703            alert('The form does not exist - bind');
17704            return false;
17705        }
17706
17707        var elmForm = formInfo.instance;
17708
17709        var Response = this._response(formId);
17710
17711        this._fireon(formId, elmForm, Response);
17712        this._submit(formId, elmForm, expand);
17713
17714        return true;
17715
17716    },
17717
17718    /**
17719     * Validator 검사 진행
17720     *
17721     * @param string formId
17722     * @return object | false
17723     */
17724    inspection : function(formId, expand) {
17725
17726        expand = (expand === true) ? true : false;
17727
17728        var self = this;
17729        var Response = this._response(formId);
17730
17731        if (Response === false) {
17732            alert('The form does not exist - inspection');
17733            return false;
17734        }
17735
17736        if (Response.elmsTarget.length == 0) {
17737            return this.Helper.getResult(Response, this.CODE_SUCCESS);
17738        }
17739
17740        Response.elmsTarget.each(function(){
17741            self._execute(Response, this);
17742        });
17743
17744        if (Response.elmsCurrErrorField.length > 0) {
17745
17746            if (expand !== true) {
17747                this.Handler.errorHandler(Response.elmsCurrErrorField[0]);
17748            } else {
17749                this.Handler.errorHandlerByExapnd(Response);
17750            }
17751
17752            return Response.elmsCurrErrorField[0];
17753
17754        }
17755
17756        return this.Helper.getResult(Response, this.CODE_SUCCESS);
17757
17758    },
17759
17760    /**
17761     * submit 이벤트 등록
17762     *
17763     * @param string    formId
17764     * @param object    elmForm
17765     */
17766    _submit : function(formId, elmForm, expand) {
17767        var self = this;
17768        var handler = function(event){
17769            var result = false;
17770
17771            // 중복 요청 방지로 추가
17772            event.stopImmediatePropagation();
17773
17774            try{
17775                result = self.inspection(formId, expand);
17776            }catch(e){
17777                alert(e);
17778                return false;
17779            }
17780
17781            if(!result || result.passed === self.CODE_FAIL){
17782                return false;
17783            };
17784
17785            var callback = self._beforeSubmit(elmForm);
17786
17787            return callback !== false ? true : false;
17788        };
17789
17790        elmForm.unbind('submit');
17791        elmForm.bind('submit', handler);
17792
17793        // window.$에서 submit() 처리시 오동작으로 인해 추가 
17794        if (this.jQuery !== window.$) {
17795            $(elmForm).unbind('submit');
17796            $(elmForm).bind('submit', handler);
17797        }
17798    },
17799
17800    /**
17801     * fireon 이벤트 등록
17802     *
17803     * @param string                formId
17804     * @param object                elmForm
17805     * @param FwValidator.Response  Response
17806     */
17807    _fireon : function(formId, elmForm, Response) {
17808        var $ = this.jQuery;
17809        var self = this;
17810        var formInfo = this.Helper.getFormInfo(formId);
17811
17812        $(formInfo.selector).find('*['+this.ATTR_FILTER+']['+this.ATTR_FIREON+']').each(function(){
17813            var elm = $(this);
17814            var evtName = self.Helper.trim(elm.attr(self.ATTR_FIREON));
17815            var elmMsg = '';
17816
17817            elm.unbind(evtName);
17818            elm.bind(evtName, function(){
17819                var result = self._execute(Response, this);
17820                var targetField = Response.elmCurrField;
17821
17822                //에러 메세지가 출력되 있다면 일단 지우고 체킹을 시작한다.
17823                if(typeof elmMsg == 'object'){
17824                    elmMsg.remove();
17825                }
17826
17827                if(result > -1){
17828                    elmMsg = self.Handler.errorHandlerByFireon(Response.elmsCurrErrorField[result]);
17829                }else{
17830                    self.Handler.successHandlerByFireon(self.Helper.getResult(Response, self.CODE_FAIL));
17831                }
17832            });
17833        });
17834    },
17835
17836    /**
17837     * Response 객체 생성
17838     *
17839     * @param string formId
17840     * @return FwValidator.Response | false
17841     */
17842    _response : function(formId) {
17843        var $ = this.jQuery;
17844        var formInfo = this.Helper.getFormInfo(formId);
17845
17846        if (formInfo === false) {
17847            alert('The form does not exist - find');
17848            return false;
17849        }
17850
17851        var elmForm = formInfo.instance;
17852        var elmsTarget = $(formInfo.selector).find('*[' + this.ATTR_FILTER + ']');
17853
17854        this.responses[formId] = new FwValidator.Response();
17855
17856        this.responses[formId].formId = formId;
17857        this.responses[formId].elmForm = elmForm;
17858        this.responses[formId].elmsTarget = elmsTarget;
17859
17860        return this.responses[formId];
17861
17862    },
17863
17864    /**
17865     * BeforeExecute 콜백함수 실행
17866     *
17867     * @param FwValidator.Response Response
17868     */
17869    _beforeExecute : function(Response) {
17870
17871        var count = this.Handler.beforeExecute.length;
17872
17873        if (count == 0) return;
17874
17875        for (var i in this.Handler.beforeExecute) {
17876            this.Handler.beforeExecute[i].call(this, Response);
17877        }
17878
17879    },
17880
17881    /**
17882     * BeforeSubmit 콜백함수 실행
17883     *
17884     * @param object elmForm (jquery 셀렉터 문법으로 찾아낸 폼 객체)
17885     */
17886    _beforeSubmit : function(elmForm) {
17887
17888        if(typeof this.Handler.beforeSubmit != 'function') return true;
17889
17890        return this.Handler.beforeSubmit.call(this, elmForm);
17891
17892    },
17893
17894    /**
17895     * 엘리먼트별 유효성 검사 실행
17896     *
17897     * @param FwValidator.Response  Response
17898     * @param htmlElement           elmTarget
17899     * @return int(에러가 발생한 elmCurrField 의 인덱스값) | -1(성공)
17900     */
17901    _execute : function(Response, elmTarget) {
17902        var $ = this.jQuery;
17903        var RESULT_SUCCESS = -1;
17904
17905        Response.elmCurrField = $(elmTarget);
17906        Response.elmCurrLabel = Response.elmCurrField.attr(this.ATTR_LABEL);
17907        Response.elmCurrFieldType = this.Helper.getElmType(Response.elmCurrField);
17908        Response.elmCurrFieldDisabled = elmTarget.disabled;
17909        Response.elmCurrValue = this.Helper.getValue(Response.formId, Response.elmCurrField);
17910        Response.elmCurrErrorMsg = Response.elmCurrField.attr(this.ATTR_MSG);
17911
17912        //_beforeExecute 콜백함수 실행
17913        this._beforeExecute(Response);
17914
17915        //필드가 disabled 일 경우는 체크하지 않음.
17916        if (Response.elmCurrFieldDisabled === true) {
17917            return RESULT_SUCCESS;
17918        }
17919
17920        var filter = this.Helper.trim( Response.elmCurrField.attr(this.ATTR_FILTER) );
17921
17922        if (filter == '') {
17923            return RESULT_SUCCESS;
17924        }
17925
17926        //is로 시작하지 않는것들은 정규표현식으로 간주
17927        if (/^is/i.test(filter)) {
17928            var filters = filter.split('&');
17929            var count = filters.length;
17930
17931            //필수항목이 아닌경우 빈값이 들어왔을경우는 유효성 체크를 통과시킴
17932
17933            if ((/isFill/i.test(filter) === false) && !Response.elmCurrValue) {
17934                return RESULT_SUCCESS;
17935            }
17936
17937            for (var i=0; i < count; ++i) {
17938                var filter = filters[i];
17939                var param = '';
17940                var filtersInfo = this.Helper.getFilterInfo(filter);
17941
17942                filter = Response.elmCurrFilter = filtersInfo.id;
17943                param = filtersInfo.param;
17944
17945                //필수 입력 필터의 경우 항목관리에서 사용자가 메세지를 직접 지정하는 부분이 있어 이렇게 처리
17946                if (filter == 'isFill') {
17947                    Response.elmCurrValue = this.Helper.trim(Response.elmCurrValue);
17948                    Response.elmCurrErrorMsg = this.requireMsgs[elmTarget.id] ? this.requireMsgs[elmTarget.id] : this.msgs['isFill'];
17949                } else {
17950                    var msg = Response.elmCurrField.attr(this.ATTR_MSG);
17951
17952                    if (msg) {
17953                        Response.elmCurrErrorMsg = msg;
17954                    } else if (this.Helper.getElmFilterMsg(elmTarget.id, filter)) {
17955                        Response.elmCurrErrorMsg = this.Helper.getElmFilterMsg(elmTarget.id, filter);
17956                    } else {
17957                        Response.elmCurrErrorMsg = this.msgs[filter];
17958                    }
17959
17960                }
17961
17962                //존재하지 않는 필터인 경우 에러코드 반환
17963                if(this.Filter[filter] === undefined){
17964                    Response.elmCurrErrorMsg = this.msgs['notMethod'];
17965                    var result = this.Helper.getResult(Response, this.CODE_FAIL);
17966
17967                    Response.elmsCurrErrorField.push(result);
17968                    return Response.elmsCurrErrorField.length - 1;
17969                }
17970
17971                //필터 실행
17972                var result = this.Filter[filter](Response, param);
17973
17974                if (result == undefined || result.passed === this.CODE_FAIL) {
17975                    Response.elmsCurrErrorField.push(result);
17976
17977                    //Debug를 위해 넣어둔 코드(확장형 필터를 잘못 등록해서 return값이 없는 경우를 체크하기 위함)
17978                    if (result == undefined) {
17979                        alert('Extension Filter Return error - ' + filter);
17980                    }
17981
17982                    return Response.elmsCurrErrorField.length - 1;
17983                }
17984            }
17985        } else {
17986            var msg = Response.elmCurrErrorMsg;
17987            Response.elmCurrErrorMsg = msg ? msg : this.msgs['isRegex'];
17988            var result = this.Filter.isRegex(Response, filter);
17989
17990            if(result.passed === this.CODE_FAIL){
17991                Response.elmsCurrErrorField.push(result);
17992
17993                return Response.elmsCurrErrorField.length - 1;
17994            }
17995        }
17996
17997        return RESULT_SUCCESS;
17998    }
17999};
18000
18001/**
18002 * FwValidator.Response
18003 *
18004 * @package     jquery
18005 * @subpackage  validator
18006 */
18007
18008FwValidator.Response = function() {
18009
18010    this.formId = null;
18011    this.elmForm = null;
18012    this.elmsTarget = null;
18013    this.elmsCurrErrorField = [];
18014
18015    this.elmCurrField = null;
18016    this.elmCurrFieldType = null;
18017    this.elmCurrFieldDisabled = null;
18018    this.elmCurrLabel = null;
18019    this.elmCurrValue = null;
18020    this.elmCurrFilter = null;
18021    this.elmCurrErrorMsg = null;
18022
18023    this.requireMsgs = {};
18024
18025};
18026
18027/**
18028 * FwValidator.Helper
18029 *
18030 * @package     jquery
18031 * @subpackage  validator
18032 */
18033
18034FwValidator.Helper = {
18035
18036    parent : FwValidator,
18037
18038    /**
18039     * 메세지 엘리먼트의 아이디 prefix
18040     */
18041    msgIdPrefix : 'msg_',
18042
18043    /**
18044     * 메세지 엘리먼트의 클래스 명 prefix
18045     */
18046    msgClassNamePrefix : 'msg_error_mark_',
18047
18048    /**
18049     * 결과 반환
18050     */
18051    getResult : function(Response, code, param) {
18052
18053        //특수 파라미터 정보(특정 필터에서만 사용함)
18054        param = param != undefined ? param : {};
18055
18056        var msg = '';
18057
18058        if (code === this.parent.CODE_FAIL) {
18059
18060            try {
18061                msg = Response.elmCurrErrorMsg.replace(/\{label\}/i, Response.elmCurrLabel);
18062            } catch(e) {
18063                msg = 'No Message';
18064            }
18065
18066        } else {
18067
18068            msg = 'success';
18069
18070        }
18071
18072        var result = {};
18073        result.passed = code;
18074        result.formid = Response.formId;
18075        result.msg = msg;
18076        result.param = param;
18077
18078        try {
18079        result.element = Response.elmCurrField;
18080        result.elmid = Response.elmCurrField.attr('id');
18081        result.filter = Response.elmCurrFilter;
18082        } catch(e) {}
18083
18084        return result;
18085
18086    },
18087
18088    /**
18089     * 필터 정보 반환(필터이름, 파라미터)
18090     */
18091    getFilterInfo : function(filter) {
18092        var matches = filter.match(/(is[a-z]*)((?:\[.*?\])*)/i);
18093
18094        return {
18095            id : matches[1],
18096            param : this.getFilterParams(matches[2])
18097        };
18098    },
18099
18100    /**
18101     * 필터의 파라미터 스트링 파싱
18102     * isFill[a=1][b=1][c=1] 이런식의 멀티 파라미터가 지정되어 있는 경우는 배열로 반환함
18103     * isFill[a=1] 단일 파라미터는 파라미터로 지정된 스트링값만 반환함
18104     */
18105    getFilterParams : function(paramStr) {
18106        if (paramStr == undefined || paramStr == null || paramStr == '') {
18107            return '';
18108        }
18109
18110        var matches = paramStr.match(/\[.*?\]/ig);
18111
18112        if (matches == null) {
18113            return '';
18114        }
18115
18116        var count = matches.length;
18117        var result = [];
18118
18119        for (var i=0; i < count; i++) {
18120            var p = matches[i].match(/\[(.*?)\]/);
18121            result.push(p[1]);
18122        }
18123
18124        if (result.length == 1) {
18125            return result[0];
18126        }
18127
18128        return result;
18129    },
18130
18131    /**
18132     * 필드 타입 반환(select, checkbox, radio, textbox)
18133     */
18134    getElmType : function(elmField) {
18135        var $ = this.parent.jQuery;
18136
18137        elmField = $(elmField);
18138
18139        var elTag = elmField[0].tagName;
18140        var result = null;
18141
18142        switch (elTag) {
18143            case 'SELECT' :
18144                result = 'select';
18145                break;
18146
18147            case 'INPUT' :
18148                if ($.fn.prop) {
18149                    var _type = elmField.prop('type').toLowerCase();
18150                } else {
18151                    var _type = elmField.attr('type').toLowerCase();
18152                }
18153                if(_type == 'checkbox') result = 'checkbox';
18154                else if(_type =='radio') result = 'radio';
18155                else result = 'textbox';
18156
18157                break;
18158
18159            case 'TEXTAREA' :
18160                result = 'textbox';
18161                break;
18162
18163            default :
18164                result = 'textbox';
18165                break;
18166        }
18167
18168        return result;
18169    },
18170
18171    /**
18172     * 필드 값 반환
18173     */
18174    getValue : function(formId, elmField) {
18175        var $ = this.parent.jQuery;
18176        var result = '';
18177        var elmName = elmField.attr('name');
18178        var fieldType = this.getElmType(elmField);
18179
18180        //checkbox 나 radio 박스는 value값을 반환하지 않음
18181        if (fieldType == 'checkbox' || fieldType == 'radio') {
18182            if(elmField.get(0).checked === true){
18183                result = elmField.val();
18184            }
18185            return result;
18186        }
18187
18188        //alonefilter 속성이 Y 로 되어 있다면 해당 엘리먼트의 값만 반환함
18189        var aloneFilter = elmField.attr(this.parent.ATTR_ALONE);
18190        if(aloneFilter == 'Y' || aloneFilter == 'y'){
18191            return elmField.val();
18192        }
18193
18194        //name이 배열형태로 되어 있다면 값을 모두 합쳐서 반환
18195        if( /\[.*?\]/.test(elmName) ){
18196            var formInfo = this.getFormInfo(formId);
18197
18198            var groupElms = $(formInfo.selector +' [name="'+elmName+'"]');
18199            groupElms.each(function(i){
18200                var elm = $(this);
18201                result += elm.val();
18202            });
18203        }else{
18204            result = elmField.val();
18205        }
18206
18207        return result;
18208    },
18209
18210    /**
18211     * 에러메세지 엘리먼트 생성
18212     */
18213    createMsg : function(elm, msg, formId) {
18214        var $ = this.parent.jQuery;
18215        var elmMsg = document.createElement('span');
18216
18217        elmMsg.id = this.msgIdPrefix + elm.attr('id');
18218        elmMsg.className = this.msgClassNamePrefix + formId;
18219        elmMsg.innerHTML = msg;
18220
18221        return $(elmMsg);
18222    },
18223
18224    /**
18225     * 에러메세지 엘리먼트 제거
18226     */
18227    removeMsg : function(elm) {
18228        var $ = this.parent.jQuery;
18229        var id = this.msgIdPrefix + elm.attr('id');
18230        var elmErr = $('#'+id);
18231
18232        if (elmErr) elmErr.remove();
18233    },
18234
18235    /**
18236     * 에러메세지 엘리먼트 모두 제거
18237     */
18238    removeAllMsg : function(formId) {
18239        var $ = this.parent.jQuery;
18240        var className = this.msgClassNamePrefix + formId;
18241
18242        $('.' + className).remove();
18243    },
18244
18245    /**
18246     * 문자열의 Byte 수 반환
18247     */
18248    getByte : function(str) {
18249        var encode = encodeURIComponent(str);
18250        var totalBytes = 0;
18251        var chr;
18252        var bytes;
18253        var code;
18254
18255        for(var i = 0; i < encode.length; i++)
18256        {
18257            chr = encode.charAt(i);
18258            if(chr != "%") totalBytes++;
18259            else
18260            {
18261                code = parseInt(encode.substr(i+1,2),16);
18262                if(!(code & 0x80)) totalBytes++;
18263                else
18264                {
18265                    if((code & 0xE0) == 0xC0) bytes = 2;
18266                    else if((code & 0xF0) == 0xE0) bytes = 3;
18267                    else if((code & 0xF8) == 0xF0) bytes = 4;
18268                    else return -1;
18269
18270                    i += 3 * (bytes - 1);
18271
18272                    totalBytes += 2;
18273                }
18274                i += 2;
18275            }
18276        }
18277
18278        return totalBytes;
18279    },
18280
18281    /**
18282     * 지정한 엘리먼트의 필터 메세지가 존재하는가
18283     *
18284     * @param elmId (엘리먼트 아이디)
18285     * @param filter (필터명)
18286     * @return string | false
18287     */
18288    getElmFilterMsg : function(elmId, filter) {
18289        if (this.parent.elmFilterMsgs[elmId] == undefined) return false;
18290        if (this.parent.elmFilterMsgs[elmId][filter] == undefined) return false;
18291
18292        return this.parent.elmFilterMsgs[elmId][filter];
18293    },
18294
18295    /**
18296     * 폼 정보 반환
18297     *
18298     * @param formId (폼 아이디 혹은 네임)
18299     * @return array(
18300     *   'selector' => 셀렉터 문자,
18301     *   'instance' => 셀렉터 문법으로 검색해낸 폼 객체
18302     * ) | false
18303     */
18304    getFormInfo : function(formId) {
18305        var $ = this.parent.jQuery;
18306        var result = {};
18307        var selector = '#' + formId;
18308        var instance = $(selector);
18309
18310        if (instance.length > 0) {
18311            result.selector = selector;
18312            result.instance = instance;
18313
18314            return result;
18315        }
18316
18317        selector = 'form[name="' + formId + '"]';
18318        instance = $(selector);
18319
18320        if (instance.length > 0) {
18321            result.selector = selector;
18322            result.instance = instance;
18323
18324            return result;
18325        }
18326
18327        return false;
18328    },
18329
18330    /**
18331     * 숫자형태의 문자열로 바꿔줌
18332     * 123,123,123
18333     * 123123,123
18334     * 123%
18335     * 123  %
18336     * 123.4
18337     * -123
18338     * ,123
18339     *
18340     * @param value
18341     * @return float
18342     */
18343    getNumberConv : function(value) {
18344        if (!value || value == undefined || value == null) return '';
18345
18346        value = value + "";
18347
18348        value = value.replace(/,/g, '');
18349        value = value.replace(/%/g, '');
18350        value = value.replace(/[\s]/g, '');
18351
18352        if (this.parent.Verify.isFloat(value) === false) return '';
18353
18354        return parseFloat(value);
18355    },
18356
18357    /**
18358     * 문자열 앞 뒤 공백 제거
18359     *
18360     * @param string text
18361     * @return string
18362     */
18363    trim: function(text) {
18364        var trim = String.prototype.trim;
18365
18366        return text == null ? "" : trim.call(text);
18367    }
18368};
18369
18370/**
18371 * FwValidator.Handler
18372 *
18373 * @package     jquery
18374 * @subpackage  validator
18375 */
18376
18377FwValidator.Handler = {
18378
18379    parent : FwValidator,
18380
18381    /**
18382     * 사용자 정의형 에러핸들러(엘리먼트 아이디별로 저장됨)
18383     */
18384    customErrorHandler : {},
18385
18386    /**
18387     * 사용자 정의형 에러핸들러(필터별로 저장됨)
18388     */
18389    customErrorHandlerByFilter : {},
18390
18391    /**
18392     * 사용자 정의형 성공핸들러(엘리먼트 아이디별로 저장됨)
18393     */
18394    customSuccessHandler : {},
18395
18396    /**
18397     * 사용자 정의형 성공핸들러(필터별로 저장됨)
18398     */
18399    customSuccessHandlerByFilter : {},
18400
18401    /**
18402     * FwValidator._execute에 의해 검사되기 전 실행되는 콜백함수
18403     */
18404    beforeExecute : [],
18405
18406    /**
18407     * FwValidator._submit에서 바인딩한 onsubmit 이벤트 발생후 실행되는 콜백함수
18408     * {폼아이디 : 콜백함수, ...}
18409     */
18410    beforeSubmit : {},
18411
18412    /**
18413     * 기본 메세지 전체를 오버라이딩
18414     */
18415    overrideMsgs : function(msgs) {
18416        if (typeof msgs != 'object') return;
18417
18418        this.parent.msgs = msgs;
18419    },
18420
18421    /**
18422     * 필드에 따른 필수 입력 에러메세지 설정
18423     */
18424    setRequireErrorMsg : function(field, msg) {
18425        this.parent.requireMsgs[field] = msg;
18426    },
18427
18428    /**
18429     * 필터 타입에 따른 에러메세지 설정
18430     */
18431    setFilterErrorMsg : function(filter, msg) {
18432        this.parent.msgs[filter] = msg;
18433    },
18434
18435    /**
18436     * 엘리먼트의 특정 필터에만 에러메세지를 설정
18437     */
18438    setFilterErrorMsgByElement : function(elmId, filter, msg) {
18439        if (this.parent.elmFilterMsgs[elmId] == undefined) {
18440            this.parent.elmFilterMsgs[elmId] = {};
18441        }
18442
18443        this.parent.elmFilterMsgs[elmId][filter] = msg;
18444    },
18445
18446    /**
18447     * 엘리먼트 아이디별 사용자정의형 에러핸들러 등록
18448     */
18449    setCustomErrorHandler : function(elmId, func) {
18450        if (typeof func != 'function') return;
18451
18452        this.customErrorHandler[elmId] = func;
18453    },
18454
18455    /**
18456     * 필터 타입별 사용자정의형 에러핸들러 등록
18457     */
18458    setCustomErrorHandlerByFilter : function(filter, func) {
18459        if (typeof func != 'function') return;
18460
18461        this.customErrorHandlerByFilter[filter] = func;
18462    },
18463
18464    /**
18465     * 엘리먼트 아이디별 사용자정의형 성공핸들러 등록
18466     */
18467    setCustomSuccessHandler : function(elmId, func) {
18468        if (typeof func != 'function') return;
18469
18470        this.customSuccessHandler[elmId] = func;
18471    },
18472
18473    /**
18474     * 필터 타입별 사용자정의형 성공핸들러 등록
18475     */
18476    setCustomSuccessHandlerByFilter : function(filter, func) {
18477        if (typeof func != 'function') return;
18478
18479        this.customSuccessHandlerByFilter[filter] = func;
18480    },
18481
18482    /**
18483     * 확장형 필터 등록
18484     */
18485    setExtensionFilter : function(filter, func) {
18486        if (typeof func != 'function') return;
18487
18488        if (this.parent.Filter[filter] == undefined) {
18489            this.parent.Filter[filter] = func;
18490        }
18491    },
18492
18493    /**
18494     * 각 엘리먼트가 FwValidator._execute에 의해 검사되기 전 실행되는 콜백함수 등록
18495     */
18496    setBeforeExecute : function(func) {
18497        if (typeof func != 'function') return;
18498
18499        this.beforeExecute.push(func);
18500    },
18501
18502    /**
18503     * FwValidator._submit 에서 바인딩된 onsubmit 이벤트의 콜백함수 등록(유효성 검사가 성공하면 호출됨)
18504     */
18505    setBeforeSubmit : function(func) {
18506        if (typeof func != 'function') return;
18507
18508        this.beforeSubmit = func;
18509    },
18510
18511    /**
18512     * 에러핸들러 - 기본
18513     */
18514    errorHandler : function(resultData) {
18515        if (this._callCustomErrorHandler(resultData) === true) return;
18516
18517        alert(resultData.msg);
18518        resultData.element.focus();
18519    },
18520
18521    /**
18522     * 에러핸들러 - 전체 펼침 모드
18523     */
18524    errorHandlerByExapnd : function(Response) {
18525        var count = Response.elmsCurrErrorField.length;
18526
18527        //해당 폼에 출력된 에러메세지를 일단 모두 지운다.
18528        this.parent.Helper.removeAllMsg(Response.formId);
18529
18530        for (var i=0; i < count; ++i) {
18531            var resultData = Response.elmsCurrErrorField[i];
18532
18533            if (this._callCustomErrorHandler(resultData) === true) continue;
18534
18535            var elmMsg = this.parent.Helper.createMsg(resultData.element, resultData.msg, resultData.formid).css({'color':'#FF3300'});
18536            elmMsg.appendTo(resultData.element.parent());
18537        }
18538    },
18539
18540    /**
18541     * 에러핸들러 - fireon
18542     */
18543    errorHandlerByFireon : function(resultData) {
18544        if (this._callCustomErrorHandler(resultData) === true) return;
18545
18546        //해당 항목의 에러메세지 엘리먼트가 있다면 먼저 삭제한다.
18547        this.parent.Helper.removeMsg(resultData.element);
18548
18549        var elmMsg = this.parent.Helper.createMsg(resultData.element, resultData.msg, resultData.formid).css({'color':'#FF3300'});
18550        elmMsg.appendTo(resultData.element.parent());
18551
18552        return elmMsg;
18553    },
18554
18555    /**
18556     * 성공핸들러 - fireon
18557     */
18558    successHandlerByFireon : function(resultData) {
18559
18560        this._callCustomSuccessHandler(resultData);
18561
18562    },
18563
18564    /**
18565     * 정의형 에러 핸들러 호출
18566     *
18567     * @return boolean (정의형 에러핸들러를 호출했을 경우 true 반환)
18568     */
18569    _callCustomErrorHandler : function(resultData) {
18570        //resultData 가 정의되어 있지 않은 경우
18571        if (resultData == undefined) {
18572            alert('errorHandler - resultData is not found');
18573            return true;
18574        }
18575
18576        //해당 엘리먼트에 대한 Custom에러핸들러가 등록되어 있다면 탈출
18577        if (this.customErrorHandler[resultData.elmid] != undefined) {
18578            this.customErrorHandler[resultData.elmid].call(this.parent, resultData);
18579            return true;
18580        }
18581
18582        //해당 필터에 대한 Custom에러핸들러가 등록되어 있다면 탈출
18583        if (this.customErrorHandlerByFilter[resultData.filter] != undefined) {
18584            this.customErrorHandlerByFilter[resultData.filter].call(this.parent, resultData);
18585            return true;
18586        }
18587
18588        return false;
18589    },
18590
18591    /**
18592     * 정의형 성공 핸들러 호출 - 기본적으로 fireon 속성이 적용된 엘리먼트에만 적용됨.
18593     */
18594    _callCustomSuccessHandler : function(resultData) {
18595
18596        if (this.customSuccessHandler[resultData.elmid] != undefined) {
18597            this.customSuccessHandler[resultData.elmid].call(this.parent, resultData);
18598            return;
18599        }
18600
18601        if (this.customSuccessHandlerByFilter[resultData.filter] != undefined) {
18602            this.customSuccessHandlerByFilter[resultData.filter].call(this.parent, resultData);
18603            return;
18604        }
18605
18606    }
18607};
18608
18609/**
18610 * FwValidator.Verify
18611 *
18612 * @package     jquery
18613 * @subpackage  validator
18614 */
18615
18616FwValidator.Verify = {
18617
18618    parent : FwValidator,
18619
18620    isNumber : function(value, cond) {
18621        if (value == '') return true;
18622
18623        if (!cond) {
18624            cond = 1;
18625        }
18626
18627        cond = parseInt(cond);
18628
18629        pos = 1;
18630        nga = 2;
18631        minpos = 4;
18632        minnga = 8;
18633
18634        result = 0;
18635
18636        if ((/^[0-9]+$/).test(value) === true) {
18637            result = pos;
18638        } else if ((/^[-][0-9]+$/).test(value) === true) {
18639            result = nga;
18640        } else if ((/^[0-9]+[.][0-9]+$/).test(value) === true) {
18641            result = minpos;
18642        } else if ((/^[-][0-9]+[.][0-9]+$/).test(value) === true) {
18643            result = minnga;
18644        }
18645
18646        if (result & cond) {
18647            return true;
18648        }
18649
18650        return false;
18651    },
18652
18653    isFloat : function(value) {
18654        if (value == '') return true;
18655
18656        return (/^[\-0-9]([0-9]+[\.]?)*$/).test(value);
18657    },
18658
18659    isIdentity : function(value) {
18660        if (value == '') return true;
18661
18662        return (/^[a-z]+[a-z0-9_]+$/i).test(value);
18663    },
18664
18665    isIdentitySearch : function(value) {
18666        if (value == '') return true;
18667        var bChk1 = (/^[a-zA-Z]+[a-zA-Z0-9_]+$/i).test(value);
18668        var bChk2 = (/^.*@.{1,2}$/i).test(value);
18669        return bChk1 || bChk2;
18670    },
18671
18672    isKorean : function(value) {
18673        if (value == '') return true;
18674
18675        var count = value.length;
18676
18677        for(var i=0; i < count; ++i){
18678            var cCode = value.charCodeAt(i);
18679
18680            //공백은 무시
18681            if(cCode == 0x20) continue;
18682
18683            if(cCode < 0x80){
18684                return false;
18685            }
18686        }
18687
18688        return true;
18689    },
18690
18691    isAlpha : function(value) {
18692        if (value == '') return true;
18693
18694        return (/^[a-z]+$/i).test(value);
18695    },
18696
18697    isAlphaUpper : function(value) {
18698        if (value == '') return true;
18699
18700        return (/^[A-Z]+$/).test(value);
18701    },
18702
18703    isAlphaLower : function(value) {
18704        if (value == '') return true;
18705
18706        return (/^[a-z]+$/).test(value);
18707    },
18708
18709    isAlphaNum : function(value) {
18710        if (value == '') return true;
18711
18712        return (/^[a-z0-9]+$/i).test(value);
18713    },
18714
18715    isAlphaSpace : function(value) {
18716        if (value == '') return true;
18717
18718        return (/^[a-zA-Z ]+$/).test(value);
18719    },
18720
18721    isAlphaNumUpper : function(value) {
18722        if (value == '') return true;
18723
18724        return (/^[A-Z0-9]+$/).test(value);
18725    },
18726
18727    isAlphaNumLower : function(value) {
18728        if (value == '') return true;
18729
18730        return (/^[a-z0-9]+$/).test(value);
18731    },
18732
18733    isAlphaDash : function(value) {
18734        if (value == '') return true;
18735
18736        return (/^[a-z0-9_-]+$/i).test(value);
18737    },
18738
18739    isAlphaDashUpper : function(value) {
18740        if (value == '') return true;
18741
18742        return (/^[A-Z0-9_-]+$/).test(value);
18743    },
18744
18745    isAlphaDashLower : function(value) {
18746        if (value == '') return true;
18747
18748        return (/^[a-z0-9_-]+$/).test(value);
18749    },
18750
18751    isSsn : function(value) {
18752        value = value.replace(/-/g, '');
18753        if (value == '') return true;
18754
18755        if ( (/[0-9]{2}[01]{1}[0-9]{1}[0123]{1}[0-9]{1}[1234]{1}[0-9]{6}$/).test(value) === false ) {
18756            return false;
18757        }
18758
18759        var sum = 0;
18760        var last = value.charCodeAt(12) - 0x30;
18761        var bases = "234567892345";
18762        for (var i=0; i<12; i++) {
18763            sum += (value.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
18764        };
18765        var mod = sum % 11;
18766
18767        if ( (11 - mod) % 10 != last ) {
18768            return false;
18769        }
18770
18771        return true;
18772    },
18773
18774    isForeignerNo : function(value) {
18775        value = value.replace(/-/g, '');
18776        if (value == '') return true;
18777
18778        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 ) {
18779            return false;
18780        }
18781
18782        var sum = 0;
18783        var last = value.charCodeAt(12) - 0x30;
18784        var bases = "234567892345";
18785        for (var i=0; i<12; i++) {
18786            sum += (value.charCodeAt(i) - 0x30) * (bases.charCodeAt(i) - 0x30);
18787        };
18788        var mod = sum % 11;
18789        if ( (11 - mod + 2) % 10 != last ) {
18790            return false;
18791        }
18792
18793        return true;
18794    },
18795
18796    isBizNo : function(value) {
18797        value = value.replace(/-/g, '');
18798        if (value == '') return true;
18799
18800        if ( (/[0-9]{3}[0-9]{2}[0-9]{5}$/).test(value) === false ) {
18801            return false;
18802        }
18803
18804        var sum = parseInt(value.charAt(0));
18805        var chkno = [0, 3, 7, 1, 3, 7, 1, 3];
18806        for (var i = 1; i < 8; i++) {
18807            sum += (parseInt(value.charAt(i)) * chkno[i]) % 10;
18808        }
18809        sum += Math.floor(parseInt(parseInt(value.charAt(8))) * 5 / 10);
18810        sum += (parseInt(value.charAt(8)) * 5) % 10 + parseInt(value.charAt(9));
18811
18812        if (sum % 10 != 0) {
18813            return false;
18814        }
18815
18816        return true;
18817    },
18818
18819    isJuriNo : function(value) {
18820        value = value.replace(/-/g, '');
18821        if (value == '') return true;
18822
18823        if ( (/^([0-9]{6})-?([0-9]{7})$/).test(value) === false ) {
18824            return false;
18825        }
18826
18827        var sum = 0;
18828        var last = parseInt(value.charAt(12), 10);
18829        for (var i=0; i<12; i++) {
18830            if (i % 2 == 0) {  // * 1
18831                sum += parseInt(value.charAt(i), 10);
18832            } else {    // * 2
18833                sum += parseInt(value.charAt(i), 10) * 2;
18834            };
18835        };
18836
18837        var mod = sum % 10;
18838        if( (10 - mod) % 10 != last ){
18839            return false;
18840        }
18841
18842        return true;
18843    },
18844
18845    isPhone : function(value) {
18846        value = value.replace(/-/g, '');
18847        if (value == '') return true;
18848
18849        return (/^(02|0[0-9]{2,3})[1-9]{1}[0-9]{2,3}[0-9]{4}$/).test(value);
18850    },
18851
18852    isMobile : function(value) {
18853        value = value.replace(/-/g, '');
18854        if (value == '') return true;
18855
18856        return (/^01[016789][1-9]{1}[0-9]{2,3}[0-9]{4}$/).test(value);
18857    },
18858
18859    isZipcode : function(value) {
18860        value = value.replace(/-/g, '');
18861        if (value == '') return true;
18862
18863        return (/^[0-9]{3}[0-9]{3}$/).test(value);
18864    },
18865
18866    isIp : function(value) {
18867        if (value == '') return true;
18868
18869        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);
18870    },
18871
18872    isEmail : function(value) {
18873        value = this.parent.Helper.trim(value);
18874        if (value == '') return true;
18875
18876        return (/^([a-z0-9\_\-\.\+]+)@([a-z0-9\_\-]+\.)+[a-z]{2,63}$/i).test(value);
18877    },
18878
18879    isUrl : function(value) {
18880        if (value == '') return true;
18881
18882        return (/http[s]?:\/\/[a-z0-9_\-]+(\.[a-z0-9_\-]+)+/i).test(value);
18883    },
18884
18885    isDate : function(value) {
18886        value = value.replace(/-/g, '');
18887        if (value == '') return true;
18888
18889        return (/^[12][0-9]{3}(([0]?[1-9])|([1][012]))[0-3]?[0-9]$/).test(value);
18890    },
18891
18892    isPassport : function(value) {
18893        if (value == '') return true;
18894
18895        //일반 여권
18896        if ( (/^[A-Z]{2}[0-9]{7}$/).test(value) === true ) {
18897            return true;
18898        }
18899
18900        //전자 여권
18901        if ( (/^[A-Z]{1}[0-9]{8}$/).test(value) === true ) {
18902            return true;
18903        }
18904
18905        return false;
18906    },
18907
18908    isNumberMin : function(value, limit) {
18909        value = this.parent.Helper.getNumberConv(value);
18910        limit = this.parent.Helper.getNumberConv(limit);
18911
18912        if (value < limit) {
18913            return false;
18914        }
18915
18916        return true;
18917    },
18918
18919    isNumberMax : function(value, limit) {
18920        value = this.parent.Helper.getNumberConv(value);
18921        limit = this.parent.Helper.getNumberConv(limit);
18922
18923        if (value > limit) {
18924            return false;
18925        }
18926
18927        return true;
18928    },
18929
18930    isNumberMinPrice : function(value, limit) {
18931        return this.isNumberMin(value, limit);
18932    },
18933
18934
18935    isNumberMaxPrice : function(value, limit) {
18936        return this.isNumberMin(value, limit);
18937    },
18938
18939    isNumberMinMonth : function(value, limit) {
18940        return this.isNumberMin(value, limit);
18941    },
18942
18943
18944    isNumberMaxMonth : function(value, limit) {
18945        return this.isNumberMin(value, limit);
18946    },
18947
18948    isNumberRange : function(value, min, max) {
18949        value = this.parent.Helper.getNumberConv(value);
18950
18951        min = this.parent.Helper.getNumberConv(min);
18952        max = this.parent.Helper.getNumberConv(max);
18953
18954        if (value < min || value > max) {
18955            return false;
18956        }
18957
18958        return true;
18959    }
18960};
18961
18962/**
18963 * FwValidator.Filter
18964 *
18965 * @package     jquery
18966 * @subpackage  validator
18967 */
18968
18969FwValidator.Filter = {
18970
18971    parent : FwValidator,
18972
18973    isFill : function(Response, cond) {
18974        if (typeof cond != 'string') {
18975            var count = cond.length;
18976            var result = this.parent.Helper.getResult(Response, parent.CODE_SUCCESS);
18977
18978            for (var i = 0; i < count; ++i) {
18979                result = this._fillConditionCheck(Response, cond[i]);
18980
18981                if (result.passed === true) {
18982                    return result;
18983                }
18984            }
18985
18986            return result;
18987        }
18988
18989        return this._fillConditionCheck(Response, cond);
18990    },
18991
18992    isMatch : function(Response, sField) {
18993        var $ = this.parent.jQuery;
18994
18995        if(Response.elmCurrValue == ''){
18996            return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
18997        }
18998
18999        //Radio 나 Checkbox의 경우 무시
19000        if(Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox'){
19001            return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19002        }
19003
19004        var elmTarget = $('#'+sField);
19005        var elmTargetValue = elmTarget.val();
19006
19007        if (Response.elmCurrValue != elmTargetValue) {
19008            var label = elmTarget.attr(this.parent.ATTR_LABEL);
19009            var match = label ? label : sField;
19010
19011            Response.elmCurrErrorMsg = Response.elmCurrErrorMsg.replace(/\{match\}/i, match);
19012
19013            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19014        }
19015
19016        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19017    },
19018
19019    isMax : function(Response, iLen) {
19020        var $ = this.parent.jQuery;
19021        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19022
19023        if (Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox') {
19024            var chkCount = 0;
19025            var sName = Response.elmCurrField.attr('name');
19026
19027            $('input[name="'+sName+'"]').each(function(i){
19028                if ($(this).get(0).checked === true) {
19029                    ++chkCount;
19030                }
19031            });
19032
19033            if (chkCount > iLen) {
19034                result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19035            }
19036
19037        } else {
19038            var len = Response.elmCurrValue.length;
19039
19040            if (len > iLen) {
19041                result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19042            }
19043        }
19044
19045        if (result.passed === this.parent.CODE_FAIL) {
19046            result.msg = result.msg.replace(/\{max\}/i, iLen);
19047        }
19048
19049        return result;
19050    },
19051
19052    isMin : function(Response, iLen) {
19053        var $ = this.parent.jQuery;
19054        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19055
19056        if(Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox'){
19057            var chkCount = 0;
19058            var sName = Response.elmCurrField.attr('name');
19059
19060            $('input[name="'+sName+'"]').each(function(i){
19061                if($(this).get(0).checked === true){
19062                    ++chkCount;
19063                }
19064            });
19065
19066            if (chkCount < iLen) {
19067                result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19068            }
19069
19070        }else{
19071            var len = Response.elmCurrValue.length;
19072
19073            if(len < iLen){
19074                result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19075            }
19076        }
19077
19078        if(result.passed === this.parent.CODE_FAIL){
19079            result.msg = result.msg.replace(/\{min\}/i, iLen);
19080        }
19081
19082        return result;
19083    },
19084
19085    isNumber : function(Response, iCond) {
19086        var result = this.parent.Verify.isNumber(Response.elmCurrValue, iCond);
19087
19088        if(result === false){
19089            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19090        }
19091
19092        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19093    },
19094
19095    isIdentity : function(Response){
19096        var result = this.parent.Verify.isIdentity(Response.elmCurrValue);
19097
19098        if(result === false){
19099            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19100        }
19101
19102        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19103    },
19104
19105    isIdentitySearch : function(Response){
19106        var result = this.parent.Verify.isIdentitySearch(Response.elmCurrValue);
19107
19108        if(result === false){
19109            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19110        }
19111
19112        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19113    },
19114
19115    isKorean : function(Response){
19116        var result = this.parent.Verify.isKorean(Response.elmCurrValue);
19117
19118        if(result === false){
19119            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19120        }
19121
19122        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19123    },
19124
19125    isAlpha : function(Response){
19126        var result = this.parent.Verify.isAlpha(Response.elmCurrValue);
19127
19128        if(result === false){
19129            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19130        }
19131
19132        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19133    },
19134
19135    isAlphaLower : function(Response){
19136        var result = this.parent.Verify.isAlphaLower(Response.elmCurrValue);
19137
19138        if(result === false){
19139            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19140        }
19141
19142        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19143    },
19144
19145
19146    isAlphaSpace : function(Response){
19147        var result = this.parent.Verify.isAlphaSpace(Response.elmCurrValue);
19148
19149        if(result === false){
19150            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19151        }
19152
19153        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19154    },
19155
19156    isAlphaUpper : function(Response){
19157        var result = this.parent.Verify.isAlphaUpper(Response.elmCurrValue);
19158
19159        if(result === false){
19160            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19161        }
19162
19163        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19164    },
19165
19166    isAlphaNum : function(Response){
19167        var result = this.parent.Verify.isAlphaNum(Response.elmCurrValue);
19168
19169        if(result === false){
19170            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19171        }
19172
19173        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19174    },
19175
19176    isAlphaNumLower : function(Response){
19177        var result = this.parent.Verify.isAlphaNumLower(Response.elmCurrValue);
19178
19179        if(result === false){
19180            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19181        }
19182
19183        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19184    },
19185
19186    isAlphaNumUpper : function(Response){
19187        var result = this.parent.Verify.isAlphaNumUpper(Response.elmCurrValue);
19188
19189        if(result === false){
19190            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19191        }
19192
19193        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19194    },
19195
19196    isAlphaDash : function(Response){
19197        var result = this.parent.Verify.isAlphaDash(Response.elmCurrValue);
19198
19199        if(result === false){
19200            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19201        }
19202
19203        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19204    },
19205
19206    isAlphaDashLower : function(Response){
19207        var result = this.parent.Verify.isAlphaDashLower(Response.elmCurrValue);
19208
19209        if(result === false){
19210            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19211        }
19212
19213        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19214    },
19215
19216    isAlphaDashUpper : function(Response){
19217        var result = this.parent.Verify.isAlphaDashUpper(Response.elmCurrValue);
19218
19219        if(result === false){
19220            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19221        }
19222
19223        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19224    },
19225
19226    isSsn : function(Response){
19227        var result = this.parent.Verify.isSsn(Response.elmCurrValue);
19228
19229        if(result === false){
19230            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19231        }
19232
19233        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19234    },
19235
19236    isForeignerNo : function(Response){
19237        var result = this.parent.Verify.isForeignerNo(Response.elmCurrValue);
19238
19239        if(result === false){
19240            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19241        }
19242
19243        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19244    },
19245
19246    isBizNo : function(Response){
19247        var result = this.parent.Verify.isBizNo(Response.elmCurrValue);
19248
19249        if(result === false){
19250            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19251        }
19252
19253        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19254    },
19255
19256    isJuriNo : function(Response){
19257        var result = this.parent.Verify.isJuriNo(Response.elmCurrValue);
19258
19259        if(result === false){
19260            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19261        }
19262
19263        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19264    },
19265
19266    isPhone : function(Response){
19267        var result = this.parent.Verify.isPhone(Response.elmCurrValue);
19268
19269        if(result === false){
19270            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19271        }
19272
19273        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19274    },
19275
19276    isMobile : function(Response){
19277        var result = this.parent.Verify.isMobile(Response.elmCurrValue);
19278
19279        if(result === false){
19280            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19281        }
19282
19283        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19284    },
19285
19286    isZipcode : function(Response){
19287        var result = this.parent.Verify.isZipcode(Response.elmCurrValue);
19288
19289        if(result === false){
19290            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19291        }
19292
19293        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19294    },
19295
19296    isIp : function(Response){
19297        var result = this.parent.Verify.isIp(Response.elmCurrValue);
19298
19299        if(result === false){
19300            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19301        }
19302
19303        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19304    },
19305
19306    isEmail : function(Response){
19307        var result = this.parent.Verify.isEmail(Response.elmCurrValue);
19308
19309        if(result === false){
19310            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19311        }
19312
19313        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19314    },
19315
19316    isUrl : function(Response){
19317        var result = this.parent.Verify.isUrl(Response.elmCurrValue);
19318
19319        if(result === false){
19320            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19321        }
19322
19323        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19324    },
19325
19326    isDate : function(Response){
19327        var result = this.parent.Verify.isDate(Response.elmCurrValue);
19328
19329        if(result === false){
19330            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19331        }
19332
19333        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19334    },
19335
19336    isRegex : function(Response, regex){
19337        regex = eval(regex);
19338
19339        if( regex.test(Response.elmCurrValue) === false ){
19340            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19341        }
19342
19343        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19344    },
19345
19346    isPassport : function(Response){
19347        var result = this.parent.Verify.isPassport(Response.elmCurrValue);
19348
19349        if(result === false){
19350            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19351        }
19352
19353        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19354    },
19355
19356    isSimplexEditorFill : function(Response){
19357
19358        var result = eval(Response.elmCurrValue + ".isEmptyContent();");
19359
19360        if(result === true){
19361            return this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19362        }
19363
19364        return this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19365
19366    },
19367
19368    isMaxByte : function(Response, iLen) {
19369        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19370
19371        var len = this.pare
19371nt.Helper.getByte(Response.elmCurrValue);
19372
19373        if (len > iLen) {
19374            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19375            result.msg = result.msg.replace(/\{max\}/i, iLen);
19376        }
19377
19378        return result;
19379    },
19380
19381    isMinByte : function(Response, iLen) {
19382        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19383
19384        var len = this.parent.Helper.getByte(Response.elmCurrValue);
19385
19386        if (len < iLen) {
19387            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19388            result.msg = result.msg.replace(/\{min\}/i, iLen);
19389        }
19390
19391        return result;
19392    },
19393
19394    isByteRange : function(Response, range) {
19395        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19396
19397        var rangeInfo = this._getRangeNum(range);
19398        var iMin = rangeInfo.min;
19399        var iMax = rangeInfo.max;
19400
19401        var len = this.parent.Helper.getByte(Response.elmCurrValue);
19402
19403        if (len < iMin || len > iMax) {
19404            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19405            result.msg = result.msg.replace(/\{min\}/i, iMin);
19406            result.msg = result.msg.replace(/\{max\}/i, iMax);
19407        }
19408
19409        return result;
19410    },
19411
19412    isLengthRange : function(Response, range) {
19413        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19414
19415        var rangeInfo = this._getRangeNum(range);
19416        var iMin = rangeInfo.min;
19417        var iMax = rangeInfo.max;
19418
19419        var resultMin = this.isMin(Response, iMin);
19420        var resultMax = this.isMax(Response, iMax);
19421
19422        if (resultMin.passed === this.parent.CODE_FAIL || resultMax.passed === this.parent.CODE_FAIL) {
19423            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19424            result.msg = result.msg.replace(/\{min\}/i, iMin);
19425            result.msg = result.msg.replace(/\{max\}/i, iMax);
19426        }
19427
19428        return result;
19429    },
19430
19431    isNumberMin : function(Response, iLimit) {
19432        var check = this.parent.Verify.isNumberMin(Response.elmCurrValue, iLimit);
19433        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19434
19435        if(check === false){
19436            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19437            result.msg = result.msg.replace(/\{min\}/i, iLimit);
19438        }
19439
19440        return result;
19441    },
19442
19443    isNumberMax : function(Response, iLimit) {
19444        var check = this.parent.Verify.isNumberMax(Response.elmCurrValue, iLimit);
19445        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19446
19447        if(check === false){
19448            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19449            result.msg = result.msg.replace(/\{max\}/i, iLimit);
19450        }
19451
19452        return result;
19453    },
19454
19455    isNumberMinPrice : function(Response, iLimit) {
19456        var check = this.parent.Verify.isNumberMin(Response.elmCurrValue, iLimit);
19457        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19458
19459        if(check === false){
19460            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19461            result.msg = result.msg.replace(/\{min\}/i, iLimit);
19462        }
19463
19464        return result;
19465    },
19466
19467    isNumberMaxPrice : function(Response, iLimit) {
19468        var check = this.parent.Verify.isNumberMax(Response.elmCurrValue, iLimit);
19469        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19470
19471        if(check === false){
19472            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19473            result.msg = result.msg.replace(/\{max\}/i, iLimit);
19474        }
19475
19476        return result;
19477    },
19478
19479    isNumberMinMonth : function(Response, iLimit) {
19480        var check = this.parent.Verify.isNumberMin(Response.elmCurrValue, iLimit);
19481        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19482
19483        if(check === false){
19484            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19485            result.msg = result.msg.replace(/\{min\}/i, iLimit);
19486        }
19487
19488        return result;
19489    },
19490
19491    isNumberMaxMonth : function(Response, iLimit) {
19492        var check = this.parent.Verify.isNumberMax(Response.elmCurrValue, iLimit);
19493        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19494
19495        if(check === false){
19496            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19497            result.msg = result.msg.replace(/\{max\}/i, iLimit);
19498        }
19499
19500        return result;
19501    },
19502
19503    isNumberRange : function(Response, range) {
19504        var iMin = range[0];
19505        var iMax = range[1];
19506
19507        var check = this.parent.Verify.isNumberRange(Response.elmCurrValue, iMin, iMax);
19508        var result = this.parent.Helper.getResult(Response, this.parent.CODE_SUCCESS);
19509
19510        if(check === false){
19511            result = this.parent.Helper.getResult(Response, this.parent.CODE_FAIL);
19512            result.msg = result.msg.replace(/\{min\}/i, iMin);
19513            result.msg = result.msg.replace(/\{max\}
19513/i, iMax);
19514        }
19515
19516        return result;
19517    },
19518
19519    _getRangeNum : function(range) {
19520        var result = {};
19521
19522        result.min = range[0] <= 0 ? 0 : parseInt(range[0]);
19523        result.max = range[1] <= 0 ? 0 : parseInt(range[1]);
19524
19525        return result;
19526    },
19527
19528    _fillConditionCheck : function(Response, cond) {
19529        var $ = this.parent.jQuery;
19530        var parent = this.parent;
19531
19532
19533        cond = parent.Helper.trim(cond);
19534
19535        //조건식이 들어오면 조건식에 맞을 경우만 필수값을 체크함
19536        if (cond) {
19537            var conditions = cond.split('=');
19538            var fieldId = parent.Helper.trim(conditions[0]);
19539            var fieldVal = parent.Helper.trim(conditions[1]);
19540
19541            try {
19542                var val = parent.Helper.getValue(Response.formId, $('#'+fieldId));
19543                val = parent.Helper.trim(val);
19544
19545                if(fieldVal != val) {
19546                    return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
19547                }
19548            } catch(e) {
19549                if (parent.DEBUG_MODE == true) {
19550                    Response.elmCurrErrorMsg = parent.msgs['isFillError'];
19551                    Response.elmCurrErrorMsg = Response.elmCurrErrorMsg.replace(/\{condition\}/i, cond);
19552                    return parent.Helper.getResult(Response, parent.CODE_FAIL);
19553                }
19554
19555                return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
19556            }
19557        }
19558
19559        //Radio 나 Checkbox의 경우 선택한값이 있는지 여부를 체크함
19560        if (Response.elmCurrFieldType == 'radio' || Response.elmCurrFieldType == 'checkbox') {
19561
19562            var sName = Response.elmCurrField.attr('name');
19563            var result = parent.Helper.getResult(Response, parent.CODE_FAIL);
19564
19565            $('input[name="'+sName+'"]').each(function(i){
19566                if ($(this).get(0).checked === true) {
19567                    result = parent.Helper.getResult(Response, parent.CODE_SUCCESS);
19568                }
19569            });
19570
19571            return result;
19572
19573        }
19574
19575        //일반 텍스트 박스
19576        if (Response.elmCurrValue != '') {
19577            return parent.Helper.getResult(Response, parent.CODE_SUCCESS);
19578        }
19579
19580        return parent.Helper.getResult(Response, parent.CODE_FAIL);
19581    }
19582};
19583
19584FwValidator.msgs = {
19585
19586    //기본
19587    'isFill' : '{label} 항목은 필수 입력값입니다.',
19588
19589    'isNumber' : '{label} 항목이 숫자 형식이 아닙니다.',
19590
19591    'isEmail' : '{label} 항목이 이메일 형식이 아닙니다.',
19592
19593    'isIdentity' : '{label} 항목이 아이디 형식이 아닙니다.',
19594
19595    'isIdentitySearch' : '{label} 항목이 아이디 형식이 아닙니다.',
19596
19597    'isMax' : '{label} 을(를) {max}자 이하로 입력해주세요.',
19598
19599    'isMin' : '{label} 항목이 {min}자(개) 이상으로 해주십시오 .',
19600
19601    'isRegex' : '{label} 항목이 올바른 입력값이 아닙니다.',
19602
19603    'isAlpha' : '{label} 항목이 영문이 아닙니다',
19604
19605    'isAlphaLower' : '{label} 항목이 영문 소문자 형식이 아닙니다',
19606
19607    'isAlphaUpper' : '{label} 항목이 영문 대문자 형식이 아닙니다',
19608
19609    'isAlphaNum' : '{label} 항목이 영문이나 숫자 형식이 아닙니다.',
19610
19611    'isAlphaNumLower' : '{label} 항목이 영문 소문자 혹은 숫자 형식이 아닙니다.',
19612
19613    'isAlphaNumUpper' : '{label} 항목이 영문 대문자 혹은 숫자 형식이 아닙니다.',
19614
19615    'isAlphaSpace' : '{label} 항목이 영문이 아닙니다',
19616
19617    'isAlphaDash' : '{label} 항목이 [영문,숫자,_,-] 형식이 아닙니다.',
19618
19619    'isAlphaDashLower' : '{label} 항목이 [영문 소문자,숫자,_,-] 형식이 아닙니다.',
19620
19621    'isAlphaDashUpper' : '{label} 항목이 [영문 대문자,숫자,_,-] 형식이 아닙니다.',
19622
19623    'isKorean' : '{label} 항목이 한국어 형식이 아닙니다.',
19624
19625    'isUrl' : '{label} 항목이 URL 형식이 아닙니다.',
19626
19627    'isSsn' : '{label} 항목이 주민등록번호 형식이 아닙니다.',
19628
19629    'isForeignerNo' : '{label} 항목이 외국인등록번호 형식이 아닙니다.',
19630
19631    'isBizNo' : '{label} 항목이 사업자번호 형식이 아닙니다.',
19632
19633    'isPhone' : '{label} 항목이 전화번호 형식이 아닙니다.',
19634
19635    'isMobile' : '{label} 항목이 핸드폰 형식이 아닙니다.',
19636
19637    'isZipcode' : '{label} 항목이 우편번호 형식이 아닙니다.',
19638
19639    'isJuriNo' : '{label} 항목이 법인번호 형식이 아닙니다.',
19640
19641    'isIp' : '{label} 항목이 아이피 형식이 아닙니다.',
19642
19643    'isDate' : '{label} 항목이 날짜 형식이 아닙니다.',
19644
19645    'isMatch' : '{label} 항목과 {match} 항목이 같지 않습니다.',
19646
19647    'isSuccess' : '{label} 항목의 데이터는 전송할 수 없습니다.',
19648
19649    'isSimplexEditorFill' : '{label}(을/를) 입력하세요',
19650
19651    'isPassport' : '{label} 항목이 여권번호 형식이 아닙니다.',
19652
19653    'isMaxByte' : '{label} 항목은 {max}bytes 이하로 해주십시오.',
19654
19655    'isMinByte' : '{label} 항목은 {min}bytes 이상으로 해주십시오.',
19656
19657    'isByteRange' : '{label} 항목은 {min} ~ {max}bytes 범위로 해주십시오.',
19658
19659    'isLengthRange' : '{label} 항목은 {min} ~ {max}자(개) 범위로 해주십시오.',
19660
19661    'isNumberMin' : '{label} 항목은 {min} 이상으로 해주십시오.',
19662
19663    'isNumberMax' : '{label} 항목은 {max} 이하로 해주십시오.',
19664
19665    'isNumberMinPrice' : '{label} 항목은 {min}원 이상으로 입력해 주세요.',
19666
19667    'isNumberMaxPrice' : '{label} 항목은 {max}원 이하로 입력해 주세요.',
19668
19669    'isNumberMinMonth' : '{label} 항목은 {min}개월 이상으로 입력해 주세요.',
19670
19671    'isNumberMaxMonth' : '{label} 항목은 {max}개월 이하로 입력해 주세요.',
19672
19673    'isNumberRange' : '{label} 항목은 {min} ~ {max} 범위로 해주세요.',
19674
19675
19676    //디버깅
19677    'notMethod' : '{label} 항목에 존재하지 않는 필터를 사용했습니다.',
19678
19679    'isFillError' : "[{label}
19679] 필드의 isFill {condition} 문장이 잘못되었습니다.\r\n해당 필드의 아이디를 확인하세요."
19680
19681};
19682
19683FwValidator.Handler.overrideMsgs({
19684
19685    //기본
19686    'isFill': sprintf(__('IS.REQUIRED.FIELD', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19687
19688    'isNumber': sprintf(__('MAY.ONLY.CONTAIN.NUMBERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19689
19690    'isEmail': sprintf(__('VALID.EMAIL.ADDRESS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19691
19692    'isIdentity': sprintf(__('FIELD.CORRECT.ID.FORMAT', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19693
19694    'isIdentitySearch': sprintf(__('FIELD.CORRECT.ID.FORMAT', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19695
19696    'isMax': sprintf(__('EXCEED.CHARACTERS.LENGTH', 'RESOUCE.JS.VALIDATOR'), '{label}', '{max}'),
19697
19698    'isMin': sprintf(__('MUST.AT.LEAST.CHARACTERS', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}'),
19699
19700    'isRegex': sprintf(__('FIELD.IN.CORRECT.FORMAT', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19701
19702    'isAlpha': sprintf(__('ALPHABETICAL.CHARACTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19703
19704    'isAlphaLower': sprintf(__('CONTAIN.LOWERCASE.LETTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19705
19706    'isAlphaUpper': sprintf(__('CONTAIN.UPPERCASE.LETTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19707
19708    'isAlphaNum': sprintf(__('ALPHANUMERIC.CHARACTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19709
19710    'isAlphaNumLower': sprintf(__('CONTAIN.LOWERCASE.LETTERS.001', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19711
19712    'isAlphaNumUpper': sprintf(__('CONTAIN.UPPERCASE.LETTERS.001', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19713
19714    'isAlphaSpace': sprintf(__('ALPHABETICAL.CHARACTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19715
19716    'isAlphaDash': sprintf(__('UNDERSCORES.DASHES', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19717
19718    'isAlphaDashLower': sprintf(__('UNDERSCORES.DASHES.001', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19719
19720    'isAlphaDashUpper': sprintf(__('UNDERSCORES.DASHES.002', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19721
19722    'isKorean': sprintf(__('CONTAIN.KOREAN.CHARACTERS', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19723
19724    'isUrl': sprintf(__('MUST.CONTAIN.VALID.URL', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19725
19726    'isSsn': sprintf(__('MUST.CONTAIN.VALID.SSN', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19727
19728    'isForeignerNo': sprintf(__('ALIEN.REGISTRATION.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19729
19730    'isBizNo': sprintf(__('REGISTRATION.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19731
19732    'isPhone': sprintf(__('VALID.PHONE.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19733
19734    'isMobile': sprintf(__('VALID.MOBILE.PHONE.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19735
19736    'isZipcode': sprintf(__('CONTAIN.VALID.ZIP.CODE', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19737
19738    'isJuriNo': sprintf(__('CORPORATE.IDENTITY.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19739
19740    'isIp': sprintf(__('MUST.CONTAIN.VALID.IP', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19741
19742    'isDate': sprintf(__('MUST.CONTAIN.VALID.DATE', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19743
19744    'isMatch': sprintf(__('THE.FIELD.DOES.NOT.MATCH', 'RESOUCE.JS.VALIDATOR'), '{label}', '{match}'),
19745
19746    'isSuccess': sprintf(__('THE.DATA.BE.TRANSFERRED', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19747
19748    'isSimplexEditorFill': sprintf(__('THE.FIELD.MUST.HAVE.VALUE', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19749
19750    'isPassport': sprintf(__('VALID.PASSPORT.NUMBER', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19751
19752    'isMaxByte': sprintf(__('VALUE.CAN.NOT.EXCEED', 'RESOUCE.JS.VALIDATOR'), '{label}', '{max}'),
19753
19754    'isMinByte': sprintf(__('THE.FIELD.VALUE.MUST.BE', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}'),
19755
19756    'isByteRange': sprintf(__('THE.FIELD.VALUE.MUST.BE.001', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}', '{max}'),
19757
19758    'isLengthRange': sprintf(__('MUST.CHARACTERS.LENGTH', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}', '{max}'),
19759
19760    'isNumberMin': sprintf(__('THE.FIELD.VALUE.MUST.BE.002', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}'),
19761
19762    'isNumberMax': sprintf(__('VALUE.CAN.NOT.EXCEED.001', 'RESOUCE.JS.VALIDATOR'), '{label}', '{max}'),
19763
19764    'isNumberMinPrice': sprintf(__('VALUE.PRICE.MIN', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}'),
19765
19766    'isNumberMaxPrice': sprintf(__('VALUE.PRICE.MAX', 'RESOUCE.JS.VALIDATOR'), '{label}', '{max}'),
19767
19768    'isNumberMinMonth': sprintf(__('VALUE.MONTH.MIN', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}'),
19769
19770    'isNumberMaxMonth': sprintf(__('VALUE.MONTH.MAX', 'RESOUCE.JS.VALIDATOR'), '{label}', '{max}'),
19771
19772    'isNumberRange': sprintf(__('THE.FIELD.VALUE.MUST.BE.003', 'RESOUCE.JS.VALIDATOR'), '{label}', '{min}', '{max}'),
19773
19774
19775    //디버깅
19776    'notMethod': sprintf(__('FILTER.WAS.USED.FIELD', 'RESOUCE.JS.VALIDATOR'), '{label}'),
19777
19778    'isFillError': sprintf(__('SENTENCE.INCORRECT.PLEASE', 'RESOUCE.JS.VALIDATOR'), '{label}', '{condition}')
19779
19780});
19781
19782/* flatpickr v4.5.0, @license MIT */
19783(function (global, factory) {
19784    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
19785    typeof define === 'function' && define.amd ? define(factory) :
19786    (global.flatpickr = factory());
19787}(this, (function () { 'use strict';
19788
19789    var pad = function pad(number) {
19790      return ("0" + number).slice(-2);
19791    };
19792    var int = function int(bool) {
19793      return bool === true ? 1 : 0;
19794    };
19795    function debounce(func, wait, immediate) {
19796      if (immediate === void 0) {
19797        immediate = false;
19798      }
19799      var timeout;
19800      return function () {
19801        var context = this,
19802            args = arguments;
19803        timeout !== null && clearTimeout(timeout);
19804        timeout = window.setTimeout(function () {
19805          timeout = null;
19806          if (!immediate) func.apply(context, args);
19807        }, wait);
19808        if (immediate && !timeout) func.apply(context, args);
19809      };
19810    }
19811    var arrayify = function arrayify(obj) {
19812      return obj instanceof Array ? obj : [obj];
19813    };
19814
19815    var do_nothing = function do_nothing() {
19816      return undefined;
19817    };
19818
19819    var monthToStr = function monthToStr(monthNumber, shorthand, locale) {
19820      return locale.months[shorthand ? "shorthand" : "longhand"][monthNumber];
19821    };
19822    var revFormat = {
19823      D: do_nothing,
19824      F: function F(dateObj, monthName, locale) {
19825        dateObj.setMonth(locale.months.longhand.indexOf(monthName));
19826      },
19827      G: function G(dateObj, hour) {
19828        dateObj.setHours(parseFloat(hour));
19829      },
19830      H: function H(dateObj, hour) {
19831        dateObj.setHours(parseFloat(hour));
19832      },
19833      J: function J(dateObj, day) {
19834        dateObj.setDate(parseFloat(day));
19835      },
19836      K: function K(dateObj, amPM, locale) {
19837        dateObj.setHours(dateObj.getHours() % 12 + 12 * int(new RegExp(locale.amPM[1], "i").test(amPM)));
19838      },
19839      M: function M(dateObj, shortMonth, locale) {
19840        dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth));
19841      },
19842      S: function S(dateObj, seconds) {
19843        dateObj.setSeconds(parseFloat(seconds));
19844      },
19845      U: function U(_, unixSeconds) {
19846        return new Date(parseFloat(unixSeconds) * 1000);
19847      },
19848      W: function W(dateObj, weekNum) {
19849        var weekNumber = parseInt(weekNum);
19850        return new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0);
19851      },
19852      Y: function Y(dateObj, year) {
19853        dateObj.setFullYear(parseFloat(year));
19854      },
19855      Z: function Z(_, ISODate) {
19856        return new Date(ISODate);
19857      },
19858      d: function d(dateObj, day) {
19859        dateObj.setDate(parseFloat(day));
19860      },
19861      h: function h(dateObj, hour) {
19862        dateObj.setHours(parseFloat(hour));
19863      },
19864      i: function i(dateObj, minutes) {
19865        dateObj.setMinutes(parseFloat(minutes));
19866      },
19867      j: function j(dateObj, day) {
19868        dateObj.setDate(parseFloat(day));
19869      },
19870      l: do_nothing,
19871      m: function m(dateObj, month) {
19872        dateObj.setMonth(parseFloat(month) - 1);
19873      },
19874      n: function n(dateObj, month) {
19875        dateObj.setMonth(parseFloat(month) - 1);
19876      },
19877      s: function s(dateObj, seconds) {
19878        dateObj.setSeconds(parseFloat(seconds));
19879      },
19880      w: do_nothing,
19881      y: function y(dateObj, year) {
19882        dateObj.setFullYear(2000 + parseFloat(year));
19883      }
19884    };
19885    var tokenRegex = {
19886      D: "(\\w+)",
19887      F: "(\\w+)",
19888      G: "(\\d\\d|\\d)",
19889      H: "(\\d\\d|\\d)",
19890      J: "(\\d\\d|\\d)\\w+",
19891      K: "",
19892      M: "(\\w+)",
19893      S: "(\\d\\d|\\d)",
19894      U: "(.+)",
19895      W: "(\\d\\d|\\d)",
19896      Y: "(\\d{4})",
19897      Z: "(.+)",
19898      d: "(\\d\\d|\\d)",
19899      h: "(\\d\\d|\\d)",
19900      i: "(\\d\\d|\\d)",
19901      j: "(\\d\\d|\\d)",
19902      l: "(\\w+)",
19903      m: "(\\d\\d|\\d)",
19904      n: "(\\d\\d|\\d)",
19905      s: "(\\d\\d|\\d)",
19906      w: "(\\d\\d|\\d)",
19907      y: "(\\d{2})"
19908    };
19909    var formats = {
19910      Z: function Z(date) {
19911        return date.toISOString();
19912      },
19913      D: function D(date, locale, options) {
19914        return locale.weekdays.shorthand[formats.w(date, locale, options)];
19915      },
19916      F: function F(date, locale, options) {
19917        return monthToStr(formats.n(date, locale, options) - 1, false, locale);
19918      },
19919      G: function G(date, locale, options) {
19920        return pad(formats.h(date, locale, options));
19921      },
19922      H: function H(date) {
19923        return pad(date.getHours());
19924      },
19925      J: function J(date, locale) {
19926        return locale.ordinal !== undefined ? date.getDate() + locale.ordinal(date.getDate()) : date.getDate();
19927      },
19928      K: function K(date, locale) {
19929        return locale.amPM[int(date.getHours() > 11)];
19930      },
19931      M: function M(date, locale) {
19932        return monthToStr(date.getMonth(), true, locale);
19933      },
19934      S: function S(date) {
19935        return pad(date.getSeconds());
19936      },
19937      U: function U(date) {
19938        return date.getTime() / 1000;
19939      },
19940      W: function W(date, _, options) {
19941        return options.getWeek(date);
19942      },
19943      Y: function Y(date) {
19944        return date.getFullYear();
19945      },
19946      d: function d(date) {
19947        return pad(date.getDate());
19948      },
19949      h: function h(date) {
19950        return date.getHours() % 12 ? date.getHours() % 12 : 12;
19951      },
19952      i: function i(date) {
19953        return pad(date.getMinutes());
19954      },
19955      j: function j(date) {
19956        return date.getDate();
19957      },
19958      l: function l(date, locale) {
19959        return locale.weekdays.longhand[date.getDay()];
19960      },
19961      m: function m(date) {
19962        return pad(date.getMonth() + 1);
19963      },
19964      n: function n(date) {
19965        return date.getMonth() + 1;
19966      },
19967      s: function s(date) {
19968        return date.getSeconds();
19969      },
19970      w: function w(date) {
19971        return date.getDay();
19972      },
19973      y: function y(date) {
19974        return String(date.getFullYear()).substring(2);
19975      }
19976    };
19977
19978    var english = {
19979      weekdays: {
19980        shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
19981        longhand: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
19982      },
19983      months: {
19984        shorthand: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
19985        longhand: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "
19985November", "December"]
19986      },
19987      daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
19988      firstDayOfWeek: 0,
19989      ordinal: function ordinal(nth) {
19990        var s = nth % 100;
19991        if (s > 3 && s < 21) return "th";
19992
19993        switch (s % 10) {
19994          case 1:
19995            return "st";
19996
19997          case 2:
19998            return "nd";
19999
20000          case 3:
20001            return "rd";
20002
20003          default:
20004            return "th";
20005        }
20006      },
20007      rangeSeparator: " - ",
20008      weekAbbreviation: "Wk",
20009      toggleTitle: "Click to toggle",
20010      amPM: ["AM", "PM"],
20011      yearAriaLabel: "Year"
20012    };
20013
20014    var createDateFormatter = function createDateFormatter(_ref) {
20015      var _ref$config = _ref.config,
20016          config = _ref$config === void 0 ? defaults : _ref$config,
20017          _ref$l10n = _ref.l10n,
20018          l10n = _ref$l10n === void 0 ? english : _ref$l10n;
20019      return function (dateObj, frmt, overrideLocale) {
20020        if (config.formatDate !== undefined) return config.formatDate(dateObj, frmt);
20021        var locale = overrideLocale || l10n;
20022        return frmt.split("").map(function (c, i, arr) {
20023          return formats[c] && arr[i - 1] !== "\\" ? formats[c](dateObj, locale, config) : c !== "\\" ? c : "";
20024        }).join("");
20025      };
20026    };
20027    var createDateParser = function createDateParser(_ref2) {
20028      var _ref2$config = _ref2.config,
20029          config = _ref2$config === void 0 ? defaults : _ref2$config,
20030          _ref2$l10n = _ref2.l10n,
20031          l10n = _ref2$l10n === void 0 ? english : _ref2$l10n;
20032      return function (date, givenFormat, timeless) {
20033        if (date !== 0 && !date) return undefined;
20034        var parsedDate;
20035        var date_orig = date;
20036        if (date instanceof Date) parsedDate = new Date(date.getTime());else if (typeof date !== "string" && date.toFixed !== undefined) parsedDate = new Date(date);else if (typeof date === "string") {
20037          var format = givenFormat || (config || defaults).dateFormat;
20038          var datestr = String(date).trim();
20039
20040          if (datestr === "today") {
20041            parsedDate = new Date();
20042            timeless = true;
20043          } else if (/Z$/.test(datestr) || /GMT$/.test(datestr)) parsedDate = new Date(date);else if (config && config.parseDate) parsedDate = config.parseDate(date, format);else {
20044            parsedDate = !config || !config.noCalendar ? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0) : new Date(new Date().setHours(0, 0, 0, 0));
20045            var matched,
20046                ops = [];
20047
20048            for (var i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) {
20049              var token = format[i];
20050              var isBackSlash = token === "\\";
20051              var escaped = format[i - 1] === "\\" || isBackSlash;
20052
20053              if (tokenRegex[token] && !escaped) {
20054                regexStr += tokenRegex[token];
20055                var match = new RegExp(regexStr).exec(date);
20056
20057                if (match && (matched = true)) {
20058                  ops[token !== "Y" ? "push" : "unshift"]({
20059                    fn: revFormat[token],
20060                    val: match[++matchIndex]
20061                  });
20062                }
20063              } else if (!isBackSlash) regexStr += ".";
20064
20065              ops.forEach(function (_ref3) {
20066                var fn = _ref3.fn,
20067                    val = _ref3.val;
20068                return parsedDate = fn(parsedDate, val, l10n) || parsedDate;
20069              });
20070            }
20071
20072            parsedDate = matched ? parsedDate : undefined;
20073          }
20074        }
20075
20076        if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) {
20077          config.errorHandler(new Error("Invalid date provided: " + date_orig));
20078          return undefined;
20079        }
20080
20081        if (timeless === true) parsedDate.setHours(0, 0, 0, 0);
20082        return parsedDate;
20083      };
20084    };
20085    function compareDates(date1, date2, timeless) {
20086      if (timeless === void 0) {
20087        timeless = true;
20088      }
20089
20090      if (timeless !== false) {
20091        return new Date(date1.getTime()).setHours(0, 0, 0, 0) - new Date(date2.getTime()).setHours(0, 0, 0, 0);
20092      }
20093
20094      return date1.getTime() - date2.getTime();
20095    }
20096    var getWeek = function getWeek(givenDate) {
20097      var date = new Date(givenDate.getTime());
20098      date.setHours(0, 0, 0, 0);
20099      date.setDate(date.getDate() + 3 - (date.getDay() + 6) % 7);
20100      var week1 = new Date(date.getFullYear(), 0, 4);
20101      return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (week1.getDay() + 6) % 7) / 7);
20102    };
20103    var isBetween = function isBetween(ts, ts1, ts2) {
20104      return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2);
20105    };
20106    var duration = {
20107      DAY: 86400000
20108    };
20109
20110    var defaults = {
20111      _disable: [],
20112      _enable: [],
20113      allowInput: false,
20114      altFormat: "F j, Y",
20115      altInput: false,
20116      altInputClass: "form-control input",
20117      animate: typeof window === "object" && window.navigator.userAgent.indexOf("MSIE") === -1,
20118      ariaDateFormat: "F j, Y",
20119      clickOpens: true,
20120      closeOnSelect: true,
20121      conjunction: ", ",
20122      dateFormat: "Y-m-d",
20123      defaultHour: 12,
20124      defaultMinute: 0,
20125      defaultSeconds: 0,
20126      disable: [],
20127      disableMobile: false,
20128      enable: [],
20129      enableSeconds: false,
20130      enableTime: false,
20131      errorHandler: function errorHandler(err) {
20132        return typeof console !== "undefined" && console.warn(err);
20133      },
20134      getWeek: getWeek,
20135      hourIncrement: 1,
20136      ignoredFocusElements: [],
20137      inline: false,
20138      locale: "default",
20139      minuteIncrement: 5,
20140      mode: "single",
20141      nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewB
20141ox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
20142      noCalendar: false,
20143      now: new Date(),
20144      onChange: [],
20145      onClose: [],
20146      onDayCreate: [],
20147      onDestroy: [],
20148      onKeyDown: [],
20149      onMonthChange: [],
20150      onOpen: [],
20151      onParseConfig: [],
20152      onReady: [],
20153      onValueUpdate: [],
20154      onYearChange: [],
20155      onPreCalendarPosition: [],
20156      plugins: [],
20157      position: "auto",
20158      positionElement: undefined,
20159      prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
20160      shorthandCurrentMonth: false,
20161      showMonths: 1,
20162      static: false,
20163      time_24hr: false,
20164      weekNumbers: false,
20165      wrap: false
20166    };
20167
20168    function toggleClass(elem, className, bool) {
20169      if (bool === true) return elem.classList.add(className);
20170      elem.classList.remove(className);
20171    }
20172    function createElement(tag, className, content) {
20173      var e = window.document.createElement(tag);
20174      className = className || "";
20175      content = content || "";
20176      e.className = className;
20177      if (content !== undefined) e.textContent = content;
20178      return e;
20179    }
20180    function clearNode(node) {
20181      while (node.firstChild) {
20182        node.removeChild(node.firstChild);
20183      }
20184    }
20185    function findParent(node, condition) {
20186      if (condition(node)) return node;else if (node.parentNode) return findParent(node.parentNode, condition);
20187      return undefined;
20188    }
20189    function createNumberInput(inputClassName, opts) {
20190      var wrapper = createElement("div", "numInputWrapper"),
20191          numInput = createElement("input", "numInput " + inputClassName),
20192          arrowUp = createElement("span", "arrowUp"),
20193          arrowDown = createElement("span", "arrowDown");
20194      numInput.type = "text";
20195      numInput.pattern = "\\d*";
20196      if (opts !== undefined) for (var key in opts) {
20197        numInput.setAttribute(key, opts[key]);
20198      }
20199      wrapper.appendChild(numInput);
20200      wrapper.appendChild(arrowUp);
20201      wrapper.appendChild(arrowDown);
20202      return wrapper;
20203    }
20204
20205    if (typeof Object.assign !== "function") {
20206      Object.assign = function (target) {
20207        if (!target) {
20208          throw TypeError("Cannot convert undefined or null to object");
20209        }
20210
20211        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
20212          args[_key - 1] = arguments[_key];
20213        }
20214
20215        var _loop = function _loop() {
20216          var source = args[_i];
20217
20218          if (source) {
20219            Object.keys(source).forEach(function (key) {
20220              return target[key] = source[key];
20221            });
20222          }
20223        };
20224
20225        for (var _i = 0; _i < args.length; _i++) {
20226          _loop();
20227        }
20228
20229        return target;
20230      };
20231    }
20232
20233    var DEBOUNCED_CHANGE_MS = 300;
20234
20235    function FlatpickrInstance(element, instanceConfig) {
20236      var self = {
20237        config: Object.assign({}, flatpickr.defaultConfig),
20238        l10n: english
20239      };
20240      self.parseDate = createDateParser({
20241        config: self.config,
20242        l10n: self.l10n
20243      });
20244      self._handlers = [];
20245      self._bind = bind;
20246      self._setHoursFromDate = setHoursFromDate;
20247      self._positionCalendar = positionCalendar;
20248      self.changeMonth = changeMonth;
20249      self.changeYear = changeYear;
20250      self.clear = clear;
20251      self.close = close;
20252      self._createElement = createElement;
20253      self.destroy = destroy;
20254      self.isEnabled = isEnabled;
20255      self.jumpToDate = jumpToDate;
20256      self.open = open;
20257      self.redraw = redraw;
20258      self.set = set;
20259      self.setDate = setDate;
20260      self.toggle = toggle;
20261
20262      function setupHelperFunctions() {
20263        self.utils = {
20264          getDaysInMonth: function getDaysInMonth(month, yr) {
20265            if (month === void 0) {
20266              month = self.currentMonth;
20267            }
20268
20269            if (yr === void 0) {
20270              yr = self.currentYear;
20271            }
20272
20273            if (month === 1 && (yr % 4 === 0 && yr % 100 !== 0 || yr % 400 === 0)) return 29;
20274            return self.l10n.daysInMonth[month];
20275          }
20276        };
20277      }
20278
20279      function init() {
20280        self.element = self.input = element;
20281        self.isOpen = false;
20282        parseConfig();
20283        setupLocale();
20284        setupInputs();
20285        setupDates();
20286        setupHelperFunctions();
20287        if (!self.isMobile) build();
20288        bindEvents();
20289
20290        if (self.selectedDates.length || self.config.noCalendar) {
20291          if (self.config.enableTime) {
20292            setHoursFromDate(self.config.noCalendar ? self.latestSelectedDateObj || self.config.minDate : undefined);
20293          }
20294
20295          updateValue(false);
20296        }
20297
20298        setCalendarWidth();
20299        self.showTimeInput = self.selectedDates.length > 0 || self.config.noCalendar;
20300        var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
20301
20302        if (!self.isMobile && isSafari) {
20303          positionCalendar();
20304        }
20305
20306        triggerEvent("onReady");
20307      }
20308
20309      function bindToInstance(fn) {
20310        return fn.bind(self);
20311      }
20312
20313      function setCalendarWidth() {
20314        var config = self.config;
20315        if (config.weekNumbers === false && config.showMonths === 1) return;else if (config.noCalendar !== true) {
20316          window.requestAnimationFrame(function () {
20317            self.calendarContainer.style.visibility = "hidden";
20318            self.calendarContainer.style.display = "block";
20319
20320            if (self.daysContainer !== undefined) {
20321              var daysWidth = (self.days.offsetWidth + 1) * config.showMonths;
20322              self.daysContainer.style.width = daysWidth + "px";
20323              self.calendarContainer.style.width = daysWidth + (self.weekWrapper !== undefined ? self.weekWrapper.offsetWidth : 0) + "px";
20324              self.calendarContainer.style.removeProperty("visibility");
20325              self.calendarContainer.style.removeProperty("display");
20326            }
20327          });
20328        }
20329      }
20330
20331      function updateTime(e) {
20332        if (self.selectedDates.length === 0) return;
20333        if (e !== undefined && e.type !== "blur") timeWrapper(e);
20334        setHoursFromInputs();
20335        updateValue();
20336
20337        self._debouncedChange();
20338      }
20339
20340      function ampm2military(hour, amPM) {
20341        return hour % 12 + 12 * int(amPM === self.l10n.amPM[1]);
20342      }
20343
20344      function military2ampm(hour) {
20345        switch (hour % 24) {
20346          case 0:
20347          case 12:
20348            return 12;
20349
20350          default:
20351            return hour % 12;
20352        }
20353      }
20354
20355      function setHoursFromInputs() {
20356        if (self.hourElement === undefined || self.minuteElement === undefined) return;
20357        var hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24,
20358            minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60,
20359            seconds = self.secondElement !== undefined ? (parseInt(self.secondElement.value, 10) || 0) % 60 : 0;
20360
20361        if (self.amPM !== undefined) {
20362          hours = ampm2military(hours, self.amPM.textContent);
20363        }
20364
20365        var limitMinHours = self.config.minTime !== undefined || self.config.minDate && self.minDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.minDate, true) === 0;
20366        var limitMaxHours = self.config.maxTime !== undefined || self.config.maxDate && self.maxDateHasTime && self.latestSelectedDateObj && compareDates(self.latestSelectedDateObj, self.config.maxDate, true) === 0;
20367
20368        if (limitMaxHours) {
20369          var maxTime = self.config.maxTime !== undefined ? self.config.maxTime : self.config.maxDate;
20370          hours = Math.min(hours, maxTime.getHours());
20371          if (hours === maxTime.getHours()) minutes = Math.min(minutes, maxTime.getMinutes());
20372          if (minutes === maxTime.getMinutes()) seconds = Math.min(seconds, maxTime.getSeconds());
20373        }
20374
20375        if (limitMinHours) {
20376          var minTime = self.config.minTime !== undefined ? self.config.minTime : self.config.minDate;
20377          hours = Math.max(hours, minTime.getHours());
20378          if (hours === minTime.getHours()) minutes = Math.max(minutes, minTime.getMinutes());
20379          if (minutes === minTime.getMinutes()) seconds = Math.max(seconds, minTime.getSeconds());
20380        }
20381
20382        setHours(hours, minutes, seconds);
20383      }
20384
20385      function setHoursFromDate(dateObj) {
20386        var date = dateObj || self.latestSelectedDateObj;
20387        if (date) setHours(date.getHours(), date.getMinutes(), date.getSeconds());
20388      }
20389
20390      function setDefaultHours() {
20391        var hours = self.config.defaultHour;
20392        var minutes = self.config.defaultMinute;
20393        var seconds = self.config.defaultSeconds;
20394
20395        if (self.config.minDate !== undefined) {
20396          var min_hr = self.config.minDate.getHours();
20397          var min_minutes = self.config.minDate.getMinutes();
20398          hours = Math.max(hours, min_hr);
20399          if (hours === min_hr) minutes = Math.max(min_minutes, minutes);
20400          if (hours === min_hr && minutes === min_minutes) seconds = self.config.minDate.getSeconds();
20401        }
20402
20403        if (self.config.maxDate !== undefined) {
20404          var max_hr = self.config.maxDate.getHours();
20405          var max_minutes = self.config.maxDate.getMinutes();
20406          hours = Math.min(hours, max_hr);
20407          if (hours === max_hr) minutes = Math.min(max_minutes, minutes);
20408          if (hours === max_hr && minutes === max_minutes) seconds = self.config.maxDate.getSeconds();
20409        }
20410
20411        setHours(hours, minutes, seconds);
20412      }
20413
20414      function setHours(hours, minutes, seconds) {
20415        if (self.latestSelectedDateObj !== undefined) {
20416          self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0);
20417        }
20418
20419        if (!self.hourElement || !self.minuteElement || self.isMobile) return;
20420        self.hourElement.value = pad(!self.config.time_24hr ? (12 + hours) % 12 + 12 * int(hours % 12 === 0) : hours);
20421        self.minuteElement.value = pad(minutes);
20422        if (self.amPM !== undefined) self.amPM.textContent = self.l10n.amPM[int(hours >= 12)];
20423        if (self.secondElement !== undefined) self.secondElement.value = pad(seconds);
20424      }
20425
20426      function onYearInput(event) {
20427        var year = parseInt(event.target.value) + (event.delta || 0);
20428
20429        if (year / 1000 > 1 || event.key === "Enter" && !/[^\d]/.test(year.toString())) {
20430          changeYear(year);
20431        }
20432      }
20433
20434      function bind(element, event, handler, options) {
20435        if (event instanceof Array) return event.forEach(function (ev) {
20436          return bind(element, ev, handler, options);
20437        });
20438        if (element instanceof Array) return element.forEach(function (el) {
20439          return bind(el, event, handler, options);
20440        });
20441        element.addEventListener(event, handler, options);
20442
20443        self._handlers.push({
20444          element: element,
20445          event: event,
20446          handler: handler,
20447          options: options
20448        });
20449      }
20450
20451      function onClick(handler) {
20452        return function (evt) {
20453          evt.which === 1 && handler(evt);
20454        };
20455      }
20456
20457      function triggerChange() {
20458        triggerEvent("onChange");
20459      }
20460
20461      function bindEvents() {
20462        if (self.config.wrap) {
20463          ["open", "close", "toggle", "clear"].forEach(function (evt) {
20464            Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) {
20465              return bind(el, "click", self[evt]);
20466            });
20467          });
20468        }
20469
20470        if (self.isMobile) {
20471          setupMobile();
20472          return;
20473        }
20474
20475        var debouncedResize = debounce(onResize, 50);
vendor: 12,796 bytes, lines 20476-20760
20476        self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);
20477        if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent)) bind(self.daysContainer, "mouseover", function (e) {
20478          if (self.config.mode === "range") onMouseOver(e.target);
20479        });
20480        bind(window.document.body, "keydown", onKeyDown);
20481        if (!self.config.static) bind(self._input, "keydown", onKeyDown);
20482        if (!self.config.inline && !self.config.static) bind(window, "resize", debouncedResize);
20483        if (window.ontouchstart !== undefined) bind(window.document, "click", documentClick);else bind(window.document, "mousedown", onClick(documentClick));
20484        bind(window.document, "focus", documentClick, {
20485          capture: true
20486        });
20487
20488        if (self.config.clickOpens === true) {
20489          bind(self._input, "focus", self.open);
20490          bind(self._input, "mousedown", onClick(self.open));
20491        }
20492
20493        if (self.daysContainer !== undefined) {
20494          bind(self.monthNav, "mousedown", onClick(onMonthNavClick));
20495          bind(self.monthNav, ["keyup", "increment"], onYearInput);
20496          bind(self.daysContainer, "mousedown", onClick(selectDate));
20497        }
20498
20499        if (self.timeContainer !== undefined && self.minuteElement !== undefined && self.hourElement !== undefined) {
20500          var selText = function selText(e) {
20501            return e.target.select();
20502          };
20503
20504          bind(self.timeContainer, ["increment"], updateTime);
20505          bind(self.timeContainer, "blur", updateTime, {
20506            capture: true
20507          });
20508          bind(self.timeContainer, "mousedown", onClick(timeIncrement));
20509          bind([self.hourElement, self.minuteElement], ["focus", "click"], selText);
20510          if (self.secondElement !== undefined) bind(self.secondElement, "focus", function () {
20511            return self.secondElement && self.secondElement.select();
20512          });
20513
20514          if (self.amPM !== undefined) {
20515            bind(self.amPM, "mousedown", onClick(function (e) {
20516              updateTime(e);
20517              triggerChange();
20518            }));
20519          }
20520        }
20521      }
20522
20523      function jumpToDate(jumpDate) {
20524        var jumpTo = jumpDate !== undefined ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate && self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now);
20525
20526        try {
20527          if (jumpTo !== undefined) {
20528            self.currentYear = jumpTo.getFullYear();
20529            self.currentMonth = jumpTo.getMonth();
20530          }
20531        } catch (e) {
20532          e.message = "Invalid date supplied: " + jumpTo;
20533          self.config.errorHandler(e);
20534        }
20535
20536        self.redraw();
20537      }
20538
20539      function timeIncrement(e) {
20540        if (~e.target.className.indexOf("arrow")) incrementNumInput(e, e.target.classList.contains("arrowUp") ? 1 : -1);
20541      }
20542
20543      function incrementNumInput(e, delta, inputElem) {
20544        var target = e && e.target;
20545        var input = inputElem || target && target.parentNode && target.parentNode.firstChild;
20546        var event = createEvent("increment");
20547        event.delta = delta;
20548        input && input.dispatchEvent(event);
20549      }
20550
20551      function build() {
20552        var fragment = window.document.createDocumentFragment();
20553        self.calendarContainer = createElement("div", "flatpickr-calendar");
20554        self.calendarContainer.tabIndex = -1;
20555
20556        if (!self.config.noCalendar) {
20557          fragment.appendChild(buildMonthNav());
20558          self.innerContainer = createElement("div", "flatpickr-innerContainer");
20559
20560          if (self.config.weekNumbers) {
20561            var _buildWeeks = buildWeeks(),
20562                weekWrapper = _buildWeeks.weekWrapper,
20563                weekNumbers = _buildWeeks.weekNumbers;
20564
20565            self.innerContainer.appendChild(weekWrapper);
20566            self.weekNumbers = weekNumbers;
20567            self.weekWrapper = weekWrapper;
20568          }
20569
20570          self.rContainer = createElement("div", "flatpickr-rContainer");
20571          self.rContainer.appendChild(buildWeekdays());
20572
20573          if (!self.daysContainer) {
20574            self.daysContainer = createElement("div", "flatpickr-days");
20575            self.daysContainer.tabIndex = -1;
20576          }
20577
20578          buildDays();
20579          self.rContainer.appendChild(self.daysContainer);
20580          self.innerContainer.appendChild(self.rContainer);
20581          fragment.appendChild(self.innerContainer);
20582        }
20583
20584        if (self.config.enableTime) {
20585          fragment.appendChild(buildTime());
20586        }
20587
20588        toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range");
20589        toggleClass(self.calendarContainer, "animate", self.config.animate === true);
20590        toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1);
20591        self.calendarContainer.appendChild(fragment);
20592        var customAppend = self.config.appendTo !== undefined && self.config.appendTo.nodeType !== undefined;
20593
20594        if (self.config.inline || self.config.static) {
20595          self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
20596
20597          if (self.config.inline) {
20598            if (!customAppend && self.element.parentNode) self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling);else if (self.config.appendTo !== undefined) self.config.appendTo.appendChild(self.calendarContainer);
20599          }
20600
20601          if (self.config.static) {
20602            var wrapper = createElement("div", "flatpickr-wrapper");
20603            if (self.element.parentNode) self.element.parentNode.insertBefore(wrapper, self.element);
20604            wrapper.appendChild(self.element);
20605            if (self.altInput) wrapper.appendChild(self.altInput);
20606            wrapper.appendChild(self.calendarContainer);
20607          }
20608        }
20609
20610        if (!self.config.static && !self.config.inline) (self.config.appendTo !== undefined ? self.config.appendTo : window.document.body).appendChild(self.calendarContainer);
20611      }
20612
20613      function createDay(className, date, dayNumber, i) {
20614        var dateIsEnabled = isEnabled(date, true),
20615            dayElement = createElement("span", "flatpickr-day " + className, date.getDate().toString());
20616        dayElement.dateObj = date;
20617        dayElement.$i = i;
20618        dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat));
20619
20620        if (className.indexOf("hidden") === -1 && compareDates(date, self.now) === 0) {
20621          self.todayDateElem = dayElement;
20622          dayElement.classList.add("today");
20623          dayElement.setAttribute("aria-current", "date");
20624        }
20625
20626        if (dateIsEnabled) {
20627          dayElement.tabIndex = -1;
20628
20629          if (isDateSelected(date)) {
20630            dayElement.classList.add("selected");
20631            self.selectedDateElem = dayElement;
20632
20633            if (self.config.mode === "range") {
20634              toggleClass(dayElement, "startRange", self.selectedDates[0] && compareDates(date, self.selectedDates[0], true) === 0);
20635              toggleClass(dayElement, "endRange", self.selectedDates[1] && compareDates(date, self.selectedDates[1], true) === 0);
20636              if (className === "nextMonthDay") dayElement.classList.add("inRange");
20637            }
20638          }
20639        } else {
20640          dayElement.classList.add("disabled");
20641        }
20642
20643        if (self.config.mode === "range") {
20644          if (isDateInRange(date) && !isDateSelected(date)) dayElement.classList.add("inRange");
20645        }
20646
20647        if (self.weekNumbers && self.config.showMonths === 1 && className !== "prevMonthDay" && dayNumber % 7 === 1) {
20648          self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>");
20649        }
20650
20651        triggerEvent("onDayCreate", dayElement);
20652        return dayElement;
20653      }
20654
20655      function focusOnDayElem(targetNode) {
20656        targetNode.focus();
20657        if (self.config.mode === "range") onMouseOver(targetNode);
20658      }
20659
20660      function getFirstAvailableDay(delta) {
20661        var startMonth = delta > 0 ? 0 : self.config.showMonths - 1;
20662        var endMonth = delta > 0 ? self.config.showMonths : -1;
20663
20664        for (var m = startMonth; m != endMonth; m += delta) {
20665          var month = self.daysContainer.children[m];
20666          var startIndex = delta > 0 ? 0 : month.children.length - 1;
20667          var endIndex = delta > 0 ? month.children.length : -1;
20668
20669          for (var i = startIndex; i != endIndex; i += delta) {
20670            var c = month.children[i];
20671            if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj)) return c;
20672          }
20673        }
20674
20675        return undefined;
20676      }
20677
20678      function getNextAvailableDay(current, delta) {
20679        var givenMonth = current.className.indexOf("Month") === -1 ? current.dateObj.getMonth() : self.currentMonth;
20680        var endMonth = delta > 0 ? self.config.showMonths : -1;
20681        var loopDelta = delta > 0 ? 1 : -1;
20682
20683        for (var m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) {
20684          var month = self.daysContainer.children[m];
20685          var startIndex = givenMonth - self.currentMonth === m ? current.$i + delta : delta < 0 ? month.children.length - 1 : 0;
20686          var numMonthDays = month.children.length;
20687
20688          for (var i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) {
20689            var c = month.children[i];
20690            if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj) && Math.abs(current.$i - i) >= Math.abs(delta)) return focusOnDayElem(c);
20691          }
20692        }
20693
20694        self.changeMonth(loopDelta);
20695        focusOnDay(getFirstAvailableDay(loopDelta), 0);
20696        return undefined;
20697      }
20698
20699      function focusOnDay(current, offset) {
20700        var dayFocused = isInView(document.activeElement);
20701        var startElem = current !== undefined ? current : dayFocused ? document.activeElement : self.selectedDateElem !== undefined && isInView(self.selectedDateElem) ? self.selectedDateElem : self.todayDateElem !== undefined && isInView(self.todayDateElem) ? self.todayDateElem : getFirstAvailableDay(offset > 0 ? 1 : -1);
20702        if (startElem === undefined) return self._input.focus();
20703        if (!dayFocused) return focusOnDayElem(startElem);
20704        getNextAvailableDay(startElem, offset);
20705      }
20706
20707      function buildMonthDays(year, month) {
20708        var firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7;
20709        var prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12);
20710        var daysInMonth = self.utils.getDaysInMonth(month),
20711            days = window.document.createDocumentFragment(),
20712            isMultiMonth = self.config.showMonths > 1,
20713            prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay",
20714            nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay";
20715        var dayNumber = prevMonthDays + 1 - firstOfMonth,
20716            dayIndex = 0;
20717
20718        for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) {
20719          days.appendChild(createDay(prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex));
20720        }
20721
20722        for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++, dayIndex++) {
20723          days.appendChild(createDay("", new Date(year, month, dayNumber), dayNumber, dayIndex));
20724        }
20725
20726        for (var dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth && (self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) {
20727          days.appendChild(createDay(nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth), dayNum, dayIndex));
20728        }
20729
20730        var dayContainer = createElement("div", "dayContainer");
20731        dayContainer.appendChild(days);
20732        return dayContainer;
20733      }
20734
20735      function buildDays() {
20736        if (self.daysContainer === undefined) {
20737          return;
20738        }
20739
20740        clearNode(self.daysContainer);
20741        if (self.weekNumbers) clearNode(self.weekNumbers);
20742        var frag = document.createDocumentFragment();
20743
20744        for (var i = 0; i < self.config.showMonths; i++) {
20745          var d = new Date(self.currentYear, self.currentMonth, 1);
20746          d.setMonth(self.currentMonth + i);
20747          frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth()));
20748        }
20749
20750        self.daysContainer.appendChild(frag);
20751        self.days = self.daysContainer.firstChild;
20752      }
20753
20754      function buildMonth() {
20755        var container = createElement("div", "flatpickr-month");
20756        var monthNavFragment = window.document.createDocumentFragment();
20757        var monthElement = createElement("span", "cur-month");
20758        var yearInput = createNumberInput("cur-year", {
20759          tabindex: "-1"
20760        });
20761        var yearElement = yearInput.childNodes[0];
20762        yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel);
20763        if (self.config.minDate) yearElement.setAttribute("data-min", self.config.minDate.getFullYear().toString());
20764
20765        if (self.config.maxDate) {
20766          yearElement.setAttribute("data-max", self.config.maxDate.getFullYear().toString());
20767          yearElement.disabled = !!self.config.minDate && self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
20768        }
20769
20770        var currentMonth = createElement("div", "flatpickr-current-month");
20771        if (self.config.yearFirst) {
20772          currentMonth.appendChild(yearInput);
20773          currentMonth.appendChild(monthElement);
20774        } else {
20775          currentMonth.appendChild(monthElement);
20776          currentMonth.appendChild(yearInput);
20777        }
20778        monthNavFragment.appendChild(currentMonth);
20779        container.appendChild(monthNavFragment);
20780        return {
20781          container: container,
20782          yearElement: yearElement,
20783          monthElement: monthElement
20784        };
20785      }
20786
20787      function buildMonths() {
20788        clearNode(self.monthNav);
20789        self.monthNav.appendChild(self.prevMonthNav);
20790
20791        for (var m = self.config.showMonths; m--;) {
20792          var month = buildMonth();
20793          self.yearElements.push(month.yearElement);
20794          self.monthElements.push(month.monthElement);
20795          self.monthNav.appendChild(month.container);
20796        }
20797
20798        self.monthNav.appendChild(self.nextMonthNav);
20799      }
20800
20801      function buildMonthNav() {
20802        self.monthNav = createElement("div", "flatpickr-months");
20803        self.yearElements = [];
20804        self.monthElements = [];
20805        self.prevMonthNav = createElement("span", "flatpickr-prev-month");
20806        self.prevMonthNav.innerHTML = self.config.prevArrow;
20807        self.nextMonthNav = createElement("span", "flatpickr-next-month");
20808        self.nextMonthNav.innerHTML = self.config.nextArrow;
20809        buildMonths();
20810        Object.defineProperty(self, "_hidePrevMonthArrow", {
20811          get: function get() {
20812            return self.__hidePrevMonthArrow;
20813          },
20814          set: function set(bool) {
20815            if (self.__hidePrevMonthArrow !== bool) {
20816              toggleClass(self.prevMonthNav, "disabled", bool);
20817              self.__hidePrevMonthArrow = bool;
20818            }
20819          }
20820        });
20821        Object.defineProperty(self, "_hideNextMonthArrow", {
20822          get: function get() {
20823            return self.__hideNextMonthArrow;
20824          },
20825          set: function set(bool) {
20826            if (self.__hideNextMonthArrow !== bool) {
20827              toggleClass(self.nextMonthNav, "disabled", bool);
20828              self.__hideNextMonthArrow = bool;
20829            }
20830          }
20831        });
20832        self.currentYearElement = self.yearElements[0];
20833        updateNavigationCurrentMonth();
20834        return self.monthNav;
20835      }
20836
20837      function buildTime() {
20838        self.calendarContainer.classList.add("hasTime");
20839        if (self.config.noCalendar) self.calendarContainer.classList.add("noCalendar");
20840        self.timeContainer = createElement("div", "flatpickr-time");
20841        self.timeContainer.tabIndex = -1;
20842        var separator = createElement("span", "flatpickr-time-separator", ":");
20843        var hourInput = createNumberInput("flatpickr-hour");
20844        self.hourElement = hourInput.childNodes[0];
20845        var minuteInput = createNumberInput("flatpickr-minute");
20846        self.minuteElement = minuteInput.childNodes[0];
20847        self.hourElement.tabIndex = self.minuteElement.tabIndex = -1;
20848        self.hourElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getHours() : self.config.time_24hr ? self.config.defaultHour : military2ampm(self.config.defaultHour));
20849        self.minuteElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getMinutes() : self.config.defaultMinute);
20850        self.hourElement.setAttribute("data-step", self.config.hourIncrement.toString());
20851        self.minuteElement.setAttribute("data-step", self.config.minuteIncrement.toString());
20852        self.hourElement.setAttribute("data-min", self.config.time_24hr ? "0" : "1");
20853        self.hourElement.setAttribute("data-max", self.config.time_24hr ? "23" : "12");
20854        self.minuteElement.setAttribute("data-min", "0");
20855        self.minuteElement.setAttribute("data-max", "59");
20856        self.timeContainer.appendChild(hourInput);
20857        self.timeContainer.appendChild(separator);
20858        self.timeContainer.appendChild(minuteInput);
20859        if (self.config.time_24hr) self.timeContainer.classList.add("time24hr");
20860
20861        if (self.config.enableSeconds) {
20862          self.timeContainer.classList.add("hasSeconds");
20863          var secondInput = createNumberInput("flatpickr-second");
20864          self.secondElement = secondInput.childNodes[0];
20865          self.secondElement.value = pad(self.latestSelectedDateObj ? self.latestSelectedDateObj.getSeconds() : self.config.defaultSeconds);
20866          self.secondElement.setAttribute("data-step", self.minuteElement.getAttribute("data-step"));
20867          self.secondElement.setAttribute("data-min", self.minuteElement.getAttribute("data-min"));
20868          self.secondElement.setAttribute("data-max", self.minuteElement.getAttribute("data-max"));
20869          self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":"));
20870          self.timeContainer.appendChild(secondInput);
20871        }
20872
20873        if (!self.config.time_24hr) {
20874          self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int((self.latestSelectedDateObj ? self.hourElement.value : self.config.defaultHour) > 11)]);
20875          //self.amPM.title = self.l10n.toggleTitle;
20876          self.amPM.tabIndex = -1;
20877          self.timeContainer.appendChild(self.amPM);
20878        }
20879
20880        return self.timeContainer;
20881      }
20882
20883      function buildWeekdays() {
20884        if (!self.weekdayContainer) self.weekdayContainer = createElement("div", "flatpickr-weekdays");else clearNode(self.weekdayContainer);
20885
20886        for (var i = self.config.showMonths; i--;) {
20887          var container = createElement("div", "flatpickr-weekdaycontainer");
20888          self.weekdayContainer.appendChild(container);
20889        }
20890
20891        updateWeekdays();
20892        return self.weekdayContainer;
20893      }
20894
20895      function updateWeekdays() {
20896        var firstDayOfWeek = self.l10n.firstDayOfWeek;
20897        var weekdays = self.l10n.weekdays.shorthand.concat();
20898
20899        if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
20900          weekdays = weekdays.splice(firstDayOfWeek, weekdays.length).concat(weekdays.splice(0, firstDayOfWeek));
20901        }
20902
20903        for (var i = self.config.showMonths; i--;) {
20904          self.weekdayContainer.children[i].innerHTML = "\n      <span class=flatpickr-weekday>\n        " + weekdays.join("</span><span class=flatpickr-weekday>") + "\n      </span>\n      ";
20905        }
20906      }
20907
20908      function buildWeeks() {
20909        self.calendarContainer.classList.add("hasWeeks");
20910        var weekWrapper = createElement("div", "flatpickr-weekwrapper");
20911        weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation));
20912        var weekNumbers = createElement("div", "flatpickr-weeks");
20913        weekWrapper.appendChild(weekNumbers);
20914        return {
20915          weekWrapper: weekWrapper,
20916          weekNumbers: weekNumbers
20917        };
20918      }
20919
20920      function changeMonth(value, is_offset) {
20921        if (is_offset === void 0) {
20922          is_offset = true;
20923        }
20924
20925        var delta = is_offset ? value : value - self.currentMonth;
20926        if (delta < 0 && self._hidePrevMonthArrow === true || delta > 0 && self._hideNextMonthArrow === true) return;
20927        self.currentMonth += delta;
20928
20929        if (self.currentMonth < 0 || self.currentMonth > 11) {
20930          self.currentYear += self.currentMonth > 11 ? 1 : -1;
20931          self.currentMonth = (self.currentMonth + 12) % 12;
20932          triggerEvent("onYearChange");
20933        }
20934
20935        buildDays();
20936        triggerEvent("onMonthChange");
20937        updateNavigationCurrentMonth();
20938      }
20939
20940      function clear(triggerChangeEvent) {
20941        if (triggerChangeEvent === void 0) {
20942          triggerChangeEvent = true;
20943        }
20944
20945        self.input.value = "";
20946        if (self.altInput !== undefined) self.altInput.value = "";
20947        if (self.mobileInput !== undefined) self.mobileInput.value = "";
20948        self.selectedDates = [];
20949        self.latestSelectedDateObj = undefined;
20950        self.showTimeInput = false;
20951
20952        if (self.config.enableTime === true) {
20953          setDefaultHours();
20954        }
20955
20956        self.redraw();
20957        if (triggerChangeEvent) triggerEvent("onChange");
20958      }
20959
20960      function close() {
20961        self.isOpen = false;
20962
20963        if (!self.isMobile) {
20964          self.calendarContainer.classList.remove("open");
20965
20966          self._input.classList.remove("active");
20967        }
20968
20969        triggerEvent("onClose");
20970      }
20971
20972      function destroy() {
20973        if (self.config !== undefined) triggerEvent("onDestroy");
20974
20975        for (var i = self._handlers.length; i--;) {
20976          var h = self._handlers[i];
20977          h.element.removeEventListener(h.event, h.handler, h.options);
20978        }
20979
20980        self._handlers = [];
20981
20982        if (self.mobileInput) {
20983          if (self.mobileInput.parentNode) self.mobileInput.parentNode.removeChild(self.mobileInput);
20984          self.mobileInput = undefined;
20985        } else if (self.calendarContainer && self.calendarContainer.parentNode) self.calendarContainer.parentNode.removeChild(self.calendarContainer);
20986
20987        if (self.altInput) {
20988          self.input.type = "text";
20989          if (self.altInput.parentNode) self.altInput.parentNode.removeChild(self.altInput);
20990          delete self.altInput;
20991        }
20992
20993        if (self.input) {
20994          self.input.type = self.input._type;
20995          self.input.classList.remove("flatpickr-input");
20996          self.input.removeAttribute("readonly");
20997          self.input.value = "";
20998        }
20999
21000        ["_showTimeInput", "latestSelectedDateObj", "_hideNextMonthArrow", "_hidePrevMonthArrow", "__hideNextMonthArrow", "__hidePrevMonthArrow", "isMobile", "isOpen", "selectedDateElem", "minDateHasTime", "maxDateHasTime", "days", "daysContainer", "_input", "_positionElement", "innerContainer", "rContainer", "monthNav", "todayDateElem", "calendarContainer", "weekdayContainer", "prevMonthNav", "nextMonthNav", "currentMonthElement", "currentYearElement", "navigationCurrentMonth", "selectedDateElem", "config"].forEach(function (k) {
21001          try {
21002            delete self[k];
21003          } catch (_) {}
21004        });
21005      }
21006
21007      function isCalendarElem(elem) {
21008        if (self.config.appendTo && self.config.appendTo.contains(elem)) return true;
21009        return self.calendarContainer.contains(elem);
21010      }
21011
21012      function documentClick(e) {
21013        if (self.isOpen && !self.config.inline) {
21014          var isCalendarElement = isCalendarElem(e.target);
21015          var isInput = e.target === self.input || e.target === self.altInput || self.element.contains(e.target) || e.path && e.path.indexOf && (~e.path.indexOf(self.input) || ~e.path.indexOf(self.altInput));
21016          var lostFocus = e.type === "blur" ? isInput && e.relatedTarget && !isCalendarElem(e.relatedTarget) : !isInput && !isCalendarElement;
21017          var isIgnored = !self.config.ignoredFocusElements.some(function (elem) {
21018            return elem.contains(e.target);
21019          });
21020
21021          if (lostFocus && isIgnored) {
21022            self.close();
21023
21024            if (self.config.mode === "range" && self.selectedDates.length === 1) {
21025              self.clear(false);
21026              self.redraw();
21027            }
21028          }
21029        }
21030      }
21031
21032      function changeYear(newYear) {
21033        if (!newYear || self.config.minDate && newYear < self.config.minDate.getFullYear() || self.config.maxDate && newYear > self.config.maxDate.getFullYear()) return;
21034        var newYearNum = newYear,
21035            isNewYear = self.currentYear !== newYearNum;
21036        self.currentYear = newYearNum || self.currentYear;
21037
21038        if (self.config.maxDate && self.currentYear === self.config.maxDate.getFullYear()) {
21039          self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth);
21040        } else if (self.config.minDate && self.currentYear === self.config.minDate.getFullYear()) {
21041          self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth);
21042        }
21043
21044        if (isNewYear) {
21045          self.redraw();
21046          triggerEvent("onYearChange");
21047        }
21048      }
21049
21050      function isEnabled(date, timeless) {
21051        if (timeless === void 0) {
21052          timeless = true;
21053        }
21054
21055        var dateToCheck = self.parseDate(date, undefined, timeless);
21056        if (self.config.minDate && dateToCheck && compareDates(dateToCheck, self.config.minDate, timeless !== undefined ? timeless : !self.minDateHasTime) < 0 || self.config.maxDate && dateToCheck && compareDates(dateToCheck, self.config.maxDate, timeless !== undefined ? timeless : !self.maxDateHasTime) > 0) return false;
21057        if (self.config.enable.length === 0 && self.config.disable.length === 0) return true;
21058        if (dateToCheck === undefined) return false;
21059        var bool = self.config.enable.length > 0,
21060            array = bool ? self.config.enable : self.config.disable;
21061
21062        for (var i = 0, d; i < array.length; i++) {
21063          d = array[i];
21064          if (typeof d === "function" && d(dateToCheck)) return bool;else if (d instanceof Date && dateToCheck !== undefined && d.getTime() === dateToCheck.getTime()) return bool;else if (typeof d === "string" && dateToCheck !== undefined) {
21065            var parsed = self.parseDate(d, undefined, true);
21066            return parsed && parsed.getTime() === dateToCheck.getTime() ? bool : !bool;
21067          } else if (typeof d === "object" && dateToCheck !== undefined && d.from && d.to && dateToCheck.getTime() >= d.from.getTime() && dateToCheck.getTime() <= d.to.getTime()) return bool;
21068        }
21069
21070        return !bool;
21071      }
21072
21073      function isInView(elem) {
21074        if (self.daysContainer !== undefined) return elem.className.indexOf("hidden") === -1 && self.daysContainer.contains(elem);
21075        return false;
21076      }
21077
21078      function onKeyDown(e) {
21079        var isInput = e.target === self._input;
21080        var allowInput = self.config.allowInput;
21081        var allowKeydown = self.isOpen && (!allowInput || !isInput);
21082        var allowInlineKeydown = self.config.inline && isInput && !allowInput;
21083
21084        if (e.keyCode === 13 && isInput) {
21085          if (allowInput) {
21086            self.setDate(self._input.value, true, e.target === self.altInput ? self.config.altFormat : self.config.dateFormat);
21087            return e.target.blur();
21088          } else self.open();
21089        } else if (isCalendarElem(e.target) || allowKeydown || allowInlineKeydown) {
21090          var isTimeObj = !!self.timeContainer && self.timeContainer.contains(e.target);
21091
21092          switch (e.keyCode) {
21093            case 13:
21094              if (isTimeObj) updateTime();else selectDate(e);
21095              break;
21096
21097            case 27:
21098              e.preventDefault();
21099              focusAndClose();
21100              break;
21101
21102            case 8:
21103            case 46:
21104              if (isInput && !self.config.allowInput) {
21105                e.preventDefault();
21106                self.clear();
21107              }
21108
21109              break;
21110
21111            case 37:
21112            case 39:
21113              if (!isTimeObj) {
21114                e.preventDefault();
21115
21116                if (self.daysContainer !== undefined && (allowInput === false || isInView(document.activeElement))) {
21117                  var _delta = e.keyCode === 39 ? 1 : -1;
21118
21119                  if (!e.ctrlKey) focusOnDay(undefined, _delta);else {
21120                    changeMonth(_delta);
21121                    focusOnDay(getFirstAvailableDay(1), 0);
21122                  }
21123                }
21124              } else if (self.hourElement) self.hourElement.focus();
21125
21126              break;
21127
21128            case 38:
21129            case 40:
21130              e.preventDefault();
21131              var delta = e.keyCode === 40 ? 1 : -1;
21132
21133              if (self.daysContainer) {
21134                if (e.ctrlKey) {
21135                  changeYear(self.currentYear - delta);
21136                  focusOnDay(getFirstAvailableDay(1), 0);
21137                } else if (!isTimeObj) focusOnDay(undefined, delta * 7);
21138              } else if (self.config.enableTime) {
21139                if (!isTimeObj && self.hourElement) self.hourElement.focus();
21140                updateTime(e);
21141
21142                self._debouncedChange();
21143              }
21144
21145              break;
21146
21147            case 9:
21148              if (!isTimeObj) break;
21149              var elems = [self.hourElement, self.minuteElement, self.secondElement, self.amPM
21149].filter(function (x) {
21150                return x;
21151              });
21152              var i = elems.indexOf(e.target);
21153
21154              if (i !== -1) {
21155                var target = elems[i + (e.shiftKey ? -1 : 1)];
21156
21157                if (target !== undefined) {
21158                  e.preventDefault();
21159                  target.focus();
21160                }
21161              }
21162
21163              break;
21164
21165            default:
21166              break;
21167          }
21168        }
21169
21170        if (self.amPM !== undefined && e.target === self.amPM) {
21171          switch (e.key) {
21172            case self.l10n.amPM[0].charAt(0):
21173            case self.l10n.amPM[0].charAt(0).toLowerCase():
21174              self.amPM.textContent = self.l10n.amPM[0];
21175              setHoursFromInputs();
21176              updateValue();
21177              break;
21178
21179            case self.l10n.amPM[1].charAt(0):
21180            case self.l10n.amPM[1].charAt(0).toLowerCase():
21181              self.amPM.textContent = self.l10n.amPM[1];
21182              setHoursFromInputs();
21183              updateValue();
21184              break;
21185          }
21186        }
21187
21188        triggerEvent("onKeyDown", e);
21189      }
21190
21191      function onMouseOver(elem) {
21192        if (self.selectedDates.length !== 1 || !elem.classList.contains("flatpickr-day") || elem.classList.contains("disabled")) return;
21193        var hoverDate = elem.dateObj.getTime(),
21194            initialDate = self.parseDate(self.selectedDates[0], undefined, true).getTime(),
21195            rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()),
21196            rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime());
21197        var containsDisabled = false;
21198        var minRange = 0,
21199            maxRange = 0;
21200
21201        for (var t = rangeStartDate; t < rangeEndDate; t += duration.DAY) {
21202          if (!isEnabled(new Date(t), true)) {
21203            containsDisabled = containsDisabled || t > rangeStartDate && t < rangeEndDate;
21204            if (t < initialDate && (!minRange || t > minRange)) minRange = t;else if (t > initialDate && (!maxRange || t < maxRange)) maxRange = t;
21205          }
21206        }
21207
21208        for (var m = 0; m < self.config.showMonths; m++) {
21209          var month = self.daysContainer.children[m];
21210          var prevMonth = self.daysContainer.children[m - 1];
21211
21212          var _loop = function _loop(i, l) {
21213            var dayElem = month.children[i],
21214                date = dayElem.dateObj;
21215            var timestamp = date.getTime();
21216            var outOfRange = minRange > 0 && timestamp < minRange || maxRange > 0 && timestamp > maxRange;
21217
21218            if (outOfRange) {
21219              dayElem.classList.add("notAllowed");
21220              ["inRange", "startRange", "endRange"].forEach(function (c) {
21221                dayElem.classList.remove(c);
21222              });
21223              return "continue";
21224            } else if (containsDisabled && !outOfRange) return "continue";
21225
21226            ["startRange", "inRange", "endRange", "notAllowed"].forEach(function (c) {
21227              dayElem.classList.remove(c);
21228            });
21229            elem.classList.add(hoverDate < self.selectedDates[0].getTime() ? "startRange" : "endRange");
21230
21231            if (month.contains(elem) || !(m > 0 && prevMonth && prevMonth.lastChild.dateObj.getTime() >= timestamp)) {
21232              if (initialDate < hoverDate && timestamp === initialDate) dayElem.classList.add("startRange");else if (initialDate > hoverDate && timestamp === initialDate) dayElem.classList.add("endRange");
21233              if (timestamp >= minRange && (maxRange === 0 || timestamp <= maxRange) && isBetween(timestamp, initialDate, hoverDate)) dayElem.classList.add("inRange");
21234            }
21235          };
21236
21237          for (var i = 0, l = month.children.length; i < l; i++) {
21238            var _ret = _loop(i, l);
21239
21240            if (_ret === "continue") continue;
21241          }
21242        }
21243      }
21244
21245      function onResize() {
21246        if (self.isOpen && !self.config.static && !self.config.inline) positionCalendar();
21247      }
21248
21249      function open(e, positionElement) {
21250        if (positionElement === void 0) {
21251          positionElement = self._input;
21252        }
21253
21254        if (self.isMobile === true) {
21255          if (e) {
21256            e.preventDefault();
21257            e.target && e.target.blur();
21258          }
21259
21260          setTimeout(function () {
21261            self.mobileInput !== undefined && self.mobileInput.focus();
21262          }, 0);
21263          triggerEvent("onOpen");
21264          return;
21265        }
21266
21267        if (self._input.disabled || self.config.inline) return;
21268        var wasOpen = self.isOpen;
21269        self.isOpen = true;
21270
21271        if (!wasOpen) {
21272          self.calendarContainer.classList.add("open");
21273
21274          self._input.classList.add("active");
21275
21276          triggerEvent("onOpen");
21277          positionCalendar(positionElement);
21278        }
21279
21280        if (self.config.enableTime === true && self.config.noCalendar === true) {
21281          if (self.selectedDates.length === 0) {
21282            self.setDate(self.config.minDate !== undefined ? new Date(self.config.minDate.getTime()) : new Date(), false);
21283            setDefaultHours();
21284            updateValue();
21285          }
21286
21287          if (self.config.allowInput === false && (e === undefined || !self.timeContainer.contains(e.relatedTarget))) {
21288            setTimeout(function () {
21289              return self.hourElement.select();
21290            }, 50);
21291          }
21292        }
21293      }
21294
21295      function minMaxDateSetter(type) {
21296        return function (date) {
21297          var dateObj = self.config["_" + type + "Date"] = self.parseDate(date, self.config.dateFormat);
21298          var inverseDateObj = self.config["_" + (type === "min" ? "max" : "min") + "Date"];
21299
21300          if (dateObj !== undefined) {
21301            self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] = dateObj.getHours() > 0 || dateObj.getMinutes() > 0 || dateObj.getSeconds() > 0;
21302          }
21303
21304          if (self.selectedDates) {
21305            self.selectedDates = self.selectedDates.filter(function (d) {
21306              return isEnabled(d);
21307            });
21308            if (!self.selectedDates.length && type === "min") setHoursFromDate(dateObj);
21309            updateValue();
21310          }
21311
21312          if (self.daysContainer) {
21313            redraw();
21314            if (dateObj !== undefined) self.currentYearElement[type] = dateObj.getFullYear().toString();else self.currentYearElement.removeAttribute(type);
21315            self.currentYearElement.disabled = !!inverseDateObj && dateObj !== undefined && inverseDateObj.getFullYear() === dateObj.getFullYear();
21316          }
21317        };
21318      }
21319
21320      function parseConfig() {
21321        var boolOpts = ["wrap", "weekNumbers", "allowInput", "clickOpens", "time_24hr", "enableTime", "noCalendar", "altInput", "shorthandCurrentMonth", "inline", "static", "enableSeconds", "disableMobile",
21322          "yearFirst"];
21323        var hooks = ["onChange", "onClose", "onDayCreate", "onDestroy", "onKeyDown", "onMonthChange", "onOpen", "onParseConfig", "onReady", "onValueUpdate", "onYearChange", "onPreCalendarPosition"];
21324        var userConfig = Object.assign({}, instanceConfig, JSON.parse(JSON.stringify(element.dataset || {})));
21325        var formats$$1 = {};
21326        self.config.parseDate = userConfig.parseDate;
21327        self.config.formatDate = userConfig.formatDate;
21328        Object.defineProperty(self.config, "enable", {
21329          get: function get() {
21330            return self.config._enable;
21331          },
21332          set: function set(dates) {
21333            self.config._enable = parseDateRules(dates);
21334          }
21335        });
21336        Object.defineProperty(self.config, "disable", {
21337          get: function get() {
21338            return self.config._disable;
21339          },
21340          set: function set(dates) {
21341            self.config._disable = parseDateRules(dates);
21342          }
21343        });
21344        var timeMode = userConfig.mode === "time";
21345
21346        if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) {
21347          formats$$1.dateFormat = userConfig.noCalendar || timeMode ? "H:i" + (userConfig.enableSeconds ? ":S" : "") : flatpickr.defaultConfig.dateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : "");
21348        }
21349
21350        if (userConfig.altInput && (userConfig.enableTime || timeMode) && !userConfig.altFormat) {
21351          formats$$1.altFormat = userConfig.noCalendar || timeMode ? "h:i" + (userConfig.enableSeconds ? ":S K" : " K") : flatpickr.defaultConfig.altFormat + (" h:i" 
21351+ (userConfig.enableSeconds ? ":S" : "") + " K");
21352        }
21353
21354        Object.defineProperty(self.config, "minDate", {
21355          get: function get() {
21356            return self.config._minDate;
21357          },
21358          set: minMaxDateSetter("min")
21359        });
21360        Object.defineProperty(self.config, "maxDate", {
21361          get: function get() {
21362            return self.config._maxDate;
21363          },
21364          set: minMaxDateSetter("max")
21365        });
21366
21367        var minMaxTimeSetter = function minMaxTimeSetter(type) {
21368          return function (val) {
21369            self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i");
21370          };
21371        };
21372
21373        Object.defineProperty(self.config, "minTime", {
21374          get: function get() {
21375            return self.config._minTime;
21376          },
21377          set: minMaxTimeSetter("min")
21378        });
21379        Object.defineProperty(self.config, "maxTime", {
21380          get: function get() {
21381            return self.config._maxTime;
21382          },
21383          set: minMaxTimeSetter("max")
21384        });
21385
21386        if (userConfig.mode === "time") {
21387          self.config.noCalendar = true;
21388          self.config.enableTime = true;
21389        }
21390
21391        Object.assign(self.config, formats$$1, userConfig);
21392
21393        for (var i = 0; i < boolOpts.length; i++) {
21394          self.config[boolOpts[i]] = self.config[boolOpts[i]] === true || self.config[boolOpts[i]] === "true";
21395        }
21396
21397        for (var _i = hooks.length; _i--;) {
21398          if (self.config[hooks[_i]] !== undefined) {
21399            self.config[hooks[_i]] = arrayify(self.config[hooks[_i]] || []).map(bindToInstance);
21400          }
21401        }
21402
21403        self.isMobile = !self.config.disableMobile && !self.config.inline && self.config.mode === "single" && !self.config.disable.length && !self.config.enable.length && !self.config.weekNumbers && /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
21404
21405        for (var _i2 = 0; _i2 < self.config.plugins.length; _i2++) {
21406          var pluginConf = self.config.plugins[_i2](self) || {};
21407
21408          for (var key in pluginConf) {
21409            if (~hooks.indexOf(key)) {
21410              self.config[key] = arrayify(pluginConf[key]).map(bindToInstance).concat(self.config[key]);
21411            } else if (typeof userConfig[key] === "undefined") self.config[key] = pluginConf[key];
21412          }
21413        }
21414
21415        triggerEvent("onParseConfig");
21416      }
21417
21418      function setupLocale() {
21419        if (typeof self.config.locale !== "object" && typeof flatpickr.l10ns[self.config.locale] === "undefined") self.config.errorHandler(new Error("flatpickr: invalid locale " + self.config.locale));
21420        self.l10n = Object.assign({}, flatpickr.l10ns.default, typeof self.config.locale === "object" ? self.config.locale : self.config.locale !== "default" ? flatpickr.l10ns[self.config.locale] : undefined);
21421        tokenRegex.K = "(" + self.l10n.amPM[0] + "|" + self.l10n.amPM[1] + "|" + self.l10n.amPM[0].toLowerCase() + "|" + self.l10n.amPM[1].toLowerCase() + ")";
21422        self.formatDate = createDateFormatter(self);
21423      }
21424
21425      function positionCalendar(customPositionElement) {
21426        if (self.calendarContainer === undefined) return;
21427        triggerEvent("onPreCalendarPosition");
21428        var positionElement = customPositionElement || self._positionElement;
21429        var calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, function (acc, child) {
21430          return acc + child.offsetHeight;
21431        }, 0),
21432            calendarWidth = self.calendarContainer.offsetWidth,
21433            configPos = self.config.position.split(" "),
21434            configPosVertical = configPos[0],
21435            configPosHorizontal = configPos.length > 1 ? configPos[1] : null,
21436            inputBounds = positionElement.getBoundingClientRect(),
21437            distanceFromBottom = window.innerHeight - inputBounds.bottom,
21438            showOnTop = configPosVertical === "above" || configPosVertical !== "below" && distanceFromBottom < calendarHeight && inputBounds.top > calendarHeight;
21439        var top = window.pageYOffset + inputBounds.top + (!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2);
21440        toggleClass(self.calendarContainer, "arrowTop", !showOnTop);
21441        toggleClass(self.calendarContainer, "arrowBottom", showOnTop);
21442        if (self.config.inline) return;
21443        var left = window.pageXOffset + inputBounds.left - (configPosHorizontal 
21443!= null && configPosHorizontal === "center" ? (calendarWidth - inputBounds.width) / 2 : 0);
21444        var right = window.document.body.offsetWidth - inputBounds.right;
21445        var rightMost = left + calendarWidth > window.document.body.offsetWidth;
21446        toggleClass(self.calendarContainer, "rightMost", rightMost);
21447        if (self.config.static) return;
21448        self.calendarContainer.style.top = top + "px";
21449
21450        if (!rightMost) {
21451          self.calendarContainer.style.left = left + "px";
21452          self.calendarContainer.style.right = "auto";
21453        } else {
21454          self.calendarContainer.style.left = "auto";
21455          self.calendarContainer.style.right = right + "px";
21456        }
21457      }
21458
21459      function redraw() {
21460        if (self.config.noCalendar || self.isMobile) return;
21461        updateNavigationCurrentMonth();
21462        buildDays();
21463      }
21464
21465      function focusAndClose() {
21466        self._input.focus();
21467
21468        if (window.navigator.userAgent.indexOf("MSIE") !== -1 || navigator.msMaxTouchPoints !== undefined) {
21469          setTimeout(self.close, 0);
21470        } else {
21471          self.close();
21472        }
21473      }
21474
21475      function selectDate(e) {
21476        e.preventDefault();
21477        e.stopPropagation();
21478
21479        var isSelectable = function isSelectable(day) {
21480          return day.classList && day.classList.contains("flatpickr-day") && !day.classList.contains("disabled") && !day.classList.contains("notAllowed");
21481        };
21482
21483        var t = findParent(e.target, isSelectable);
21484        if (t === undefined) return;
21485        var target = t;
21486        var selectedDate = self.latestSelectedDateObj = new Date(target.dateObj.getTime());
21487        var shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth || selectedDate.getMonth() > self.currentMonth + self.config.showMonths - 1) && self.config.mode !== "range";
21488        self.selectedDateElem = target;
21489        if (self.config.mode === "single") self.selectedDates = [selectedDate];else if (self.config.mode === "multiple") {
21490          var selectedIndex = isDateSelected(selectedDate);
21491          if (selectedIndex) self.selectedDates.splice(parseInt(selectedIndex), 1);else self.selectedDates.push(selectedDate);
21492        } else if (self.config.mode === "range") {
21493          if (self.selectedDates.length === 2) self.clear(false);
21494          self.selectedDates.push(selectedDate);
21495          if (compareDates(selectedDate, self.selectedDates[0], true) !== 0) self.selectedDates.sort(function (a, b) {
21496            return a.getTime() - b.getTime();
21497          });
21498        }
21499        setHoursFromInputs();
21500
21501        if (shouldChangeMonth) {
21502          var isNewYear = self.currentYear !== selectedDate.getFullYear();
21503          self.currentYear = selectedDate.getFullYear();
21504          self.currentMonth = selectedDate.getMonth();
21505          if (isNewYear) triggerEvent("onYearChange");
21506          triggerEvent("onMonthChange");
21507        }
21508
21509        updateNavigationCurrentMonth();
21510        buildDays();
21511        setDefaultHours();
21512        updateValue();
21513        if (self.config.enableTime) setTimeout(function () {
21514          return self.showTimeInput = true;
21515        }, 50);
21516
21517        if (self.config.mode === "range") {
21518          if (self.selectedDates.length === 1) {
21519            onMouseOver(target);
21520          } else updateNavigationCurrentMonth();
21521        }
21522
21523        if (!shouldChangeMonth && self.config.mode !== "range" && self.config.showMonths === 1) focusOnDayElem(target);else self.selectedDateElem && self.selectedDateElem.focus();
21524        if (self.hourElement !== undefined) setTimeout(function () {
21525          return self.hourElement !== undefined && self.hourElement.select();
21526        }, 451);
21527
21528        if (self.config.closeOnSelect) {
21529          var single = self.config.mode === "single" && !self.config.enableTime;
21530          var range = self.config.mode === "range" && self.selectedDates.length === 2 && !self.config.enableTime;
21531
21532          if (single || range) {
21533            focusAndClose();
21534          }
21535        }
21536
21537        triggerChange();
21538      }
21539
21540      var CALLBACKS = {
21541        locale: [setupLocale, updateWeekdays],
21542        showMonths: [buildMonths, setCalendarWidth, buildWeekdays]
21543      };
21544
21545      function set(option, value) {
21546        if (option !== null && typeof option === "object") Object.assign(self.config, option);else {
21547          self.config[option] = value;
21548          if (CALLBACKS[option] !== undefined) CALLBACKS[option].forEac
21548h(function (x) {
21549            return x();
21550          });
21551        }
21552        self.redraw();
21553        jumpToDate();
21554      }
21555
21556      function setSelectedDate(inputDate, format) {
21557        var dates = [];
21558        if (inputDate instanceof Array) dates = inputDate.map(function (d) {
21559          return self.parseDate(d, format);
21560        });else if (inputDate instanceof Date || typeof inputDate === "number") dates = [self.parseDate(inputDate, format)];else if (typeof inputDate === "string") {
21561          switch (self.config.mode) {
21562            case "single":
21563            case "time":
21564              dates = [self.parseDate(inputDate, format)];
21565              break;
21566
21567            case "multiple":
21568              dates = inputDate.split(self.config.conjunction).map(function (date) {
21569                return self.parseDate(date, format);
21570              });
21571              break;
21572
21573            case "range":
21574              dates = inputDate.split(self.l10n.rangeSeparator).map(function (date) {
21575                return self.parseDate(date, format);
21576              });
21577              break;
21578
21579            default:
21580              break;
21581          }
21582        } else self.config.errorHandler(new Error("Invalid date supplied: " + JSON.stringify(inputDate)));
21583        self.selectedDates = dates.filter(function (d) {
21584          return d instanceof Date && isEnabled(d, false);
21585        });
21586        if (self.config.mode === "range") self.selectedDates.sort(function (a, b) {
21587          return a.getTime() - b.getTime();
21588        });
21589      }
21590
21591      function setDate(date, triggerChange, format) {
21592        if (triggerChange === void 0) {
21593          triggerChange = false;
21594        }
21595
21596        if (format === void 0) {
21597          format = self.config.dateFormat;
21598        }
21599
21600        if (date !== 0 && !date || date instanceof Array && date.length === 0) return self.clear(triggerChange);
21601        setSelectedDate(date, format);
21602        self.showTimeInput = self.selectedDates.length > 0;
21603        self.latestSelectedDateObj = self.selectedDates[0];
21604        self.redraw();
21605        jumpToDate();
21606        setHoursFromDate();
21607        updateValue(triggerChange);
21608        if (triggerChange) triggerEvent("onChange");
21609      }
21610
21611      function parseDateRules(arr) {
21612        return arr.slice().map(function (rule) {
21613          if (typeof rule === "string" || typeof rule === "number" || rule instanceof Date) {
21614            return self.parseDate(rule, undefined, true);
21615          } else if (rule && typeof rule === "object" && rule.from && rule.to) return {
21616            from: self.parseDate(rule.from, undefined),
21617            to: self.parseDate(rule.to, undefined)
21618          };
21619
21620          return rule;
21621        }).filter(function (x) {
21622          return x;
21623        });
21624      }
21625
21626      function setupDates() {
21627        self.selectedDates = [];
21628        self.now = self.parseDate(self.config.now) || new Date();
21629        var preloadedDate = self.config.defaultDate || (self.input.placeholder.length > 0 && self.input.value === self.input.placeholder ? null : self.input.value);
21630        if (preloadedDate) setSelectedDate(preloadedDate, self.config.dateFormat);
21631        var initialDate = self.selectedDates.length > 0 ? self.selectedDates[0] : self.config.minDate && self.config.minDate.getTime() > self.now.getTime() ? self.config.minDate : self.config.maxDate && self.config.maxDate.getTime() < self.now.getTime() ? self.config.maxDate : self.now;
21632        self.currentYear = initialDate.getFullYear();
21633        self.currentMonth = initialDate.getMonth();
21634        if (self.selectedDates.length > 0) self.latestSelectedDateObj = self.selectedDates[0];
21635        if (self.config.minTime !== undefined) self.config.minTime = self.parseDate(self.config.minTime, "H:i");
21636        if (self.config.maxTime !== undefined) self.config.maxTime = self.parseDate(self.config.maxTime, "H:i");
21637        self.minDateHasTime = !!self.config.minDate && (self.config.minDate.getHours() > 0 || self.config.minDate.getMinutes() > 0 || self.config.minDate.getSeconds() > 0);
21638        self.maxDateHasTime = !!self.config.maxDate && (self.config.maxDate.getHours() > 0 || self.config.maxDate.getMinutes() > 0 || self.config.maxDate.getSeconds() > 0);
21639        Object.defineProperty(self, "showTimeInput", {
21640          get: function get() {
21641            return self._showTimeInput;
21642          },
21643          set: function set(bool) {
21644            self._showTimeInput = bool;
21645            if (self.calendarContainer) toggleClass(self.calendarContainer, "showTimeInput", bool);
21646            self.isOpen && positionCalendar();
21647          }
21648        });
21649      }
21650
21651      function setupInputs() {
21652        self.input = self.config.wrap ? element.querySelector("[data-input]") : element;
21653
21654        if (!self.input) {
21655          self.config.errorHandler(new Error("Invalid input element specified"));
21656          return;
21657        }
21658
21659        self.input._type = self.input.type;
21660        self.input.type = "text";
21661        self.input.classList.add("flatpickr-input");
21662        self._input = self.input;
21663
21664        if (self.config.altInput) {
21665          self.altInput = createElement(self.input.nodeName, self.input.className + " " + self.config.altInputClass);
21666          self._input = self.altInput;
21667          self.altInput.placeholder = self.input.placeholder;
21668          self.altInput.disabled = self.input.disabled;
21669          self.altInput.required = self.input.required;
21670          self.altInput.tabIndex = self.input.tabIndex;
21671          self.altInput.type = "text";
21672          self.input.setAttribute("type", "hidden");
21673          if (!self.config.static && self.input.parentNode) self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
21674        }
21675
21676        if (!self.config.allowInput) self._input.setAttribute("readonly", "readonly");
21677        self._positionElement = self.config.positionElement || self._input;
21678      }
21679
21680      function setupMobile() {
21681        var inputType = self.config.enableTime ? self.config.noCalendar ? "time" : "datetime-local" : "date";
21682        self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
21683        self.mobileInput.step = self.input.getAttribute("step") || "any";
21684        self.mobileInput.tabIndex = 1;
21685        self.mobileInput.type = inputType;
21686        self.mobileInput.disabled = self.input.disabled;
21687        self.mobileInput.required = self.input.required;
21688        self.mobileInput.placeholder = self.input.placeholder;
21689        self.mobileFormatStr = inputType === "datetime-local" ? "Y-m-d\\TH:i:S" : inputType === "date" ? "Y-m-d" : "H:i:S";
21690
21691        if (self.selectedDates.length > 0) {
21692          self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr);
21693        }
21694
21695        if (self.config.minDate) self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d");
21696        if (self.config.maxDate) self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d");
21697        self.input.type = "hidden";
21698        if (self.altInput !== undefined) self.altInput.type = "hidden";
21699
21700        try {
21701          if (self.input.parentNode) self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
21702        } catch (_a) {}
21703
21704        bind(self.mobileInput, "change", function (e) {
21705          self.setDate(e.target.value, false, self.mobileFormatStr);
21706          triggerEvent("onChange");
21707          triggerEvent("onClose");
21708        });
21709      }
21710
21711      function toggle(e) {
21712        if (self.isOpen === true) return self.close();
21713        self.open(e);
21714      }
21715
21716      function triggerEvent(event, data) {
21717        var hooks = self.config[event];
21718
21719        if (hooks !== undefined && hooks.length > 0) {
21720          for (var i = 0; hooks[i] && i < hooks.length; i++) {
21721            hooks[i](self.selectedDates, self.input.value, self, data);
21722          }
21723        }
21724
21725        if (event === "onChange") {
21726          self.input.dispatchEvent(createEvent("change"));
21727          self.input.dispatchEvent(createEvent("input"));
21728        }
21729      }
21730
21731      function createEvent(name) {
21732        var e = document.createEvent("Event");
21733        e.initEvent(name, true, true);
21734        return e;
21735      }
21736
21737      function isDateSelected(date) {
21738        for (var i = 0; i < self.selectedDates.length; i++) {
21739          if (compareDates(self.selectedDates[i], date) === 0) return "" + i;
21740        }
21741
21742        return false;
21743      }
21744
21745      function isDateInRange(date) {
21746        if (self.config.mode !== "range" || self.selectedDates.length < 2) return false;
21747        return compareDates(date, self.selectedDates[0]) >= 0 && compareDates(date, self.selectedDates[1]) <= 0;
21748      }
21749
21750      function updateNavigationCurrentMonth() {
21751        if (self.config.noCalendar || self.isMobile || !self.monthNav) return;
21752        self.yearElements.forEach(function (yearElement, i) {
21753          var d = new Date(self.currentYear, self.currentMonth, 1);
21754          d.setMonth(self.currentMonth + i);
21755          self.monthElements[i].textContent = monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " ";
21756          yearElement.value = d.getFullYear().toString();
21757        });
21758        self._hidePrevMonthArrow = self.config.minDate !== undefined && (self.currentYear === self.config.minDate.getFullYear() ? self.currentMonth <= self.config.minDate.getMonth() : self.currentYear < self.config.minDate.getFullYear());
21759        self._hideNextMonthArrow = self.config.maxDate !== undefined && (self.currentYear === self.config.maxDate.getFullYear() ? self.currentMonth + 1 > self.config.maxDate.getMonth() : self.currentYear > self.config.maxDate.getFullYear());
21760      }
21761
21762      function updateValue(triggerChange) {
21763        if (triggerChange === void 0) {
21764          triggerChange = true;
21765        }
21766
21767        if (self.selectedDates.length === 0) return self.clear(triggerChange);
21768
21769        if (self.mobileInput !== undefined && self.mobileFormatStr) {
21770          self.mobileInput.value = self.latestSelectedDateObj !== undefined ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : "";
21771        }
21772
21773        var joinChar = self.config.mode !== "range" ? self.config.conjunction : self.l10n.rangeSeparator;
21774        self.input.value = self.selectedDates.map(function (dObj) {
21775          return self.formatDate(dObj, self.config.dateFormat);
21776        }).join(joinChar);
21777
21778        if (self.altInput !== undefined) {
21779          self.altInput.value = self.selectedDates.map(function (dObj) {
21780            return self.formatDate(dObj, self.config.altFormat);
21781          }).join(joinChar);
21782        }
21783
21784        if (triggerChange !== false) triggerEvent("onValueUpdate");
21785      }
21786
21787      function onMonthNavClick(e) {
21788        e.preventDefault();
21789        var isPrevMonth = self.prevMonthNav.contains(e.target);
21790        var isNextMonth = self.nextMonthNav.contains(e.target);
21791
21792        if (isPrevMonth || isNextMonth) {
21793          changeMonth(isPrevMonth ? -1 : 1);
21794        } else if (self.yearElements.indexOf(e.target) >= 0) {
21795          e.target.select();
21796        } else if (e.target.classList.contains("arrowUp")) {
21797          self.changeYear(self.currentYear + 1);
21798        } else if (e.target.classList.contains("arrowDown")) {
21799          self.changeYear(self.currentYear - 1);
21800        }
21801      }
21802
21803      function timeWrapper(e) {
21804        e.preventDefault();
21805        var isKeyDown = e.type === "keydown",
21806            input = e.target;
21807
21808        if (self.amPM !== undefined && e.target === self.amPM) {
21809          self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
21810        }
21811
21812        var min = parseFloat(input.getAttribute("data-min")),
21813            max = parseFloat(input.getAttribute("data-max")),
21814            step = parseFloat(input.getAttribute("data-step")),
21815            curValue = parseInt(input.value, 10),
21816            delta = e.delta || (isKeyDown ? e.which === 38 ? 1 : -1 : 0);
21817        var newValue = curValue + step * delta;
21818
21819        if (typeof input.value !== "undefined" && input.value.length === 2) {
21820          var isHourElem = input === self.hourElement,
21821              isMinuteElem = input === self.minuteElement;
21822
21823          if (newValue < min) {
21824            newValue = max + newValue + int(!isHourElem) + (int(isHourElem) && int(!self.amPM));
21825            if (isMinuteElem) incrementNumInput(undefined, -1, self.hourElement);
21826          } else if (newValue > max) {
21827            newValue = input === self.hourElement ? newValue - max - int(!self.amPM) : min;
21828            if (isMinuteElem) incrementNumInput(undefined, 1, self.hourElement);
21829          }
21830
21831          if (self.amPM && isHourElem && (step === 1 ? newValue + curValue === 23 : Math.abs(newValue - curValue) > step)) {
21832            self.amPM.textContent = self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
21833          }
21834
21835          input.value = pad(newValue);
21836        }
21837      }
21838
21839      init();
21840      return self;
21841    }
21842
21843    function _flatpickr(nodeList, config) {
21844      var nodes = Array.prototype.slice.call(nodeList);
21845      var instances = [];
21846
21847      for (var i = 0; i < nodes.length; i++) {
21848        var node = nodes[i];
21849
21850        try {
21851          if (node.getAttribute("data-fp-omit") !== null) continue;
21852
21853          if (node._flatpickr !== undefined) {
21854            node._flatpickr.destroy();
21855
21856            node._flatpickr = undefined;
21857          }
21858
21859          node._flatpickr = FlatpickrInstance(node, config || {});
21860          instances.push(node._flatpickr);
21861        } catch (e) {
21862          console.error(e);
21863        }
21864      }
21865
21866      return instances.length === 1 ? instances[0] : instances;
21867    }
21868
21869    if (typeof HTMLElement !== "undefined") {
21870      HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function (config) {
21871        return _flatpickr(this, config);
21872      };
21873
21874      HTMLElement.prototype.flatpickr = function (config) {
21875        return _flatpickr([this], config);
21876      };
21877    }
21878
21879    var flatpickr = function flatpickr(selector, config) {
21880      if (selector instanceof NodeList) return _flatpickr(selector, config);else if (typeof selector === "string") return _flatpickr(window.document.querySelectorAll(selector), config);
21881      return _flatpickr([selector], config);
21882    };
21883
21884    flatpickr.defaultConfig = defaults;
21885    flatpickr.l10ns = {
21886      en: Object.assign({}, english),
21887      default: Object.assign({}, english)
21888    };
21889
21890    flatpickr.localize = function (l10n) {
21891      flatpickr.l10ns.default = Object.assign({}, flatpickr.l10ns.default, l10n);
21892    };
21893
21894    flatpickr.setDefaults = function (config) {
21895      flatpickr.defaultConfig = Object.assign({}, flatpickr.defaultConfig, config);
21896    };
21897
21898    flatpickr.parseDate = createDateParser({});
21899    flatpickr.formatDate = createDateFormatter({});
21900    flatpickr.compareDates = compareDates;
21901
21902    if (typeof jQuery !== "undefined") {
21903      jQuery.fn.flatpickr = function (config) {
21904        return _flatpickr(this, config);
21905      };
21906    }
21907
21908    Date.prototype.fp_incr = function (days) {
21909      return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days));
21910    };
21911
21912    if (typeof window !== "undefined") {
21913      window.flatpickr = flatpickr;
21914    }
21915
21916    return flatpickr;
21917
21918})));
21919
21920(function (global, factory) {
21921    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
21922    typeof define === 'function' && define.amd ? define(['exports'], factory) :
21923    (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ko = {}));
21924  }(this, (function (exports) { 'use strict';
21925
21926    var fp = typeof window !== "undefined" && window.flatpickr !== undefined
21927        ? window.flatpickr
21928        : {
21929            l10ns: {},
21930        };
21931    var Korean = {
21932        weekdays: {
21933            shorthand: ["일", "월", "화", "수", "목", "금", "토"],
21934            longhand: [
21935                "일요일",
21936                "월요일",
21937                "화요일",
21938                "수요일",
21939                "목요일",
21940                "금요일",
21941                "토요일",
21942            ],
21943        },
21944        months: {
21945            shorthand: [
21946                "1월",
21947                "2월",
21948                "3월",
21949                "4월",
21950                "5월",
21951                "6월",
21952                "7월",
21953                "8월",
21954                "9월",
21955                "10월",
21956                "11월",
21957                "12월",
21958            ],
21959            longhand: [
21960                "1월",
21961                "2월",
21962                "3월",
21963                "4월",
21964                "5월",
21965                "6월",
21966                "7월",
21967                "8월",
21968                "9월",
21969                "10월",
21970                "11월",
21971                "12월",
21972            ],
21973        },
21974        ordinal: function () {
21975            return "일";
21976        },
21977        rangeSeparator: " - ",
21978        amPM: ["오전", "오후"],
21979    };
21980    fp.l10ns.ko = Korean;
21981    var ko = fp.l10ns;
21982
21983    exports.Korean = Korean;
21984    exports.default = ko;
21985
21986    Object.defineProperty(exports, '__esModule', { value: true });
21987
21988  })));
21989EC$(document).ready(function() {
21990    RESERVATION.init();
21991});
21992var RESERVATION = {
21993    oCustomConfig : {},
21994    oTargetObject : {
21995        'calendarInputs' : document.querySelectorAll('.ec-search-calendar'),
21996        'selectedTerm' : document.querySelector('.selectedTerm'),
21997        'controls' : document.querySelector('.calendar-controls'),
21998    },
21999    init : function(oCustomOption)
22000    {
22001        RESERVATION.oCustomConfig = oCustomOption;
22002        RESERVATION.initCalendar();
22003        RESERVATION.initLayer();
22004        window.addEventListener('resize', RESERVATION.initCalendar);
22005
22006        const closeButtons = document.querySelectorAll('.eCalendarClose');
22007        closeButtons.forEach(button => {
22008            button.addEventListener('click', function() {
22009                RESERVATION.oTargetObject['calendarInputs'].forEach(calendarInput => {
22010                    if (calendarInput._flatpickr) {
22011                        calendarInput._flatpickr.close();
22012                    }
22013                });
22014            });
22015        });
22016
22017        const applyButton = document.querySelector('.eCalendarApply');
22018        if (applyButton !== null) {
22019            applyButton.addEventListener('click', function() {
22020                RESERVATION.oTargetObject['calendarInputs'].forEach(calendarInput => {
22021                    // 검색페이지의 검색폼과 레이아웃의 검색폼의 "날짜 적용"버튼 클릭시 어떤 위치에서 클릭했는지 필터링 하기 위한 조건
22022                    const bIisSearchExpand = EC$('body').hasClass('searchExpand');
22023                    const bIsInSearchForm = EC$(calendarInput).parents('form#ec-product-searchdata-searchkeyword_form').length > 0 || EC$(calendarInput).parents('form#ec-product-fixed-form').length > 0;
22024                    if (bIisSearchExpand === bIsInSearchForm) {
22025                        return;
22026                    }
22027
22028                    if (calendarInput._flatpickr.selectedDates.length === 0) {
22029                        alert(__('SELECT.DATE', 'SHOP.JS.FRONT.SEARCH.RESEVATION')); // 날짜를 선택해주세요.
22030                        return false;
22031                    }
22032                    if (calendarInput._flatpickr) {
22033                        calendarInput._flatpickr.close();
22034                    }
22035                });
22036            });
22037        }
22038
22039        EC$('.ec-search-calendar').parent().find('.btnDelete').on('click', function() {
22040            RESERVATION.oTargetObject['calendarInputs'].forEach(calendarInput => {
22041                const bIisSearchExpand = EC$('body').hasClass('searchExpand');
22042                const bIsInSearchForm = EC$(calendarInput).parents('form#ec-product-searchdata-searchkeyword_form').length > 0 || EC$(calendarInput).parents('form#ec-product-fixed-form').length > 0;
22043                if (bIisSearchExpand === bIsInSearchForm) {
22044                    return;
22045                }
22046                if (calendarInput._flatpickr) {
22047                    calendarInput._flatpickr.clear();
22048                }
22049            });
22050        });
22051
22052        EC$('#ec-reservation-product-only').click(function() {
22053            EC$('input.ec-reservation-product-only').remove();
22054            if (EC$('#ec-reservation-product-only').prop('checked') === true) {
22055                EC$("#ec-product-searchdata-submit_button").append(EC$('<input>', {type: 'hidden', name: 'only_reservation', value: 'T', class: 'ec-reservation-product-only'}));
22056            }
22057            EC$('#ec-product-searchdata-submit_button').click();
22058        });
22059    },
22060    initCalendar : function()
22061    {
22062        const maxWidth = 890;
22063        const numberOfMonths = window.innerWidth <= maxWidth ? 1 : 2;
22064
22065        RESERVATION.oTargetObject['calendarInputs'].forEach(calendarInput => {
22066            if (calendarInput._flatpickr) {
22067                calendarInput._flatpickr.destroy();
22068            }
22069
22070            let oCalendarConfig = {
22071                yearFirst: true,
22072                enableTime: false,
22073                mode: "range",
22074                dateFormat: "Y.m.d",
22075                showMonths: numberOfMonths,
22076                locale: "ko",
22077                minDate: "today",
22078                maxDate: EC_FRONT_JS_CONFIG_SHOP.calendar_config.maxDate,
22079                position: "below center",
22080                closeOnSelect: false,
22081                onDayCreate: function(dObj, dStr, fp, dayElem) {
22082                    if (dayElem.dateObj.toDateString() === new Date().toDateString()) {
22083                        dayElem.classList.add('today');
22084                    }
22085                },
22086                onChange: function(selectedDates, dateStr, instance) {
22087                    EC$(calendarInput.parentElement.querySelector('.btnDelete')).removeClass('displaynone');
22088                    if (selectedDates.length === 2) {
22089                        const [startDate, endDate] = selectedDates;
22090                        let iMaxLimitDate = 90;
22091                        let range = instance.formatDate(endDate, 'U') - instance.formatDate(startDate, 'U');
22092                        range = range / 86400;
22093                        if(range > iMaxLimitDate) {
22094                            alert(sprintf(__('CAN.SELECT.DATE.MAX.TO', 'SHOP.JS.FRONT.SEARCH.RESEVATION'), iMaxLimitDate)); // 최대 %s일까지 선택 가능합니다.
22095                            instance.clear();
22096                            calendarInput.value = '';
22097                            RESERVATION.oTargetObject['selectedTerm'].textContent = '';
22098                            return;
22099                        }
22100                        const formattedStartDate = `${startDate.getFullYear()}.${('0' + (startDate.getMonth() + 1)).slice(-2)}.${('0' + startDate.getDate()).slice(-2)}`;
22101                        const formattedEndDate = `${endDate.getFullYear()}.${('0' + (endDate.getMonth() + 1)).slice(-2)}.${('0' + endDate.getDate()).slice(-2)}`;
22102                        calendarInput.value = `${formattedStartDate} - ${formattedEndDate}`;
22103                        RESERVATION.oTargetObject['selectedTerm'].textContent = `${formattedStartDate} - ${formattedEndDate}`;
22104                    } else if (selectedDates.length === 1) {
22105                        const startDate = selectedDates[0];
22106                        const formattedStartDate = `${startDate.getFullYear()}.${('0' + (startDate.getMonth() + 1)).slice(-2)}.${('0' + startDate.getDate()).slice(-2)}`;
22107                        calendarInput.value = formattedStartDate;
22108                        RESERVATION.oTargetObject['selectedTerm'].textContent = formattedStartDate;
22109                    } else {
22110                        calendarInput.value = '';
22111                        RESERVATION.oTargetObject['selectedTerm'].textContent = '';
22112                        EC$(calendarInput.parentElement.querySelector('.btnDelete')).addClass('displaynone');
22113                    }
22114                },
22115                onOpen: function(selectedDates, dateStr, instance) {
22116                    // 달력 컨트롤 표시
22117                    RESERVATION.oTargetObject['controls'].style.display = 'flex';
22118                    const calendarContainer = instance.calendarContainer;
22119                    // 달력 컨트롤 추가
22120                    if (!calendarContainer.querySelector('.calendar-controls')) {
22121                        calendarContainer.appendChild(RESERVATION.oTargetObject['controls']);
22122                    }
22123                    // 'open' 클래스 추가
22124                    requestAnimationFrame(() => {
22125                        calendarContainer.classList.add('open');
22126                    });
22127                    // 조건 2: xans-product-searchdata 영역 안의 .datepickr 활성화 시 hidden 클래스 추가 안함
22128                    if (!calendarInput.closest('.xans-product-searchdata') && window.innerWidth <= maxWidth) {
22129                        document.body.classList.add('hidden');
22130                    }
22131                },
22132                onClose: function(selectedDates, dateStr, instance) {
22133                    // 조건 2: xans-product-searchdata 영역 안의 .datepickr 닫을 경우 hidden 클래스 제거 안함
22134                    if (!calendarInput.closest('.xans-product-searchdata') && window.innerWidth <= maxWidth) {
22135                        document.body.classList.remove('hidden');
22136                    }
22137                    if (selectedDates.length === 1) {
22138                        const startDate = selectedDates[0];
22139                        instance.setDate([startDate, startDate], true);
22140                        const formattedStartDate = `${startDate.getFullYear()}.${('0' + (startDate.getMonth() + 1)).slice(-2)}.${('0' + startDate.getDate()).slice(-2)}`;
22141                        calendarInput.value = formattedStartDate;
22142                        RESERVATION.oTargetObject['selectedTerm'].textContent = formattedStartDate;
22143                    }
22144                },
22145                onReady : function(selectedDates, dateStr, instance) {
22146                    // 검색폼에 있는 날짜만 유지해달라고함
22147                    if (EC$(calendarInput).parents('form#ec-product-searchdata-searchkeyword_form').length > 0
22148                        || EC$(calendarInput).parents('form#ec-product-fixed-form').length > 0) {
22149                        //calendarInput.value = calendarInput.value.replace('~', '-');
22150                        if (calendarInput.value !== '') {
22151                            EC$(calendarInput.parentElement.querySelector('.btnDelete')).removeClass('displaynone');
22152                        }
22153                    } else {
22154                        instance.clear();
22155                    }
22156                }
22157            };
22158            oCalendarConfig['defaultDate'] = [EC_FRONT_JS_CONFIG_SHOP.search_period.start_date, EC_FRONT_JS_CONFIG_SHOP.search_period.end_date];
22159            if (typeof(EC_FRONT_JS_CONFIG_SHOP.calendar_config) === 'object') {
22160                oCalendarConfig['locale'] = EC_FRONT_JS_CONFIG_SHOP.calendar_config.locale;
22161            }
22162
22163            flatpickr(calendarInput, oCalendarConfig);
22164            // 추가: touchstart 이벤트 리스너로 모바일 환경 대응
22165            calendarInput.addEventListener('touchstart', function(event) {
22166                event.preventDefault(); // 터치 이벤트가 다른 이벤트로 전파되지 않도록 함
22167                if (calendarInput._flatpickr) {
22168                    calendarInput._flatpickr.open(); // 달력 열기
22169                }
22170            });
22171        });
22172    },
22173    initLayer : function()
22174    {
22175        RESERVATION.searchLayer();
22176    },
22177    /**
22178     * FE팀 제공 레이어 핸들링 함수
22179     * @param {*} target
22180     * @param {*} element
22181     * @param {*} className
22182     */
22183
22184    searchLayer : function()
22185    {
22186        var btnSearchs = document.querySelectorAll('.eSearch');
22187        btnSearchs.forEach(function(btnSearch) {
22188            btnSearch.addEventListener('click', function(){
22189                document.body.classList.add('searchExpand');
22190                document.body.classList.add('hidden'); // 조건 1: .searchExpand 활성화 시 body에 hidden 클래스 추가
22191            });
22192        });
22193        var btnCloses = document.querySelectorAll('.xans-layout-searchheader .btnClose');
22194        btnCloses.forEach(function(btnClose) {
22195            btnClose.addEventListener('click', function(){
22196                document.body.classList.remove('searchExpand');
22197                document.body.classList.remove('hidden'); // 조건 1: .searchExpand 없을 경우 body에 hidden 클래스 제거
22198            });
22199        });
22200        var dimmed = document.querySelector('#layoutDimmed');
22201        if (dimmed !== null) {
22202            RESERVATION.handleDimmed(dimmed, document.body, 'searchExpand');
22203        }
22204    },
22205    /**
22206     * FE팀 제공 레이어 핸들링 함수
22207     * @param {*} target
22208     * @param {*} element
22209     * @param {*} className
22210     */
22211    handleDimmed : function(target, element, className)
22212    {
22213        target.addEventListener('click', function(){
22214            element.classList.remove(className);
22215            document.body.classList.remove('hidden'); // .searchExpand 없을 경우 body에 hidden 클래스 제거
22216        });
22217    }
22218};
22219/**
22220 * 게시판 관련 JS
22221 */
22222
22223EC$(function() {
22224    BOARD.event_bind();
22225    // 게시판메뉴 이미지 롤오버
22226    BOARD.board_img_over();
22227});
22228
22229
22230var BOARD = {
22231    /**
22232     * 게시판 첨부 이미지 로드큐
22233     */
22234    aAttachImageLoadQueue: [],
22235
22236    /**
22237     * 이벤트 바인딩을 합니다.
22238     */
22239    event_bind: function ()
22240    {
22241        //상품분류 검색 셀렉터 이벤트 바인딩
22242        BOARD.setProductCategorySelector.setEvent();
22243    },
22244
22245    /**
22246     * 공지글 보기
22247     */
22248    show_notice: function()
22249    {
22250        var bFlag = EC$('input[type="checkbox"][name="showNotice"]')[0].checked;
22251        if (bFlag === true) {
22252            EC$('.mNoticeFlag').each(function(index, node) {
22253                EC$(node).show();
22254            });
22255        } else {
22256            EC$('.mNoticeFlag').each(function(index, node) {
22257                EC$(node).hide();
22258            });
22259        }
22260    },
22261
22262    /**
22263     * 관리자 설정에 따른 제목, 컨텐츠 고정하기
22264     */
22265    fix_subject_content: function()
22266    {
22267        EC$("select[name='subject']").change(function() {
22268            if (EC$("#fix_content_" + this.selectedIndex).val() != undefined) {
22269                var content = EC$("#fix_content_" + this.selectedIndex).val() + EC$("#fix_add_content").val();
22270            } else {
22271                if (EC$("#fix_add_content").val() != undefined) {
22272                    var content = EC$("#fix_add_content").val();
22273                } else {
22274                    var content = '';
22275                }
22276            }
22277
22278            // 답변, 수정 모드에서는 컨텐츠 영역이 수정되지 않도록 한다.
22279            // 게시글 입력 양식 설정 '노출안함'일 경우 content에 빈값으로 셋팅
22280            if (EC$('#no').length == 0) {
22281                //IE10 이하는 NN에디터
22282                if (EC$('#content_IFRAME').length > 0 && EC$('#content_TEXTAREA').length > 0) {
22283                    EC$("#content_IFRAME").get(0).contentWindow.document.body.innerHTML = content;
22284                    EC$("#content_TEXTAREA").val(content);
22285                } else {
22286                    applyContentToFroala(content);
22287                }
22288            }
22289
22290        });
22291    },
22292
22293    /**
22294     * 항상 비밀글 사용하기
22295     */
22296    disable_secret: function()
22297    {
22298        EC$("#secure0").prop({
22299            "checked": false,
22300            "disabled": true
22301        });
22302
22303        EC$("#secure1").prop("checked", true);
22304    },
22305
22306    /**
22307     * 게시판메뉴 이미지 롤오버
22308     */
22309    board_img_over: function()
22310    {
22311        EC$(".board_img_over").hover(function() {
22312            EC$(this).attr('src',EC$(this).attr('eImgOver'));
22313        }, function() {
22314            EC$(this).attr('src',EC$(this).attr('eImgout'));
22315        });
22316    },
22317
22318    /**
22319     * 폼 submit
22320     * @param string sFormName 폼 name
22321     */
22322    form_submit: function(sFormName)
22323    {
22324        // 서밋 위치를 BOARD_WRITE로 변경
22325        EC$('#'+sFormName).submit();
22326    },
22327
22328    /**
22329     * 리스트 정렬 submit
22330     * @param string sFormName 폼 name
22331     */
22332    change_sort: function(sFormName, obj)
22333    {
22334        EC$('#'+sFormName+' [id="board_sort"]').val(obj.value);
22335
22336        EC$('#'+sFormName).submit();
22337    },
22338
22339    /**
22340     * 답변여부 선택 select
22341     * @param element obj select element
22342     */
22343    change_reply_sort: function(obj)
22344    {
22345        var sQueryString = document.location.search.substr(1);
22346        var aParams = {};
22347
22348        EC$.each(sQueryString.split('&'), function(i, str) {
22349            var sKey = str.substr(0, str.indexOf('='));
22350            if ('page' !== sKey) {
22351                var sVal = str.substr(str.indexOf('=')+1);
22352
22353                aParams[sKey] = sVal;
22354            }
22355        });
22356
22357        aParams['is_reply_sort'] = EC$(obj).val();
22358        var aUrls = [];
22359        EC$.each(aParams, function(sKey, sVal) {
22360            if ('' !== CAFE24.UTIL.trim(sVal)) {
22361                aUrls.push(sKey+'='+CAFE24.UTIL.trim(sVal));
22362            }
22363        });
22364
22365        document.location.href = EC_ROUTE.getPrefixUrl(document.location.pathname)+'?'+aUrls.join('&');
22366    },
22367
22368    /**
22369     * 상품후기 리스트 펼침
22370     * @param int iNo 글번호
22371     * @param int iBoardNo 게시판번호
22372     * @param object obj
22373     */
22374    viewTarget: function(iNo, iBoardNo, obj) {
22375        var self = this;
22376        var elmTarget = EC$(obj);
22377
22378        if (elmTarget.parents('tr').next().attr('id') == 'content_view') {
22379            elmTarget.find('img').attr('src', function() {
22380                return this.src.replace('_fold','_unfold');
22381            });
22382
22383            self.changeFoldImg(obj);
22384
22385            EC$('#content_view').remove();
22386            return;
22387        } else {
22388            EC$('#content_view').remove();
22389
22390            var aData = {
22391                    'no': iNo,
22392                    'board_no': iBoardNo
22393            };
22394            EC$.get('/exec/front/board/Get/'+iBoardNo, aData, function(req) {
22395                if (req.failed == false) {
22396                    var rData = req.data;
22397                    elmTarget.find('img').attr('src', function() {
22398                        return this.src.replace('_unfold','_fold');
22399                    });
22400
22401                    self.changeFoldImg(obj);
22402
22403                    var aHtml = [];
22404                    aHtml.push('<tr id="content_view" class="'+ rData.block_target_class +'" '+ rData.block_data_attr +'>');
22405                    aHtml.push('    <td colspan='+elmTarget.parents('tr').find('td:not(.displaynone)').length+' class="'+ rData.block_content_class +'">');
22406                    if (rData.content_image != null) aHtml.push(''+rData.content_image+'<br />');
22407                    if (typeof(rData.content) !== 'undefined') {
22408                        aHtml.push(rData.content);
22409                    }
22410                    aHtml.push('    </td>');
22411                    aHtml.push('</tr>');
22412
22413                    elmTarget.parents('tr').after(aHtml.join(''));
22414
22415                    if (rData.ucc_url) EC$('.ec-ucc-media-box-'+ rData.no).replaceWith(APP_BOARD_UCC.getPreviewElement(rData.ucc_url));
22416                    APP_BOARD_BLOCK.setBlockList();
22417                } else {
22418                    BOARD.setBulletinSpreadFail(req.data);
22419                }
22420            }, 'json');
22421        }
22422    },
22423    setBulletinSpreadFail: function (sFailType)
22424    {
22425        switch (sFailType) {
22426            case 'S' :
22427                alert(__('비밀글은 미리보기가 불가 합니다.'));
22428                break;
22429            case 'M' :
22430                alert(__('회원에게만 읽기 권한이 있습니다'));
22431                break;
22432            case 'A' :
22433                alert(__('관리자에게만 읽기 권한이 있습니다'));
22434                break;
22435        }
22436    },
22437
22438    /**
22439     * 폴딩 이미지 변환
22440     * 현재 클릭한 이미지 이외에는 모두 '닫힘' 이미지로 만들기 위함
22441     *
22442     * @param HtmlElement obj
22443     */
22444    changeFoldImg: function(obj) {
22445        var elmEventList = EC$('[onclick*="BOARD.viewTarget"]');
22446
22447        elmEventList.each(function() {
22448            if (obj !== this) {
22449                EC$(this).find('img').attr('src', function() {
22450                    return this.src.replace('_fold','_unfold');
22451                });
22452            }
22453        });
22454    },
22455
22456    /**
22457     * 첨부이미지 미리보기
22458     * @param sId
22459     * @param sFlag
22460     */
22461    afile_display: function (sId, sFlag)
22462    {
22463        if (sFlag == 1) {
22464            EC$('#'+sId).css('display', '');
22465            EC$('#'+sId).css('position', 'absolute');
22466        } else {
22467            EC$('#'+sId).css('display', 'none');
22468        }
22469    },
22470
22471    /**
22472     * 첨부이미지 로딩
22473     * @param sId 로드될 타겟 아이디
22474     * @param sFlag 노출여부
22475     * @param iBoardNo 게시판 번호
22476     */
22477    load_attached_image: function(sId, sFlag, iBoardNo)
22478    {
22479        /*
22480         * 게시물 번호 계산
22481         * sId는 항상 "afile_" 이 prefix 됨
22482         */
22483        var iBulletinNo = sId.substr(6,sId.length);
22484
22485        //큐에서 해당 게시물의 이미지가 로드중 또는 로드되었는지 체크
22486        var iPosition = EC$.inArray(iBulletinNo, this.aAttachImageLoadQueue);
22487
22488        var oTarget = EC$('#'+sId);
22489
22490        //큐 체크
22491        if (iPosition === -1) {
22492            this.aAttachImageLoadQueue.push(iBulletinNo);
22493
22494            var sRequestUrl = '/exec/front/Board/Get?no='+ iBulletinNo +'&board_no='+iBoardNo;
22495            EC$.get(sRequestUrl, function(oResponse) {
22496                //로드 성공
22497                if (oResponse.failed === false) {
22498                    oTarget.append(oResponse.data.thumbnail_image);
22499                    BOARD.afile_display(sId, sFlag);
22500                }
22501                //로드 실패
22502                else {
22503                    //큐에서 제거처리하여, 다시 로드 가능하도록 변경
22504                    BOARD.aAttachImageLoadQueue.splice(iPosition,1);
22505                }
22506            },'json');
22507        }
22508
22509        //이미지 존재 체크
22510        if (oTarget.children().is('img') === true) {
22511            BOARD.afile_display(sId, sFlag);
22512        }
22513    },
22514
22515    /**
22516     * 상품 분류 검색 셀렉터
22517     */
22518    setProductCategorySelector: {
22519        /*
22520         * 중,소,세 분류 초기화
22521         */
22522        resetCategory: function(oSelectBox)
22523        {
22524            for (var i=oSelectBox.children().length - 1; i>0; i--) {
22525                oSelectBox.children().eq(i).remove();
22526            }
22527        },
22528
22529        /*
22530         * 하위분류 가져오기
22531         */
22532        getChildCategory: function(iProductCategoryNumber, oSelectBox)
22533        {
22534            var regexp = /[0-9]+/;
22535            if (regexp.test(iProductCategoryNumber) === false || oSelectBox.length === 0) return;
22536
22537            var sUrl = "/exec/front/Product/SubCategory?parent_cate_no="+iProductCategoryNumber;
22538            EC$.get(sUrl, function(oResponse) {
22539                BOARD.setProductCategorySelector.setChildCategory(oSelectBox, oResponse);
22540            }, 'json');
22541        },
22542
22543        /*
22544         * 하위분류 가져오기 Callback 함수
22545         * 하위분류 셀렉트박스 옵션추가
22546         */
22547        // [ECHOSTING-633241] category_name 등을 문자열결합+append(htmlString)으로 조립하면 HTML로 파싱되어
22548        // Stored XSS(서브분류명 미이스케이프)가 발생한다. DOM 엘리먼트를 직접 생성해 append(domElement)하면
22549        // 문자열이 마크업으로 해석되지 않아 값과 무관하게 안전하다.
22550        setChildCategory: function(oSelectBox, aChildCategory)
22551        {
22552            if (aChildCategory.length === 0 || oSelectBox.length === 0) return;
22553
22554            for (const oChildCategory of aChildCategory) {
22555                const oOption = document.createElement('option');
22556                oOption.value = oChildCategory['category_no'];
22557                oOption.textContent = oChildCategory['category_name'];
22558                oSelectBox.append(oOption);
22559            }
22560        },
22561
22562        /**
22563         * 이벤트 바인딩
22564         */
22565        setEvent: function()
22566        {
22567            var oSelector = BOARD.setProductCategorySelector;
22568            /*
22569             * 1뎁스 변경처리
22570             * - 중,소,세 분류 초기화
22571             * - 중분류 옵션 추가
22572             */
22573            EC$("#product_category_depth1").change(function() {
22574                if (EC$(this).val() !== EC$(this).attr("history")) {
22575                    oSelector.resetCategory(EC$("#product_category_depth2"));
22576                    oSelector.resetCategory(EC$("#product_category_depth3"));
22577                    oSelector.resetCategory(EC$("#product_category_depth4"));
22578                    EC$(this).attr("history", EC$(this).val());
22579                }
22580
22581                oSelector.getChildCategory(EC$(this).val(), EC$("#product_category_depth2"));
22582            });
22583
22584            /*
22585             * 2뎁스 변경처리
22586             * - 소,세분류 초기화
22587             * - 소분류 옵션 추가
22588             */
22589            EC$("#product_category_depth2").change(function() {
22590                if (EC$(this).val() !== EC$(this).attr("history")) {
22591                    oSelector.resetCategory(EC$("#product_category_depth3"));
22592                    oSelector.resetCategory(EC$("#product_category_depth4"));
22593                    EC$(this).attr("history", EC$(this).val());
22594                }
22595
22596                oSelector.getChildCategory(EC$(this).val(), EC$("#product_category_depth3"));
22597            });
22598
22599            /*
22600             * 3뎁스 변경처리
22601             * - 세분류 초기화
22602             * - 세분류 옵션 추가
22603             */
22604            EC$("#product_category_depth3").change(function() {
22605                if (EC$(this).val() !== EC$(this).attr("history")) {
22606                    oSelector.resetCategory(EC$("#product_category_depth4"));
22607                    EC$(this).attr("history", EC$(this).val());
22608                }
22609
22610                oSelector.getChildCategory(EC$(this).val(), EC$("#product_category_depth4"));
22611            });
22612        }
22613    },
22614
22615    /**
22616     * 캡차 새로고침
22617     */
22618    refresh_captcha: function(sType, iNo)
22619    {
22620        var sCaptchaId = 'captcha_' + sType;
22621        if (iNo != '') sCaptchaId += '_' + iNo;
22622
22623        EC$('#'+sCaptchaId).attr('src', '/exec/front/board/captcha?no='+iNo+'&type='+sType+'&'+new Date().getTime());
22624    },
22625
22626    END: function() {}
22627};
22628
22629/**
22630 * 쇼핑몰 금액 라이브러리
22631 */
22632CAFE24.SHOP_PRICE = {
22633
22634    /**
22635     * iShopNo 쇼핑몰의 결제화폐에 맞게 리턴합니다.
22636     * @param float fPrice 금액
22637     * @param bool bIsNumberFormat number_format 적용 유무
22638     * @param int iShopNo 쇼핑몰번호
22639     * @return float|string
22640     */
22641    toShopPrice: function(fPrice, bIsNumberFormat, iShopNo)
22642    {
22643        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22644
22645        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22646            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[undefined];
22647        } else {
22648            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo];
22649        }
22650
22651        // 쇼핑몰 결제화폐 정보 사용 (DB/Redis 저장용, Presentment 환율 미적용)
22652        var aCurrencyInfo = oCurrencyInfo.aShopCurrencyInfo;
22653
22654        return CAFE24.SHOP_PRICE.toPrice(fPrice, aCurrencyInfo, bIsNumberFormat);
22655    },
22656
22657    /**
22658     * iShopNo 쇼핑몰의 Presentment 화폐에 맞게 리턴합니다. (화면 표시용)
22659     * Global-e Presentment 활성 시 환율 적용 + Presentment 화폐 정보 사용,
22660     * 비활성 시 기본 결제화폐 정보 사용 (toShopPrice와 동일 동작)
22661     * @param float fPrice 금액
22662     * @param bool bIsNumberFormat number_format 적용 유무
22663     * @param int iShopNo 쇼핑몰번호
22664     * @return float|string
22665     */
22666    toShopPricePresentment: function(fPrice, bIsNumberFormat, iShopNo)
22667    {
22668        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22669
22670        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22671            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[undefined];
22672        } else {
22673            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo];
22674        }
22675
22676        if (oCurrencyInfo.bPresentmentEnabled === true) {
22677            // Global-e Presentment: 환율 적용 + Presentment 화폐 정보 사용
22678            fPrice = fPrice * (oCurrencyInfo.fExchangePresentmentRate || 0);
22679            var aCurrencyInfo = oCurrencyInfo.aPresentmentCurrencyInfo;
22680        } else {
22681            // 기본: 쇼핑몰 결제화폐 정보 사용
22682            var aCurrencyInfo = oCurrencyInfo.aShopCurrencyInfo;
22683        }
22684
22685        return CAFE24.SHOP_PRICE.toPrice(fPrice, aCurrencyInfo, bIsNumberFormat);
22686    },
22687
22688    /**
22689     * iShopNo 쇼핑몰의 참조화폐에 맞게 리턴합니다.
22690     * @param float fPrice 금액
22691     * @param bool bIsNumberFormat number_format 적용 유무
22692     * @param int iShopNo 쇼핑몰번호
22693     * @return float|string
22694     */
22695    toShopSubPrice: function(fPrice, bIsNumberFormat, iShopNo)
22696    {
22697        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22698
22699        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22700            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[undefined];
22701        } else {
22702            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo];
22703        }
22704
22705        // Presentment 활성 시 참조화폐 표시 비활성화
22706        if (oCurrencyInfo.bPresentmentEnabled === true) {
22707            return '';
22708        }
22709
22710        // 참조화폐 정보
22711        var aSubCurrencyInfo = oCurrencyInfo.aShopSubCurrencyInfo;
22712
22713        if (! aSubCurrencyInfo) {
22714            // 참조화폐가 없으면
22715            return '';
22716
22717        } else {
22718            var aCurrencyInfo = oCurrencyInfo.aShopCurrencyInfo;
22719
22720            if (aSubCurrencyInfo.currency_code === aCurrencyInfo.currency_code) {
22721                // 결제화폐와 참조화폐가 동일하면
22722                return '';
22723            } else {
22724                return CAFE24.SHOP_PRICE.toPrice(fPrice, aSubCurrencyInfo, bIsNumberFormat);
22725            }
22726        }
22727    },
22728
22729    /**
22730     * 쇼핑몰의 기준화폐에 맞게 리턴합니다.
22731     * @param float fPrice 금액
22732     * @param bool bIsNumberFormat number_format 적용 유무
22733     * @param int iShopNo 쇼핑몰번호
22734     * @return float
22735     */
22736    toBasePrice: function(fPrice, bIsNumberFormat, iShopNo)
22737    {
22738        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22739
22740        // 기준화폐 정보
22741        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22742            var aBaseCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[undefined].aBaseCurrencyInfo;
22743        } else {
22744            var aBaseCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo;
22745        }
22746
22747        return CAFE24.SHOP_PRICE.toPrice(fPrice, aBaseCurrencyInfo, bIsNumberFormat);
22748    },
22749
22750    /**
22751     * 결제화폐 금액을 참조화폐 금액으로 변환하여 리턴합니다.
22752     * @param float fPrice 금액
22753     * @param bool bIsNumberFormat number_format 적용 유무
22754     * @param int iShopNo 쇼핑몰번호
22755     * @return float 참조화폐 금액
22756     */
22757    shopPriceToSubPrice: function(fPrice, bIsNumberFormat, iShopNo)
22758    {
22759        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22760
22761        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22762            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[undefined];
22763        } else {
22764            var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo];
22765        }
22766
22767        // Presentment 활성 시 참조화폐 표시 비활성화
22768        if (oCurrencyInfo.bPresentmentEnabled === true) {
22769            return '';
22770        }
22771
22772        // 결제화폐 금액 => 참조화폐 금액
22773        fPrice = fPrice * (oCurrencyInfo.fExchangeSubRate || 0);
22774
22775        return CAFE24.SHOP_PRICE.toShopSubPrice(fPrice, bIsNumberFormat, iShopNo);
22776    },
22777
22778    /**
22779     * 결제화폐 대비 기준화폐 환율 리턴
22780     * @param int iShopNo 쇼핑몰번호
22781     * @return float 결제화폐 대비 기준화폐 환율
22782     */
22783    getRate: function(iShopNo)
22784    {
22785        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22786
22787        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22788            return CAFE24.SHOP_CURRENCY_INFO[undefined].fExchangeRate;
22789        } else {
22790            return CAFE24.SHOP_CURRENCY_INFO[iShopNo].fExchangeRate;
22791        }
22792    },
22793
22794    /**
22795     * 결제화폐 대비 참조화폐 환율 리턴
22796     * @param int iShopNo 쇼핑몰번호
22797     * @return float 결제화폐 대비 참조화폐 환율 (참조화폐가 없는 경우 null을 리턴합니다.)
22798     */
22799    getSubRate: function(iShopNo)
22800    {
22801        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22802
22803        if (typeof CAFE24.SHOP_CURRENCY_INFO[undefined] == 'object') {
22804            return CAFE24.SHOP_CURRENCY_INFO[undefined].fExchangeSubRate;
22805        } else {
22806            return CAFE24.SHOP_CURRENCY_INFO[iShopNo].fExchangeSubRate;
22807        }
22808    },
22809
22810    /**
22811     * 금액을 원하는 화폐코드의 제약조건(소수점 절삭)에 맞춰 리턴합니다.
22812     * @param float fPrice 금액
22813     * @param string aCurrencyInfo 원하는 화폐의 화폐 정보
22814     * @param bool bIsNumberFormat number_format 적용 유무
22815     * @return float|string
22816     */
22817    toPrice: function(fPrice, aCurrencyInfo, bIsNumberFormat)
22818    {
22819        // 소수점 아래 절삭
22820        var iPow = Math.pow(10, aCurrencyInfo['decimal_place']);
22821        fPrice = fPrice * iPow;
22822        if (aCurrencyInfo['round_method_type'] === 'F') {
22823            fPrice = Math.floor(fPrice);
22824        } else if (aCurrencyInfo['round_method_type'] === 'C') {
22825            fPrice = Math.ceil(fPrice);
22826        } else {
22827            fPrice = Math.round(fPrice);
22828        }
22829        fPrice = fPrice / iPow;
22830
22831        if (! fPrice) {
22832            // 가격이 없는 경우
22833            return 0;
22834
22835        } else if (bIsNumberFormat === true) {
22836            // 3자리씩 ,로 끊어서 리턴
22837            var sPrice = fPrice.toFixed(aCurrencyInfo['decimal_place']);
22838            var regexp = /^(-?[0-9]+)([0-9]{3})($|\.|,)/;
22839            while (regexp.test(sPrice)) {
22840                sPrice = sPrice.replace(regexp, "$1,$2$3");
22841            }
22842            return sPrice;
22843
22844        } else {
22845            // 숫자만 리턴
22846            return fPrice;
22847
22848        }
22849    }    
22850};
22851
22852var SHOP_PRICE = CAFE24.getDeprecatedNamespace('SHOP_PRICE');
22853/**
22854 * 화폐 포맷
22855 */
22856CAFE24.SHOP_CURRENCY_FORMAT = {
22857    /**
22858     * 어드민 페이지인지
22859     * @var bool
22860     */
22861    _bIsAdmin: /^\/(admin\/php|disp\/admin|exec\/admin)\//.test(location.pathname) ? true : false,
22862
22863    /**
22864     * iShopNo 쇼핑몰의 결제화폐 포맷을 리턴합니다.
22865     * @param int iShopNo 쇼핑몰번호
22866     * @return array head,tail
22867     */
22868    getShopCurrencyFormat: function(iShopNo)
22869    {
22870        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22871
22872        // 결제화폐 코드
22873        var sCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.currency_code;
22874
22875        if (CAFE24.SHOP_CURRENCY_FORMAT._bIsAdmin === true) {
22876            // 어드민
22877
22878            // 기준화폐 코드
22879            var sBaseCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.currency_code;
22880
22881            if (sCurrencyCode === sBaseCurrencyCode) {
22882                // 결제화폐와 기준화폐가 동일한 경우
22883                return {
22884                    'head': '',
22885                    'tail': ''
22886                };
22887
22888            } else {
22889                return {
22890                    'head': sCurrencyCode + ' ',
22891                    'tail': ''
22892                };
22893            }
22894
22895        } else {
22896            // 프론트
22897            if (CAFE24.SHOP_CURRENCY_INFO[iShopNo].bPresentmentEnabled === true) {
22898                return CAFE24.SHOP_CURRENCY_INFO[iShopNo].aFrontPresentmentCurrencyFormat;
22899            }
22900            return CAFE24.SHOP_CURRENCY_INFO[iShopNo].aFrontCurrencyFormat;
22901        }
22902    },
22903
22904    /**
22905     * iShopNo 쇼핑몰의 참조화폐의 포맷을 리턴합니다.
22906     * @param int iShopNo 쇼핑몰번호
22907     * @return array head,tail
22908     */
22909    getShopSubCurrencyFormat: function(iShopNo)
22910    {
22911        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22912
22913        // 참조화폐 정보
22914        var aSubCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopSubCurrencyInfo;
22915
22916        if (! aSubCurrencyInfo) {
22917            // 참조화폐가 없으면
22918            return {
22919                'head': '',
22920                'tail': ''
22921            };
22922
22923        } else if (CAFE24.SHOP_CURRENCY_FORMAT._bIsAdmin === true) {
22924            // 어드민
22925            return {
22926                'head': '(' + aSubCurrencyInfo.currency_code + ' ',
22927                'tail': ')'
22928            };
22929
22930        } else {
22931            // 프론트
22932            return CAFE24.SHOP_CURRENCY_INFO[iShopNo].aFrontSubCurrencyFormat;
22933        }
22934
22935    },
22936
22937    /**
22938     * 쇼핑몰의 기준화폐의 포맷을 리턴합니다.
22939     * @param int iShopNo 쇼핑몰번호
22940     * @return array head,tail
22941     */
22942    getBaseCurrencyFormat: function(iShopNo)
22943    {
22944        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22945
22946        // 기준화폐 코드
22947        var sBaseCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.currency_code;
22948
22949        // 결제화폐 코드
22950        var sCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.currency_code;
22951
22952        if (sCurrencyCode === sBaseCurrencyCode) {
22953            // 기준화폐와 결제화폐가 동일하면
22954            return {
22955                'head': '',
22956                'tail': ''
22957            };
22958
22959        } else {
22960            // 어드민
22961            return {
22962                'head': '(' + sBaseCurrencyCode + ' ',
22963                'tail': ')'
22964            };
22965
22966        }
22967    },
22968
22969    /**
22970     * 금액 입력란 화폐 포맷용 head,tail
22971     * @param int iShopNo 쇼핑몰번호
22972     * @return array head,tail
22973     */
22974    getInputFormat: function(iShopNo)
22975    {
22976        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
22977
22978        var sCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo;
22979
22980        // 멀티쇼핑몰이 아니고 단위가 '원화'인 경우
22981        if (SHOP.isMultiShop() === false && sCurrencyCode === 'KRW') {
22982            return {
22983                'head': '',
22984                'tail': '원'
22985            };
22986
22987        } else {
22988            return {
22989                'head': '',
22990                'tail': sCurrencyCode
22991            };
22992        }
22993    },
22994
22995    /**
22996     * 해당몰 결제 화폐 코드 반환
22997     * ECHOSTING-266141 대응
22998     * 국문 기본몰 일 경우에는 화폐코드가 아닌 '원' 으로 반환
22999     *
23000     * @param int iShopNo 쇼핑몰번호
23001     * @return string currency_code
23002     */
23003    getCurrencyCode: function(iShopNo)
23004    {
23005        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23006
23007        var sCurrencyCode = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.currency_code;
23008
23009        // 멀티쇼핑몰이 아니고 단위가 '원화'인 경우
23010        if (SHOP.isMultiShop() === false && sCurrencyCode === 'KRW') {
23011            return '원';
23012        } else {
23013            return sCurrencyCode;
23014        }
23015    }
23016
23017};
23018
23019var SHOP_CURRENCY_FORMAT = CAFE24.getDeprecatedNamespace('SHOP_CURRENCY_FORMAT');
23020
23021/**
23022 * 금액 포맷
23023 */
23024CAFE24.SHOP_PRICE_FORMAT = {
23025    /**
23026     * iShopNo 쇼핑몰의 결제화폐에 맞도록 하고 포맷팅하여 리턴합니다.
23027     * @param float fPrice 금액
23028     * @param int iShopNo 쇼핑몰번호
23029     * @return string
23030     */
23031    toShopPrice: function(fPrice, iShopNo)
23032    {
23033        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23034
23035        var aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getShopCurrencyFormat(iShopNo);
23036        var sPrice = CAFE24.SHOP_PRICE.toShopPrice(fPrice, true, iShopNo);
23037        return aFormat.head + sPrice + aFormat.tail;
23038    },
23039
23040    /**
23041     * iShopNo 쇼핑몰의 Presentment 화폐에 맞도록 하고 포맷팅하여 리턴합니다. (화면 표시용)
23042     * Global-e Presentment 활성 시 환율 적용 + Presentment 화폐 포맷 사용,
23043     * 비활성 시 기본 결제화폐 포맷 사용 (toShopPrice와 동일 동작)
23044     * @param float fPrice 금액
23045     * @param int iShopNo 쇼핑몰번호
23046     * @return string
23047     */
23048    toShopPricePresentment: function(fPrice, iShopNo)
23049    {
23050        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23051
23052        var oCurrencyInfo = CAFE24.SHOP_CURRENCY_INFO[iShopNo] || CAFE24.SHOP_CURRENCY_INFO[undefined];
23053        var aFormat;
23054        if (oCurrencyInfo && oCurrencyInfo.bPresentmentEnabled === true) {
23055            aFormat = oCurrencyInfo.aFrontPresentmentCurrencyFormat;
23056        } else {
23057            aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getShopCurrencyFormat(iShopNo);
23058        }
23059        var sPrice = CAFE24.SHOP_PRICE.toShopPricePresentment(fPrice, true, iShopNo);
23060        return aFormat.head + sPrice + aFormat.tail;
23061    },
23062
23063    /**
23064     * iShopNo 쇼핑몰의 참조화폐에 맞도록 하고 포맷팅하여 리턴합니다.
23065     * @param float fPrice 금액
23066     * @param int iShopNo 쇼핑몰번호
23067     * @return string
23068     */
23069    toShopSubPrice: function(fPrice, iShopNo)
23070    {
23071        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23072
23073        var aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getShopSubCurrencyFormat(iShopNo);
23074        var sPrice = CAFE24.SHOP_PRICE.toShopSubPrice(fPrice, true, iShopNo);
23075        return aFormat.head + sPrice + aFormat.tail;
23076    },
23077
23078    /**
23079     * 쇼핑몰의 기준화폐에 맞도록 하고 포맷팅하여 리턴합니다.
23080     * @param float fPrice 금액
23081     * @param int iShopNo 쇼핑몰번호
23082     * @return string
23083     */
23084    toBasePrice: function(fPrice, iShopNo)
23085    {
23086        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23087
23088        var aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getBaseCurrencyFormat(iShopNo);
23089        var sPrice = CAFE24.SHOP_PRICE.toBasePrice(fPrice, true, iShopNo);
23090        return aFormat.head + sPrice + aFormat.tail;
23091    },
23092
23093    /**
23094     * 결제화폐 금액을 참조화폐 금액으로 변환하고 포맷팅하여 리턴합니다.
23095     * @param float fPrice 금액
23096     * @param int iShopNo 쇼핑몰번호
23097     * @return string
23098     */
23099    shopPriceToSubPrice: function(fPrice, iShopNo)
23100    {
23101        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23102
23103
23104        var aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getShopSubCurrencyFormat(iShopNo);
23105        var sPrice = CAFE24.SHOP_PRICE.shopPriceToSubPrice(fPrice, true, iShopNo);
23106
23107        if (CAFE24.CURRENCY_INFO.isUseReferenceCurrency() !== true) { return sPrice; }
23108
23109        return '<span class="eRefPriceUnitHead">' + aFormat.head + '</span><span class="eRefPrice">' + sPrice + '</span><span class="eRefPriceUnitTail">'  + aFormat.tail + '</span>';
23110    },
23111
23112
23113    /**
23114     * 금액을 적립금 단위 명칭 설정에 따라 반환
23115     * @param float fPrice 금액
23116     * @return float|string
23117     */
23118    toShopMileagePrice: function (fPrice, iShopNo) {
23119        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23120        
23121        var sPrice = CAFE24.SHOP_PRICE.toShopPrice(fPrice, true, iShopNo);
23122        if (typeof sMileageUnit !== 'undefined' && CAFE24.UTIL.trim(sMileageUnit) != '') {
23123            sConvertMileageUnit = sMileageUnit.replace('[:PRICE:]', sPrice);
23124            return sConvertMileageUnit;
23125        } else {
23126            return CAFE24.SHOP_PRICE_FORMAT.toShopPrice(fPrice);
23127        }
23128    },
23129
23130    /**
23131     * 금액을 예치금 단위 명칭 설정에 따라 반환
23132     * @param float fPrice 금액
23133     * @return float|string
23134     */
23135    toShopDepositPrice: function (fPrice, iShopNo) {
23136        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23137
23138        var sPrice = CAFE24.SHOP_PRICE.toShopPrice(fPrice, true, iShopNo);
23139        if (typeof sDepositUnit !== 'undefined' || CAFE24.UTIL.trim(sDepositUnit) != '') {
23140            return sPrice + sDepositUnit;
23141        } else {
23142            return CAFE24.SHOP_PRICE_FORMAT.toShopPrice(fPrice);
23143        }
23144    },
23145
23146    /**
23147     * ECHOSTING-610183 Presentment: 금액을 적립금 단위 명칭 설정에 따라 presentment 화폐로 반환
23148     * @param float fPrice 금액 (KRW 기준)
23149     * @param int iShopNo 쇼핑몰번호
23150     * @return string
23151     */
23152    toShopMileagePricePresentment: function (fPrice, iShopNo) {
23153        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23154
23155        var sPrice = CAFE24.SHOP_PRICE.toShopPricePresentment(fPrice, true, iShopNo);
23156        if (typeof sMileageUnit !== 'undefined' && CAFE24.UTIL.trim(sMileageUnit) != '') {
23157            return sMileageUnit.replace('[:PRICE:]', sPrice);
23158        } else {
23159            return CAFE24.SHOP_PRICE_FORMAT.toShopPricePresentment(fPrice);
23160        }
23161    },
23162
23163    /**
23164     * ECHOSTING-610183 Presentment: 금액을 예치금 단위 명칭 설정에 따라 presentment 화폐로 반환
23165     * @param float fPrice 금액 (KRW 기준)
23166     * @param int iShopNo 쇼핑몰번호
23167     * @return string
23168     */
23169    toShopDepositPricePresentment: function (fPrice, iShopNo) {
23170        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23171
23172        var sPrice = CAFE24.SHOP_PRICE.toShopPricePresentment(fPrice, true, iShopNo);
23173        if (typeof sDepositUnit !== 'undefined' || CAFE24.UTIL.trim(sDepositUnit) != '') {
23174            return sPrice + sDepositUnit;
23175        } else {
23176            return CAFE24.SHOP_PRICE_FORMAT.toShopPricePresentment(fPrice);
23177        }
23178    },
23179
23180    /**
23181     * 금액을 부가결제수단(통합포인트) 단위 명칭 설정에 따라 반환
23182     * @param float fPrice 금액
23183     * @return float|string
23184     */
23185    toShopAddpaymentPrice: function (fPrice, sAddpaymentUnit, iShopNo) {
23186        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23187
23188        var sPrice = CAFE24.SHOP_PRICE.toShopPrice(fPrice, true, iShopNo);
23189        if (typeof sDepositUnit !== 'undefined' || CAFE24.UTIL.trim(sDepositUnit) != '') {
23190            return sPrice + sAddpaymentUnit;
23191        } else {
23192            return CAFE24.SHOP_PRICE_FORMAT.toShopPrice(fPrice);
23193        }
23194    },
23195
23196    /**
23197     * 포맷을 제외한 금액정보만 리턴합니다.
23198     * @param {string} sFormattedPrice
23199     * @returns {string}
23200     */
23201    detachFormat: function(sFormattedPrice) {
23202        if (typeof sFormattedPrice === 'undefined' || sFormattedPrice === null) {
23203            return '0';
23204        }
23205
23206        var sPattern = /[0-9.]/;
23207        var sPrice = '';
23208        for (var i = 0; i < sFormattedPrice.length; i++) {
23209            if (sPattern.test(sFormattedPrice[i])) {
23210                sPrice += sFormattedPrice[i];
23211            }
23212        }
23213
23214        return sPrice;
23215    }
23216};
23217
23218var SHOP_PRICE_FORMAT = CAFE24.getDeprecatedNamespace('SHOP_PRICE_FORMAT');
23219CAFE24.SHOP_PRICE_UTIL = {
23220    /**
23221     * iShopNo 쇼핑몰의 결제화폐 금액 입력폼으로 만듭니다.
23222     * @param Element elem 입력폼
23223     * @param bool bUseMinus 마이너스 입력 사용 여부
23224     */
23225    toShopPriceInput: function(elem, iShopNo, bUseMinus)
23226    {
23227        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23228
23229        var iDecimalPlace = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopCurrencyInfo.decimal_place;
23230        bUseMinus ? CAFE24.SHOP_PRICE_UTIL._toPriceInput(elem, i
23230DecimalPlace, bUseMinus) : CAFE24.SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
23231    },
23232
23233    /**
23234     * iShopNo 쇼핑몰의 참조화폐 금액 입력폼으로 만듭니다.
23235     * @param Element elem 입력폼
23236     */
23237    toShopSubPriceInput: function(elem, iShopNo)
23238    {
23239        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23240
23241        var iDecimalPlace = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aShopSubCurrencyInfo.decimal_place;
23242        CAFE24.SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
23243    },
23244
23245    /**
23246     * iShopNo 쇼핑몰의 기준화폐 금액 입력폼으로 만듭니다.
23247     * @param Element elem 입력폼
23248     */
23249    toBasePriceInput: function(elem, iShopNo)
23250    {
23251        iShopNo = parseInt(iShopNo) || CAFE24.SDE_SHOP_NUM;
23252
23253        var iDecimalPlace = CAFE24.SHOP_CURRENCY_INFO[iShopNo].aBaseCurrencyInfo.decimal_place;
23254        CAFE24.SHOP_PRICE_UTIL._toPriceInput(elem, iDecimalPlace);
23255    },
23256
23257    /**
23258     * 소수점 iDecimalPlace까지만 입력 가능하도록 처리
23259     * @param Element elem 입력폼
23260     * @param int iDecimalPlace 허용 소수점
23261     * @param bool bUseMinus 마이너스 입력 사용 여부
23262     */
23263    _toPriceInput: function(elem, iDecimalPlace, bUseMinus)
23264    {
23265        attachEvent(elem, 'keyup', function(e) {
23266            e = e || window.event;
23267            bUseMinus ? replaceToMinusPrice(e.srcElement) : replaceToPrice(e.srcElement);
23268        });
23269        attachEvent(elem, 'blur', function(e) {
23270            e = e || window.event;
23271            bUseMinus ? replaceToMinusPrice(e.srcElement) : replaceToPrice(e.srcElement);
23272        });
23273
23274        // 추가금액에서 마이너스를 입력받기 위해 사용
23275        function replaceToMinusPrice(target) {
23276            var value = target.value;
23277
23278            var regExpTest = new RegExp('^[0-9]*' + (iDecimalPlace ? '' : '\\.[0-9]{0, ' + iDecimalPlace + '}') + '$');
23279
23280            if (regExpTest.test(value) === false) {
23281                value = value.replace(/[^0-9.|\-]/g, '');
23282                if (parseInt(iDecimalPlace)) {
23283                    value = value.replace(/^([0-9]+\.[0-9]+)\.+.*$/, '$1');
23284                    value = value.replace(new RegExp('(\\.[0-9]{' + iDecimalPlace + '})[0-9]*$'), '$1');
23285                } else {
23286                    value = value.replace(/[^(0-9|\-)]/g, '');
23287                }
23288                target.value = value;
23289            }
23290        }
23291
23292        function replaceToPrice(target)
23293        {
23294            var value = target.value;
23295
23296            var regExpTest = new RegExp('^[0-9]*' + (iDecimalPlace ? '' : '\\.[0-9]{0, ' + iDecimalPlace + '}') + '$');
23297            if (regExpTest.test(value) === false) {
23298                value = value.replace(/[^0-9.]/g, '');
23299                if (parseInt(iDecimalPlace)) {
23300                    value = value.replace(/^([0-9]+\.[0-9]+)\.+.*$/, '$1');
23301                    value = value.replace(new RegExp('(\\.[0-9]{' + iDecimalPlace + '})[0-9]*$'), '$1');
23302                } else {
23303                    value = value.replace(/\.+[0-9]*$/, '');
23304                }
23305                target.value = value;
23306            }
23307        }
23308
23309        function attachEvent(elem, sEventName, fn)
23310        {
23311            if (elem.addEventListener) {
23312                elem.addEventListener(sEventName, fn, false);
23313
23314            } else if (elem.attachEvent) {
23315                elem.attachEvent("on" + sEventName, fn);
23316            }
23317        }
23318
23319    }
23320};
23321
23322if (window.jQuery !== undefined) {
23323    $.fn.extend({
23324        toShopPriceInput: function(iShopNo)
23325        {
23326            return this.each(function() {
23327                var iElementShopNo = $(this).data('shop_no') || iShopNo;
23328                CAFE24.SHOP_PRICE_UTIL.toShopPriceInput(this, iElementShopNo);
23329            });
23330        },
23331        toShopSubPriceInput: function(iShopNo)
23332        {
23333            return this.each(function() {
23334                var iElementShopNo = $(this).data('shop_no') || iShopNo;
23335                CAFE24.SHOP_PRICE_UTIL.toShopSubPriceInput(this, iElementShopNo);
23336            });
23337        },
23338        toBasePriceInput: function(iShopNo)
23339        {
23340            return this.each(function() {
23341                var iElementShopNo = $(this).data('shop_no') || iShopNo;
23342                CAFE24.SHOP_PRICE_UTIL.toBasePriceInput(this, iElementShopNo);
23343            });
23344        }
23345    });
23346}
23347
23348// EC$ 별칭용
23349if (typeof window.EC$ === 'function') {
23350    EC$.fn.extend({
23351        toShopPriceInput: function(iShopNo)
23352        {
23353            return this.each(function() {
23354                var iElementShopNo = EC$(this).data('shop_no') || iShopNo;
23355                CAFE24.SHOP_PRICE_UTIL.toShopPriceInput(this, iElementShopNo);
23356            });
23357        },
23358        toShopSubPriceInput: function(iShopNo)
23359        {
23360            return this.each(function() {
23361                var iElementShopNo = EC$(this).data('shop_no') || iShopNo;
23362                CAFE24.SHOP_PRICE_UTIL.toShopSubPriceInput(this, iElementShopNo);
23363            });
23364        },
23365        toBasePriceInput: function(iShopNo)
23366        {
23367            return this.each(function() {
23368                var iElementShopNo = EC$(this).data('shop_no') || iShopNo;
23369                CAFE24.SHOP_PRICE_UTIL.toBasePriceInput(this, iElementShopNo);
23370            });
23371        }
23372    });
23373}
23374
23375var SHOP_PRICE_UTIL = CAFE24.getDeprecatedNamespace('SHOP_PRICE_UTIL');
23376/**
23377 * front - 쿠폰관련 js집합
23378 *
23379 * @package app/Newcoupon
23380 * @subpackage Front
23381 * @author 백병한,신호섭 <[email protected]>
23382 * @since 2013. 05. 06.
23383 * @version 1.0
23384 * */
23385
23386/**
23387 * 시리얼 쿠폰 등록폼의 엔터키 동작 처리추가
23388 */
23389EC$('#frmSerialCoupon').on("keypress", function(e) {
23390    if (e.keyCode == 13) {
23391        return coupon_code_check();
23392    }
23393});
23394
23395EC$('#frmCouponlist').on("keypress", function(e) {
23396    if (e.keyCode == 13) {
23397        return COUPON.useCoupon();
23398    }
23399});
23400
23401
23402function coupon_code_submit()
23403{
23404    if (coupon_code_check() === true) coupon_submit('frmSerialCoupon');
23405}
23406
23407/**
23408 * 시리얼 쿠폰 체크
23409 * @returns {Boolean}
23410 */
23411function coupon_code_check()
23412{
23413    if (COUPON.is_coupon_code_submit === true) {
23414        setTimeout(alert(__('TRY.FEW.MINUTES', 'NEWCOUPON.FRONT.COUPON.JS')), 3000);
23415        location.reload();
23416        return;
23417    }
23418
23419    if (EC$('#frmSerialCoupon #coupon_code').val().length > 35 || EC$('#frmSerialCoupon #coupon_code').val().length < 10) {
23420
23421        if (EC$('#frmSerialCoupon #coupon_code').val().length == 0) {
23422            alert(__('쿠폰번호를 입력해주세요'));
23423        } else {
23424            alert(__('쿠폰번호는 10~35자리 입니다.'));
23425        }
23426
23427        EC$('#frmSerialCoupon #coupon_code').focus();
23428
23429        return false;
23430    }
23431
23432    COUPON.is_coupon_code_submit = true;
23433    return true;
23434
23435}
23436
23437function coupon_product_popup(url, coupon_no)
23438{
23439    window.open(url+'?coupon_no='+coupon_no, 'myshop_coupon_pop_list','width=700,height=630,scrollbars=yes,resizable=yes,menubar=no,toolbar=no,location=no,status=no');
23440
23441}
23442
23443function coupon_submit(sFormName)
23444{
23445    EC$('#'+sFormName).submit();
23446}
23447
23448
23449function listsize_change(sFormName)
23450{
23451    var $f = EC$("#" + sFormName);
23452    if (EC$("#limit").length == 0) {
23453        $f.append("<input type='hidden' id='limit' name='limit'>");
23454    }
23455    EC$("#limit").val(EC$("#list_size option:selected").val());
23456    $f.submit();
23457}
23458
23459function Layer_overload_pop(LayerName,Status)
23460{
23461    try
23462    {
23463        var LayerN;
23464
23465        if (navigator.appName == "Netscape")
23466        {
23467            LayerN = document.getElementById(LayerName).style;
23468            if (Status == 'show') LayerN.visibility = 'visible';
23469            if (Status == 'hide') LayerN.visibility = 'hidden';
23470        }
23471        else
23472        {
23473            LayerN = document.all[LayerName].style;
23474            if (Status == 'show') LayerN.visibility = 'visible';
23475            if (Status == 'hide') LayerN.visibility = 'hidden';
23476        }
23477    }
23478    catch (e)
23479    {
23480    }
23481}
23482
23483
23484var COUPON = {
23485    is_coupon_code_submit: false,
23486    is_coupon_use_submit: false,
23487
23488    viewInfo: function(iCouponNo, oCouponElem)
23489    {
23490        var aPos = EC$(oCouponElem).offset();
23491
23492        var oCoupon = aCouponInfo[iCouponNo];
23493        EC$('#dCouponDetail').remove();
23494
23495        var sHtml = '<div id="dCouponDetail" class="layerTheme"></div>';
23496
23497        EC$('body').append(sHtml);
23498        if (mobileWeb === true) {
23499            try {
23500                EC$('#dCouponDetail').html('<h4><strong>' + __('쿠폰정보') + '</strong></h4>' +
23501                        '<ul class="couponInfo">' +
23502                            '<li><span>' + __('쿠폰명') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_name) + '</li>' +
23503                            '<li><span>' + __('적용상품') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_product_info) + '</li>' +
23504                            '<li><span>' + __('COUPON.BENEFITS', 'NEWCOUPON.FRONT.COUPON.JS') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_content) + ' ' + decodeURIComponent(oCoupon.coupon_max_benefit) + '</li>' +
23505                            '<li><span>' + __('사용조건') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_usecon) + ' ' + decodeURIComponent(oCoupon.region_delivery_msg) + ' ' + decodeURIComponent(oCoupon.foreign_delivery_msg) + '</li>' +
23506                            '<li><span>' + __('발행수량') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_issue) + '</li>' +
23507                            '<li><span>' + __('사용기간') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_period_detail) + '</li>' +
23508                        '</ul>' +
23509                        '<p class="mButton">' +
23510                            '<a href="' + oCoupon.coupon_issue_url + '" class="tSubmit1">' + '<span>' + __('다운받기') + '</span></a>' +
23511                            '<a href="#none" class="tSubmit2" onclick="EC$(\'#dCouponDetail\').remove();">' + '<span>' + __('닫기') + '</span> </a>' +
23512                        '</p>');
23513            } catch (err) {
23514                EC$('#dCouponDetail').html('<h4><strong>' + __('쿠폰정보') + '</strong></h4>' +
23515                        '<ul class="couponInfo">' +
23516                            '<li><span>' + __('쿠폰명') + ' :</span> ' + oCoupon.coupon_name + '</li>' +
23517                            '<li><span>' + __('적용상품') + ' :</span> ' + oCoupon.coupon_product_info + '</li>' +
23518                            '<li><span>
23518' + __('COUPON.BENEFITS', 'NEWCOUPON.FRONT.COUPON.JS') + ' :</span> ' + oCoupon.coupon_content + ' ' + oCoupon.coupon_max_benefit + '</li>' +
23519                            '<li><span>' + __('사용조건') + ' :</span> ' + oCoupon.coupon_usecon + ' ' + oCoupon.region_delivery_msg + ' ' + oCoupon.foreign_delivery_msg + '</li>' +
23520                            '<li><span>' + __('발행수량') + ' :</span> ' + oCoupon.coupon_issue + '</li>' +
23521                            '<li><span>' + __('사용기간') + ' :</span> ' + oCoupon.coupon_period_detail + '</li>' +
23522                        '</ul>' +
23523                        '<p class="mButton">' +
23524                            '<a href="' + oCoupon.coupon_issue_url + '" class="tSubmit1">' + '<span>' + __('다운받기') + '</span></a>' +
23525                            '<a href="#none" class="tSubmit2" onclick="EC$(\'#dCouponDetail\').remove();">' + '<span>' + __('닫기') + '</span> </a>' +
23526                        '</p>');
23527            }
23528
23529            //EC$('#dCouponDetail').offset({top:aPos.top,left:aPos.left-10});
23530            var iLeft = '-' + EC$('#dCouponDetail').width() / 2 + 'px', iTop = '-' + EC$('#dCouponDetail').height() / 2 + 'px';
23531            EC$('#dCouponDetail').css({top: '50%', left: '50%', position: 'fixed', marginTop: iTop, marginLeft: iLeft});
23532
23533        } else {
23534            try {
23535                EC$('#dCouponDetail').html('<h3 class="title">' + __('쿠폰정보') + '</h3>' +
23536                        '<a href="#none" onclick="EC$(\'#dCouponDetail\').remove();">' +
23537                            '<img src="//img.cafe24.com/images/ec_hosting/front/btn_close_003.gif" />' +
23538                        '</a>' +
23539                        '<div class="content">' +
23540                            '<ul>' +
23541                                '<li><span>' + __('쿠폰명') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_name) + '</li>' +
23542                                '<li><span>' + __('적용상품') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_product_info) + '</li>' +
23543                                '<li><span>' + __('COUPON.BENEFITS', 'NEWCOUPON.FRONT.COUPON.JS') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_content) + ' ' + decodeURIComponent(oCoupon.coupon_max_benefit) + '</li>' +
23544                                '<li><span>' + __('사용조건') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_usecon) + ' ' + decodeURIComponent(oCoupon.region_delivery_msg) + ' ' + decodeURIComponent(oCoupon.foreign_delivery_msg) + '</li>' +
23545                                '<li><span>' + __('발행수량') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_issue) + '</li>' +
23546                                '<li><span>' + __('사용기간') + ' :</span> ' + decodeURIComponent(oCoupon.coupon_period_detail) + '</li>' +
23547                            '</ul>' +
23548                        '<a href="' + oCoupon.coupon_issue_url + '&is_popup=' + '&opener_url=' + document.URL + '">' +
23549                            '<img src="//img.echosting.cafe24.com/skin/admin_' + SHOP.getLanguage() + '/product/btn_coupon_download.gif" />' +
23550                        '</a>' +
23551                        '</div>');
23552            } catch (err) {
23553                EC$('#dCouponDetail').html('<h3 class="title">' + __('쿠폰정보') + '</h3>' +
23554                        '<a href="#none" onclick="EC$(\'#dCouponDetail\').remove();">' +
23555                            '<img src="//img.cafe24.com/images/ec_hosting/front/btn_close_003.gif" />' +
23556                        '</a>' +
23557                        '<div class="content">' +
23558                            '<ul>' +
23559                                '<li><span>' + __('쿠폰명') + ' :</span> ' + oCoupon.coupon_name + '</li>' +
23560                                '<li><span>' + __('적용상품') + ' :</span> ' + oCoupon.coupon_product_info + '</li>' +
23561                                '<li><span>' + __('COUPON.BENEFITS', 'NEWCOUPON.FRONT.COUPON.JS') + ' :</span> ' + oCoupon.coupon_content + ' ' + oCoupon.coupon_max_benefit + '</li>' +
23562                                '<li><span>' + __('사용조건') + ' :</span> ' + oCoupon.coupon_useco + ' ' + oCoupon.region_delivery_msg + ' ' + oCoupon.foreign_delivery_msg + '</li>' +
23563                                '<li><span>' + __('발행수량') + ' :</span> ' + oCoupon.coupon_issue + '</li>' +
23564                                '<li><span>' + __('사용기간') + ' :</span> ' + oCoupon.coupon_period_detail + '</li>' +
23565                            '</ul>' +
23566                            '<a href="' + oCoupon.coupon_issue_url + '&is_popup=' + '&opener_url=' + document.URL + '">' +
23567                                '<img src="//img.echosting.cafe24.com/skin/admin_' + SHOP.getLanguage() + '/product/btn_coupon_download.gif" />' +
23568                                '</a>' +
23569                        '</div>');
23570            }
23571
23572            EC$('#dCouponDetail').offset({top: aPos.top+20,left: aPos.left+30});
23573        }
23574
23575    },
23576
23577    useCoupon: function()
23578    {
23579        if (COUPON.is_coupon_use_submit === true) {
23580            setTimeout(alert(__('USE.TRY.IN.FEW.MINUTES', 'NEWCOUPON.FRONT.COUPON.JS')), 3000);
23581            location.reload();
23582            return;
23583        }
23584
23585        var cnt = 0;
23586
23587        for (var i=0;
23587 i<document.frmCouponlist.length; i++) {
23588
23589            if ((document.frmCouponlist.elements[i].type == "checkbox") && (document.frmCouponlist.elements[i].name == "coupon_code[]")) {
23590                if (document.frmCouponlist.elements[i].checked == true)
23591                    cnt = cnt + 1;
23592            }
23593        }
23594
23595        if (cnt < 1) {
23596            alert(__("선택된 쿠폰이 없습니다."));
23597            return false;
23598        }
23599
23600        COUPON.is_coupon_use_submit = true;
23601        document.frmCouponlist.action = '/exec/front/Coupon/Mileage/';
23602        document.frmCouponlist.submit();
23603
23604    },
23605
23606    //쿠폰발급결과 출력
23607    getDownCouponResultForm: function(data)
23608    {
23609        //var total = Object.keys(aCouponInfo).length;
23610        var total = data['total_list'];
23611
23612        var sContent = "<ul>";
23613        if (typeof(data.message) === 'object') {
23614            EC$.each(data.message, function(key, val) {
23615                sContent += '<li>'+val+'</li>';
23616            });
23617        } else {
23618            sContent = '<li>'+data.message+'</li>';
23619        }
23620        sContent += '</ul>';
23621
23622        var iSuccessCnt = 0;
23623        if (typeof(data['issue_list']) !== 'undefined') {
23624            iSuccessCnt = data['issue_list'].length;
23625        }
23626
23627        var aData = {
23628            'total': total,
23629            'success_cnt': iSuccessCnt,
23630            'content': sContent
23631        };
23632
23633        EC$.get(sCouponDownResultUrl, aData, function(formData) {
23634            formData = formData.replace(/\{\$total\}/, parseInt(total))
23635                .replace(/\{\$success_cnt\}/, parseInt(iSuccessCnt))
23636                .replace(/\{\$fail_cnt\}/, parseInt(total - iSuccessCnt))
23637                .replace(/\{\$content\}/, sContent);
23638
23639            //EC$(".xans-coupon-productdetail").first().prepend(formData);
23640            EC$("body").prepend(formData);
23641        });
23642    }
23643};
23644
23645/**
23646 * 상품상세 쿠폰 영역
23647 */
23648CAFE24.SHOP_FRONT_PRODUCT_INFO_COUPON = {
23649
23650    sCouponCacheKey: '',
23651    iExpireTime: 1000 * 60, //1분캐시
23652
23653    /**
23654     * 상품상세 로딩시 호출
23655     * @param iProductNo
23656     * @param iCategoryNo
23657     */
23658    getPrdDetailCouponAjax: function (iProductNo, iCategoryNo) {
23659        var sPath = document.location.pathname;
23660
23661        // ECHOSTING-317844 대응
23662        if (parseInt(iProductNo) < 1 || CAFE24.UTIL.trim(parent.EC$('.ec-product-coupon').html()) != "") {
23663            return;
23664        }
23665
23666        //세션 스토리지 사용 안함이면..
23667        if (!window.sessionStorage) {
23668            EC$.get(EC_FRONT_JS_CONFIG_SHOP.sCouponDownloadPage,{'product_no': iProductNo,'cate_no': iCategoryNo, 'sPath': sPath, 'asyncEmbededPage': 'T'} ,function(sHtml) {
23669                sHtml = sHtml.replace(/<script.*?ind-script\/(optimizer.php|i18n.php|moment.php).*?<\/script>/g, '');
23670                sHtml = sHtml.replace(/<script.*?\/cid.generate.js.*?<\/script>/g, '');
23671                CAFE24.SHOP_FRONT_PRODUCT_INFO_COUPON.displayCouponDownload(sHtml, 'F');
23672            });
23673        } else {
23674            if (this.getCouponCache(iProductNo) == false) {
23675                EC$.get(EC_FRONT_JS_CONFIG_SHOP.sCouponDownloadPage,{'product_no': iProductNo,'cate_no': iCategoryNo, 'sPath': sPath, 'asyncEmbededPage': 'T'} ,function(sHtml) {
23676                    sHtml = sHtml.replace(/<script.*?ind-script\/(optimizer.php|i18n.php|moment.php).*?<\/script>/g, '');
23677                    sHtml = sHtml.replace(/<script.*?\/cid.generate.js.*?<\/script>/g, '');
23678                    CAFE24.SHOP_FRONT_PRODUCT_INFO_COUPON.setCouponcache(sHtml);
23679                });
23680            }
23681
23682        }
23683    },
23684
23685    /**
23686     * view단
23687     * @param sHtml
23688     */
23689    displayCouponDownload: function(sHtml, bSessionStorageFlag) {
23690        document.getElementsByClassName('ec-product-coupon')[0].innerHTML = sHtml;
23691
23692        if (bSessionStorageFlag =='F') { //쿠폰 세션스토리지 사용시에 /layout/basic/js/common.js 토글이벤트가 적용된다.
23693            EC$('div.xans-coupon-productdetailajax .title').click(function (e) {
23694                var toggle = EC$(this).parent('.eToggle');
23695                if (toggle.hasClass('disable') == false) {
23696                    EC$(this).parent('.eToggle').toggleClass('selected');
23697                }
23698            });
23699        }
23700    },
23701
23702    /**
23703     * 쿠폰 html 캐시 처리
23704     * @param sHtml
23705     */
23706    setCouponcache: function(sHtml)
23707    {
23708        window.sessionStorage.setItem(this.sCouponCacheKey, JSON.stringify({
23709            exp: Date.now() + this.iExpireTime,
23710            data: {sHtml: sHtml}
23711        }));
23712        this.displayCouponDownload(sHtml, 'F');
23713    },
23714
23715    /**
23716     * 쿠폰 html 캐시 가져오기
23717     * @returns {boolean}
23718     */
23719    getCouponCache: function(iProductNo)
23720    {
23721        this.sCouponCacheKey = 'coupon_download_' + iProductNo + '_' + CAFE24.SDE_SHOP_NUM;
23722        try {
23723            // 데이터 복구
23724            var oCache = JSON.parse(window.sessionStorage.getItem(this.sCouponCacheKey));
23725            // expire 체크
23726            if (oCache.exp < Date.now()) {
23727                throw 'cache has expired.';
23728            }
23729            // 데이터 체크
23730            if (typeof oCache.data.sHtml === 'undefined') {
23731                throw 'Invalid cache data.';
23732            }
23733            this.displayCouponDownload(oCache.data.sHtml, 'T');
23734        } catch (e) {
23735            // 복구 실패시 캐시 삭제
23736            this.removeCouponCache();
23737            return false;
23738        }
23739        return true;
23740    },
23741
23742    /**
23743     * 쿠폰 html캐시 삭제
23744     */
23745    removeCouponCache: function()
23746    {
23747        // 캐시 삭제
23748        window.sessionStorage.removeItem(this.sCouponCacheKey);
23749    }
23750};
23751
23752var EC_SHOP_FRONT_PRODUCT_INFO_COUPON = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_INFO_COUPON');
23753
23754/**
23755 * jQuery JSON Plugin
23756 * version: 2.3 (2011-09-17)
23757 *
23758 * This document is licensed as free software under the terms of the
23759 * MIT License: http://www.opensource.org/licenses/mit-license.php
23760 *
23761 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
23762 * website's http://www.json.org/json2.js, which proclaims:
23763 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
23764 * I uphold.
23765 *
23766 * It is also influenced heavily by MochiKit's serializeJSON, which is
23767 * copyrighted 2005 by Bob Ippolito.
23768 */
23769
23770(function($) {
23771
23772    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
23773        meta = {
23774            '\b': '\\b',
23775            '\t': '\\t',
23776            '\n': '\\n',
23777            '\f': '\\f',
23778            '\r': '\\r',
23779            '"': '\\"',
23780            '\\': '\\\\'
23781        };
23782
23783    /**
23784     * jQuery.toJSON
23785     * Converts the given argument into a JSON respresentation.
23786     *
23787     * @param o {Mixed} The json-serializble *thing* to be converted
23788     *
23789     * If an object has a toJSON prototype, that will be used to get the representation.
23790     * Non-integer/string keys are skipped in the object, as are keys that point to a
23791     * function.
23792     *
23793     */
23794    $.toJSON = typeof JSON === 'object' && JSON.stringify
23795        ? JSON.stringify
23796        : function(o) {
23797
23798        if (o === null) {
23799            return 'null';
23800        }
23801
23802        var type = typeof o;
23803
23804        if (type === 'undefined') {
23805            return undefined;
23806        }
23807        if (type === 'number' || type === 'boolean') {
23808            return '' + o;
23809        }
23810        if (type === 'string') {
23811            return $.quoteString(o);
23812        }
23813        if (type === 'object') {
23814            if (typeof o.toJSON === 'function') {
23815                return $.toJSON(o.toJSON());
23816            }
23817            if (o.constructor === Date) {
23818                var month = o.getUTCMonth() + 1,
23819                    day = o.getUTCDate(),
23820                    year = o.getUTCFullYear(),
23821                    hours = o.getUTCHours(),
23822                    minutes = o.getUTCMinutes(),
23823                    seconds = o.getUTCSeconds(),
23824                    milli = o.getUTCMilliseconds();
23825
23826                if (month < 10) {
23827                    month = '0' + month;
23828                }
23829                if (day < 10) {
23830                    day = '0' + day;
23831                }
23832                if (hours < 10) {
23833                    hours = '0' + hours;
23834                }
23835                if (minutes < 10) {
23836                    minutes = '0' + minutes;
23837                }
23838                if (seconds < 10) {
23839                    seconds = '0' + seconds;
23840                }
23841                if (milli < 100) {
23842                    milli = '0' + milli;
23843                }
23844                if (milli < 10) {
23845                    milli = '0' + milli;
23846                }
23847                return '"' + year + '-' + month + '-' + day + 'T' +
23848                    hours + ':' + minutes + ':' + seconds +
23849                    '.' + milli + 'Z"';
23850            }
23851            if (o.constructor === Array) {
23852                var ret = [];
23853                for (var i = 0; i < o.length; i++) {
23854                    ret.push($.toJSON(o[i]) || 'null');
23855                }
23856                return '[' + ret.join(',') + ']';
23857            }
23858            var name,
23859                val,
23860                pairs = [];
23861            for (var k in o) {
23862                type = typeof k;
23863                if (type === 'number') {
23864                    name = '"' + k + '"';
23865                } else if (type === 'string') {
23866                    name = $.quoteString(k);
23867                } else {
23868                    // Keys must be numerical or string. Skip others
23869                    continue;
23870                }
23871                type = typeof o[k];
23872
23873                if (type === 'function' || type === 'undefined') {
23874                    // Invalid values like these return undefined
23875                    // from toJSON, however those object members
23876                    // shouldn't be included in the JSON string at all.
23877                    continue;
23878                }
23879                val = $.toJSON(o[k]);
23880                pairs.push(name + ':' + val);
23881            }
23882            return '{' + pairs.join(',') + '}';
23883        }
23884    };
23885
23886    /**
23887     * jQuery.evalJSON
23888     * Evaluates a given piece of json source.
23889     *
23890     * @param src {String}
23891     */
23892    $.evalJSON = typeof JSON === 'object' && JSON.parse
23893        ? JSON.parse
23894        : function(src) {
23895        return eval('(' + src + ')');
23896    };
23897
23898    /**
23899     * jQuery.secureEvalJSON
23900     * Evals JSON in a way that is *more* secure.
23901     *
23902     * @param src {String}
23903     */
23904    $.secureEvalJSON = typeof JSON === 'object' && JSON.parse
23905        ? JSON.parse
23906        : function(src) {
23907
23908        var filtered =
23909            src
23910            .replace(/\\["\\\/bfnrtu]/g, '@')
23911            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
23912            .replace(/(?:^|:|,)(?:\s*\[)+/g, '');
23913
23914        if (/^[\],:{}\s]*$/.test(filtered)) {
23915            return eval('(' + src + ')');
23916        } else {
23917            throw new SyntaxError('Error parsing JSON, source is not valid.');
23918        }
23919    };
23920
23921    /**
23922     * jQuery.quoteString
23923     * Returns a string-repr of a string, escaping quotes intelligently.
23924     * Mostly a support function for toJSON.
23925     * Examples:
23926     * >>> jQuery.quoteString('apple')
23927     * "apple"
23928     *
23929     * >>> jQuery.quoteString('"Where are we going?", she asked.')
23930     * "\"Where are we going?\", she asked."
23931     */
23932    $.quoteString = function(string) {
23933        if (string.match(escapeable)) {
23934            return '"' + string.replace(escapeable, function(a) {
23935                var c = meta[a];
23936                if (typeof c === 'string') {
23937                    return c;
23938                }
23939                c = a.charCodeAt();
23940                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
23941            }) + '"';
23942        }
23943        return '"' + string + '"';
23944    };
23945
23946})(jQuery);
23947
23948/**
23949 * jQuery JSON Plugin
23950 * version: 2.3 (2011-09-17)
23951 *
23952 * This document is licensed as free software under the terms of the
23953 * MIT License: http://www.opensource.org/licenses/mit-license.php
23954 *
23955 * Brantley Harris wrote this plugin. It is based somewhat on the JSON.org
23956 * website's http://www.json.org/json2.js, which proclaims:
23957 * "NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.", a sentiment that
23958 * I uphold.
23959 *
23960 * It is also influenced heavily by MochiKit's serializeJSON, which is
23961 * copyrighted 2005 by Bob Ippolito.
23962 */
23963
23964(function($) {
23965
23966    var escapeable = /["\\\x00-\x1f\x7f-\x9f]/g,
23967        meta = {
23968            '\b': '\\b',
23969            '\t': '\\t',
23970            '\n': '\\n',
23971            '\f': '\\f',
23972            '\r': '\\r',
23973            '"': '\\"',
23974            '\\': '\\\\'
23975        };
23976
23977    /**
23978     * jQuery.toJSON
23979     * Converts the given argument into a JSON respresentation.
23980     *
23981     * @param o {Mixed} The json-serializble *thing* to be converted
23982     *
23983     * If an object has a toJSON prototype, that will be used to get the representation.
23984     * Non-integer/string keys are skipped in the object, as are keys that point to a
23985     * function.
23986     *
23987     */
23988    $.toJSON = typeof JSON === 'object' && JSON.stringify
23989        ? JSON.stringify
23990        : function(o) {
23991
23992        if (o === null) {
23993            return 'null';
23994        }
23995
23996        var type = typeof o;
23997
23998        if (type === 'undefined') {
23999            return undefined;
24000        }
24001        if (type === 'number' || type === 'boolean') {
24002            return '' + o;
24003        }
24004        if (type === 'string') {
24005            return $.quoteString(o);
24006        }
24007        if (type === 'object') {
24008            if (typeof o.toJSON === 'function') {
24009                return $.toJSON(o.toJSON());
24010            }
24011            if (o.constructor === Date) {
24012                var month = o.getUTCMonth() + 1,
24013                    day = o.getUTCDate(),
24014                    year = o.getUTCFullYear(),
24015                    hours = o.getUTCHours(),
24016                    minutes = o.getUTCMinutes(),
24017                    seconds = o.getUTCSeconds(),
24018                    milli = o.getUTCMilliseconds();
24019
24020                if (month < 10) {
24021                    month = '0' + month;
24022                }
24023                if (day < 10) {
24024                    day = '0' + day;
24025                }
24026                if (hours < 10) {
24027                    hours = '0' + hours;
24028                }
24029                if (minutes < 10) {
24030                    minutes = '0' + minutes;
24031                }
24032                if (seconds < 10) {
24033                    seconds = '0' + seconds;
24034                }
24035                if (milli < 100) {
24036                    milli = '0' + milli;
24037                }
24038                if (milli < 10) {
24039                    milli = '0' + milli;
24040                }
24041                return '"' + year + '-' + month + '-' + day + 'T' +
24042                    hours + ':' + minutes + ':' + seconds +
24043                    '.' + milli + 'Z"';
24044            }
24045            if (o.constructor === Array) {
24046                var ret = [];
24047                for (var i = 0; i < o.length; i++) {
24048                    ret.push($.toJSON(o[i]) || 'null');
24049                }
24050                return '[' + ret.join(',') + ']';
24051            }
24052            var name,
24053                val,
24054                pairs = [];
24055            for (var k in o) {
24056                type = typeof k;
24057                if (type === 'number') {
24058                    name = '"' + k + '"';
24059                } else if (type === 'string') {
24060                    name = $.quoteString(k);
24061                } else {
24062                    // Keys must be numerical or string. Skip others
24063                    continue;
24064                }
24065                type = typeof o[k];
24066
24067                if (type === 'function' || type === 'undefined') {
24068                    // Invalid values like these return undefined
24069                    // from toJSON, however those object members
24070                    // shouldn't be included in the JSON string at all.
24071                    continue;
24072                }
24073                val = $.toJSON(o[k]);
24074                pairs.push(name + ':' + val);
24075            }
24076            return '{' + pairs.join(',') + '}';
24077        }
24078    };
24079
24080    /**
24081     * jQuery.evalJSON
24082     * Evaluates a given piece of json source.
24083     *
24084     * @param src {String}
24085     */
24086    $.evalJSON = typeof JSON === 'object' && JSON.parse
24087        ? JSON.parse
24088        : function(src) {
24089        return eval('(' + src + ')');
24090    };
24091
24092    /**
24093     * jQuery.secureEvalJSON
24094     * Evals JSON in a way that is *more* secure.
24095     *
24096     * @param src {String}
24097     */
24098    $.secureEvalJSON = typeof JSON === 'object' && JSON.parse
24099        ? JSON.parse
24100        : function(src) {
24101
24102        var filtered =
24103            src
24104            .replace(/\\["\\\/bfnrtu]/g, '@')
24105            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
24106            .replace(/(?:^|:|,)(?:\s*\[)+/g, '');
24107
24108        if (/^[\],:{}\s]*$/.test(filtered)) {
24109            return eval('(' + src + ')');
24110        } else {
24111            throw new SyntaxError('Error parsing JSON, source is not valid.');
24112        }
24113    };
24114
24115    /**
24116     * jQuery.quoteString
24117     * Returns a string-repr of a string, escaping quotes intelligently.
24118     * Mostly a support function for toJSON.
24119     * Examples:
24120     * >>> jQuery.quoteString('apple')
24121     * "apple"
24122     *
24123     * >>> jQuery.quoteString('"Where are we going?", she asked.')
24124     * "\"Where are we going?\", she asked."
24125     */
24126    $.quoteString = function(string) {
24127        if (string.match(escapeable)) {
24128            return '"' + string.replace(escapeable, function(a) {
24129                var c = meta[a];
24130                if (typeof c === 'string') {
24131                    return c;
24132                }
24133                c = a.charCodeAt();
24134                return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
24135            }) + '"';
24136        }
24137        return '"' + string + '"';
24138    };
24139
24140})(EC$ || jQuery);
24141
24142/**
24143 * 상품연동형 js - for 프론트
24144 */
24145
24146
24147(function($) {
24148
24149    var $Olnk = {
24150         iOlinkTotalPrice: 0, // 저장형 옵션의 가격
24151         iAddOptionTotalPrice: 0, // 추가 구성상품의 가격
24152         aOptionData: new Array(), // 순차적 로딩을 위한 배열
24153         iOptionAddNum: 1, // 필수값을 표시하기 위한 번호
24154         iOptionAddProductNum: 1,
24155         aOptionAddProductNum: new Array(),
24156         aOptionProductData: new Array(),
24157         aOptionProductDataListKey: new Array(),
24158         bAllSelectedOption: false,
24159
24160         getOlnkSelectedItem: function(aStockData, bButton, sDispNonePrice, iProductPrice)
24161         {
24162             var aOption = new Array();
24163             var bItemSelected = false;
24164             var bResult = true;
24165             var sOptionId = '';
24166             var iOptPrice = 0;
24167             var iPrdPrice = CAFE24.SHOP_PRICE.toShopPrice(iProductPrice);
24168
24169             // 운영방식설정 > 회원/비회원 가격표시 설정 반영
24170             if (sDispNonePrice == 'T') {
24171                 iTotalPrice = 0;
24172             } else {
24173                 var sSelector = 'select[id^="'+product_option_id+'"]';
24174                 if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
24175                     var sCompositionCode = EC$(CAFE24.SHOP_FRONT_NEW_OPTION_BIND.oOptionObject).attr('composition-code');
24176                     sSelector = 'select[id^="'+product_option_id+'_'+sCompositionCode+'"]';
24177                 }
24178                 if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
24179                    var aValueNum = [];
24180                    EC$(sSelector).each(function() {
24181                        aValueNum.push(EC$(this).val());
24182                    });
24183                    sOptionId = aValueNum.join('-');
24184                    if (aStockData.hasOwnProperty(sOptionId) === false) {
24185                        sOptionId = 'default';
24186                    }
24187                    iTotalPrice = iPrdPrice + CAFE24.SHOP_PRICE.toShopPrice(aStockData[sOptionId].stock_price);
24188                 } else {
24189                     EC$(sSelector).each(function() {
24190                         var iValNo = parseInt(EC$(this).val());
24191
24192                         if (isNaN(iValNo) === true) {
24193                             return;
24194                         }
24195
24196                         iOptPrice += CAFE24.SHOP_PRICE.toShopPrice(aStockData[iValNo].option_price);
24197                         sOptionId = iValNo;
24198                     });
24199
24200                     iTotalPrice = iPrdPrice + iOptPrice;
24201                 }
24202             }
24203
24204             EC$(sSelector).each(function() {
24205
24206                 if (EC$(this).prop('required') === false && EC$(this).val() === '*') {
24207                     return true;
24208                 }
24209                 aOption.push(EC$(this).val());
24210             });
24211
24212             // 전부 선택인 옵션만 있고 선택된 옵션이 없을때
24213             if ((Olnk.bAllSelectedOption === true || bButton === true) && aOption.length === 0) {
24214                 bItemSelected = true;
24215                 sOptionId = sProductCode;
24216             } else if (ITEM.isOptionSelected(aOption) === true) {
24217                 bItemSelected = true;
24218             }
24219
24220            // 버튼으로 처리 했을때 선택이 모두 되어 있지 않다면 튕겨 내자
24221             if (bButton === true && bItemSelected === false && aOption.length > 0) {
24222                 alert(__('필수 옵션을 선택해주세요.'));
24223                 bResult = false;
24224             }
24225
24226             // 추가입력옵션 체크!!
24227             if (bButton === true && checkAddOption() === false) {
24228                 bItemSelected = false;
24229             }
24230
24231             return {'bResult': bResult, 'bItemSelected': bItemSelected, 'aOption': aOption, 'sOptionId': sOptionId, 'iTotalPrice': iTotalPrice};
24232         },
24233
24234        /**
24235         * 최종가격 표시 핸들링 - 상품상세
24236         */
24237        handleTotalPrice: function(sOptionStockData, iProductPrice, sDispNonePrice, bButton, iManualQuantity) {
24238            var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
24239            var sOptionId = '';
24240            var iTotalPrice = 0;
24241            var iCnt = 1;
24242            var sQuantity = '('+sprintf(__('%s개'), iCnt)+')';
24243            var sPrice = '';
24244
24245            // 옵션 선택 완료 되었을때 check
24246            var aOption = new Array();
24247            var aRequiredData = new Array();
24248            var sOptionText = '';
24249            var aOptionText = new Array();
24250            var bItemSelected = false, bSoldOut = false;
24251            var iTotalQuantity = 0;
24252
24253            var aItemSelectInfo = Olnk.getOlnkSelectedItem(aStockData, bButton, sDispNonePrice, iProductPrice);
24254
24255            bResult = aItemSelectInfo.bResult;
24256            bItemSelected = aItemSelectInfo.bItemSelected;
24257            aOption = aItemSelectInfo.aOption;
24258            if (aItemSelectInfo.sOptionId !== '') {
24259                sOptionId = aItemSelectInfo.sOptionId;
24260            }
24261
24262            iTotalPrice = aItemSelectInfo.iTotalPrice;
24263
24264
24265            if (bItemSelected === true) {
24266                var sOptionText = '';
24267                var iStockNumber = aStockData[sOptionId].stock_number;
24268                var bStock = aStockData[sOptionId].use_stock;
24269                var useSoldOut = aStockData[sOptionId].use_soldout;
24270                var sIsDisplay = aStockData[sOptionId].is_display;
24271                var sIsSelling = aStockData[sOptionId].is_selling;
24272                var sIsReserveStat = aStockData[sOptionId].is_reserve_stat; //예약주문R|Q당일발송
24273                if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
24274                    useSoldOut = 'F';
24275                }
24276
24277                var iBuyUnit = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getBuyUnitQuantity('base');
24278                var iProductMin = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
24279
24280                var iQuantity = (iBuyUnit >= iProductMin ? iBuyUnit : iProductMin);
24281
24282                if (typeof(iManualQuantity) !== 'undefined') {
24283                    iQuantity = iManualQuantity;
24284                }
24285                if (sIsSelling == 'F' || ((iStockNumber < buy_unit || iStockNumber <= 0) && ((bStock === true && useSoldOut === 'T') || sIsDisplay == 'F'))) {
24286                    bSoldOut = true;
24287                    sOptionText = ' <span class="soldOut">['+__('품절')+']</span>';
24288                }
24289
24290                if (bSoldOut === true && isNewProductSkin() === false) {
24291                    alert(__('이 상품은 현재 재고가 부족하여 판매가 잠시 중단되고 있습니다.') + '\n\n' + __('제품명') + ' : ' + product_name);
24292                    return;
24293                }
24294
24295                //( 품절 or 추가메시지)
24296                if (aReserveStockMessage['show_stock_message'] === 'T' && sIsReserveStat !== 'N') {
24297                    var sReserveStockMessage = '';
24298                    bSoldOut = false; //품절 사용 안함
24299
24300                    sReserveStockMessage = aReserveStockMessage[sIsReserveStat];
24301                    sReserveStockMessage = sReserveStockMessage.replace(aReserveStockMessage['stock_message_replace_name'], iStockNumber);
24302                    sReserveStockMessage = sReserveStockMessage.replace('[:PRODUCT_STOCK:]', iStockNumber);
24303
24304                    sOptionText = sOptionText.replace(sReserveStockMessage, '') + ' <span class="soldOut">'+sReserveStockMessage+'</span>';
24305                }
24306
24307                // 예약형 상품은 선택되어진 옵션의 합계로 수량을 체크하지 않는다.
24308                if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
24309                    iTotalQuantity = 0;
24310                } else {
24311                    // 옵션 선택시 재고 수량이 현재 선택되어진 수량보다 적을 경우 alert처리후에 return합니다.
24312                    EC$('.option_box_id').each(function(i) {
24313                        sQuantitySelector = '#' + EC$(this).attr('id').replace('id','quantity');
24314                        if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
24315                            var sCompositionCode = EC$(this).attr('composition-code');
24316                            sQuantitySelector = '#quantity_'+sCompositionCode;
24317                        }
24318                        iTotalQuantity += parseInt(EC$(sQuantitySelector).val());
24319                    });
24320                }
24321
24322
24323                if (iTotalQuantity > 0) {
24324                    iTotalQuantity += iQuantity;
24325                    if (((iStockNumber < iTotalQuantity || iStockNumber <= 0) && ((bStock === true && useSoldOut === 'T') || sIsDisplay == 'F'))) {
24326                        alert(__('재고 수량이 부족하여 더 이상 옵션을 추가하실 수 없습니다.'));
24327                        return;
24328                    }
24329                }
24330
24331                var sSelector = 'select[id^="'+product_option_id+'"]';
24332                if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
24333                    var sCompositionCode = EC$(CAFE24.SHOP_FRONT_NEW_OPTION_BIND.oOptionObject).attr('composition-code');
24334                    if (CAFE24.SHOP_FRONT_NEW_OPTION_BIND.oOptionObject === null) {
24335                        sCompositionCode = CAFE24.SHOP_FRONT_PRODUCT_FUNDING.sCurrentCompositionCode;
24336                    }
24337                    sSelector = 'select[id^="'+product_option_id+'_'+sCompositionCode+'"]';
24338                }
24339
24340                sOptionId = '';
24341                var aOptionTitle = [];
24342                if ((Olnk.bAllSelectedOption === true || bButton === true) && aOption.length === 0) {
24343                    EC$(sSelector).each(function() {
24344                        sSelectedOptionId = EC$(this).attr('id');
24345                        sOptionId += EC$(this).val() + '_'+EC$(this).attr('option_code') +'||';
24346                    });
24347                    aOptionText.push(__('선택한 옵션 없음'));
24348                } else {
24349                    EC$(sSelector).each(function() {
24350                        if (EC$(this).prop('required') === false && EC$(this).val() === '*') {
24351                            return true;
24352                        }
24353                        if (Olnk.getCheckValue(EC$(this).val(),'') === true) {
24354                            sSelectedOptionId = EC$(this).attr('id');
24355                            var sOptionText = EC$('#'+sSelectedOptionId+ ' option:selected').text();
24356                            if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation' && EC$(this).attr('option_title') === 'timestamp') {
24357                                var sDateTimeFormat = sOptionText.includes('T') ? EC_GLOBAL_DATETIME.const.FULL_TIME : EC_GLOBAL_DATETIME.const.DATE_ONLY;
24358                                var sOptionText = EC_GLOBAL_DATETIME.parse('20'+sOptionText, 'shop').format(sDateTimeFormat);
24359                            }
24360                            aOptionText.push(sOptionText);
24361
24362                            aOptionTitle.push({ key: EC$(this).attr('option_title'), value: EC$('#'+sSelectedOptionId+ ' option:selected').text()});
24363                        }
24364                        sOptionId += EC$(this).val() + '_'+EC$(this).attr('option_code') +'||';
24365                    });
24366                }
24367                if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
24368                    var aValueNum = [];
24369                    EC$(sSelector).each(function() {
24370                        aValueNum.push(EC$(this).val());
24371                    });
24372                    sOptionId = aValueNum.join('-');
24373                    TotalAddSale.setParam('product_service_type', 'reservation');
24374                }
24375
24376                iProductPrice = getProductPrice(iQuantity, iTotalPrice, sOptionId, bSoldOut, function(iProductPrice) {
24377                    let sOptionPriceText = '';
24378                    if (isNewProductSkin() === false) {
24379                        if (sIsDisplayNonmemberPrice == 'T') {
24380                            EC$('#span_product_price_text').html(sNonmemberPrice);
24381                        } else {
24382                            EC$('#span_product_price_text').html(CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iProductPrice));
24383                        }
24384                    } else {
24385                        if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
24386                            let iOptionAddPrice = TotalAddSale.getReservationLinkAddPrice(sOptionId);
24387                            if (iOptionAddPrice !== 0) {
24388                                // 추가금액 표기: getOptionPrice로 부호/통화기호 ìˆ
24388œì„œë¥¼ 다른 옵션 타입과 통일
24389                                sOptionPriceText = '(' + getOptionPrice(iOptionAddPrice) + ')';
24390                            }
24391                        }
24392                        setOptionBox(sOptionId, (aOptionText.join('/')) + ' ' + sOptionText , iProductPrice, bSoldOut, sSelectedOptionId, sIsReserveStat, iManualQuantity, aOptionTitle, '', sOptionPriceText);
24393                    }
24394
24395                });
24396
24397
24398            }
24399
24400        },
24401        getOlinkOptionKey: function()
24402        {
24403            var sOptionId = '';
24404            EC$('select[id^="' + product_option_id + '"]').each(function() {
24405                if (EC$(this).prop('required') === false && EC$(this).val() === '*') {
24406                    return true;
24407                }
24408                sOptionId += EC$(this).val() + '_'+EC$(this).attr('option_code') +'||';
24409            });
24410            return sOptionId;
24411        },
24412
24413        /**
24414         * 장바구니 담기시 필요한 파라미터 생성
24415         */
24416        getSelectedItemForBasket: function(sProductCode, oTargets, iQuantity) {
24417            var options = {};
24418            var aOptionData ,aOptionTmp;
24419            var bCheckNum = false;
24420            oTargets.each(function() {
24421                aOptionData = {};
24422
24423                if (EC$(this).val().indexOf('||') >= 0) {
24424                    aOptionTmp = EC$(this).val().split('||');
24425                    for (i = 0; i < aOptionTmp.length; i++) {
24426                        if (aOptionTmp[i] !== '') {
24427                            aOptionData = aOptionTmp[i].split('_');
24428                        }
24429
24430                        if (Olnk.getCheckValue(aOptionData[0],'') === true) {
24431                            options[aOptionData[1]] = aOptionData[0];
24432                            bCheckNum = true;
24433                        }
24434                    }
24435                } else if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
24436                    aOptionTemp = EC$(this).val().split('-');
24437                    for (i = 0; i < aOptionTemp.length; i++) {
24438                        if (Olnk.getCheckValue(aOptionTemp[i],'') === true) {
24439                            options[i] = aOptionTemp[i];
24440                            bCheckNum = true;
24441                        }
24442                    }
24443                } else {
24444                    var optCode = EC$(this).attr('option_code');
24445                    var optValNo = parseInt(EC$(this).val());
24446
24447                    if (optCode == '' || optCode == null) {
24448                        return null;
24449                    }
24450                    if (isNaN(optValNo) === true) {
24451                        optValNo = '';
24452                    }
24453
24454                    if (optValNo !== '') {
24455                        options[optCode] = optValNo;
24456                        bCheckNum = true;
24457                    }
24458
24459                }
24460            });
24461
24462
24463            return {
24464                'product_code': sProductCode,
24465                'quantity': iQuantity,
24466                'options': options,
24467                'bCheckNum': bCheckNum
24468            };
24469        },
24470
24471        /**
24472         * 관심상품 담기시 필요한 파라미터 생성
24473         */
24474        getSelectedItemForWish: function(sProductCode, oTargets) {
24475            var options = {};
24476            var bCheckNum = false;
24477
24478            var aOptionData ,aOptionTmp;
24479            EC$(oTargets).each(function() {
24480
24481                aOptionTmp = EC$(this).val().split('||');
24482                aOptionData = {};
24483                options = {};
24484
24485                for (i = 0; i < aOptionTmp.length; i++) {
24486                    if (aOptionTmp[i] !== '') {
24487                        aOptionData = aOptionTmp[i].split('_');
24488                    }
24489                    //if (/^\*+$/.test(aOptionData[0]) === false) {
24490                    if (Olnk.getCheckValue(aOptionData[0],'') === true) {
24491                        options[aOptionData[1]] = aOptionData[0];
24492                        bCheckNum = true;
24493                    }
24494                }
24495            });
24496
24497            return {
24498                'product_code': sProductCode,
24499                'options': options,
24500                'bCheckNum': bCheckNum
24501            };
24502        },
24503
24504        /**
24505         * 선택된 품목정보 반환
24506         * 상품연동형에서는 item_code 가 선택한 옵션을 뜻하지 않으므로
24507         * 호환성을 위한 모조 값만 할당해준다.
24508         */
24509        getMockItemInfo: function(aInfo) {
24510            var aResult = {
24511                'product_no': aInfo.product_no,
24512                'item_code': aInfo.product_code + '000A',
24513                'opt_id': '000A',
24514                'opt_str': ''
24515            };
24516
24517            return aResult;
24518        },
24519
24520        /**
24521         * 상품연동형 옵션인지 여부 반환
24522         */
24523        isLinkageType: function(sOptionType) {
24524            if (typeof sOptionType === 'string' && sOptionType == 'E') {
24525                return true;
24526            }
24527
24528            return false;
24529        },
24530
24531        /**
24532         * 상품상세(NewProductAction) 관련 js 스크립트를 보면, create_layer 라는 함수가 있다.
24533         * 해당 함수는 ajax 콜을 해서 레이어 팝업으로 띄울 소스코드를 불러오게 되는데, 이때 스크립트 태그도 같이 따라온다.
24534         * 해당 스크립트 태그에서 불러오는 js 파일내부에는 동일한 jquery 코드가 다시한번 오버라이딩이 되는데
24535         * 이렇게 되면 기존에 물려있던 extension 메소드들은 초기화되어 날아가게 된다.
24536         *
24537         * 레이어 팝업이 뜨고 나서, $ 내에 존재해야할 메소드나 멤버변수들이 사라졌다면 이와 같은 현상때문이다.
24538         * 가장 이상적인 처리는 스크립트 태그를 없애는게 가장 좋으나 호출되는 스크립트에 의존적인 코드가 존재하는것으로 보인다.
24539         * 해당영역이 완전히 파악되기 전까진 필요한 부분에서만 예외적으로 동작할 수 있도록 한다.
24540         */
24541        bugfixCreateLayerForWish: function() {
24542            var __nil = jQuery.noConflict(true);
24543        },
24544
24545        /**
24546         * 장바구니 담기시 필요한 파라미터를 일부 조작
24547         */
24548        hookParamForBasket: function(aParam, aInfo) {
24549            if (aInfo.option_type != 'E') {
24550                return aParam;
24551            }
24552
24553            var aItemCode = this.getSelectedItemForBasket(aInfo.product_code, aInfo.targets, aInfo.quantity);
24554
24555            aParam['item_code_before'] = '';
24556            aParam['option_type'] = 'E';
24557            aParam['selected_item_by_etype[]'] = EC$.toJSON(aItemCode);
24558
24559            return aParam;
24560        },
24561
24562        /**
24563         * 관심상품 담기시 필요한 파라미터를 일부 조작
24564         */
24565        hookParamForWish: function(aParam, aInfo) {
24566            if (aInfo.option_type != 'E') {
24567                return aParam;
24568            }
24569
24570            var aItemCode = {};
24571
24572            //
24573            // aInfo.targets 는 구스킨을 사용했을 때 출력되는 옵션 셀렉트 박스의 엘리먼트 객체인데,
24574            // 현재 뉴스킨과 구스킨 구분을 아이디값이 wishlist_option_modify_layer_ 에 해당되는 노드가
24575            // 있는지로 판별하기 때문에 모호함이 존재한다.
24576            // 즉, 뉴스킨을 사용해도 해당 노드가 존재하지 않는 조건이 발생할 수 있기 때문이다.
24577            // 예를 들면, 관심상품상에 담긴 리스트가 모두 옵션이 없는 상품만 있는 경우이거나 아니면
24578            // 옵션이 존재하지만 아무것도 선택되지 않은 상품인 경우 발견이 되지 않을 수 있다.
24579            // 그러므로 이런 경우엔 셀렉트박스를 통해 선택된 옵션을 파악하는 것이 아니라,
24580            // 현재 할당되어 있는 데이터를 기준으로 파라미터를 세팅하도록 한다.
24581            //
24582            if (aInfo.targets.length > 0) {
24583                aItemCode = this.getSelectedItemForBasket(aInfo.product_code, aInfo.targets, aInfo.quantity);
24584            } else {
24585                aItemCode = aInfo.selected_item_by_etype;
24586            }
24587
24588            aParam.push('option_type=E');
24589            aParam.push('selected_item_by_etype[]=' + EC$.toJSON(aItemCode));
24590
24591            return aParam;
24592        },
24593        /**
24594         * 장바구니 담기시 필요한 파라미터 생성 - 구스킨 전용 뉴스킨 사용안함.
24595         */
24596        getSelectedItemForBasketOldSkin: function(sProductCode, oTargets, iQuantity) {
24597            var options = {};
24598            var optCode = '';
24599            var optValNo = '';
24600            var bCheckNum = false;
24601            oTargets.each(function() {
24602                optCode = EC$(this).attr('option_code');
24603                optValNo = parseInt(EC$(this).val());
24604
24605                if (optCode == '' || optCode == null) {
24606                    return null;
24607                }
24608
24609                if (isNaN(optValNo) === false) {
24610                    options[optCode] = EC$(this).val();
24611                    bCheckNum = true;
24612                }
24613            });
24614
24615            return {
24616                'product_code': sProductCode,
24617                'quantity': iQuantity,
24618                'options': options,
24619                'bCheckNum': bCheckNum
24620            };
24621        },
24622        /**
24623         * 관심상품 담기시 필요한 파라미터 생성
24624         */
24625        getSelectedItemForWishOldSkin: function(sProductCode, oTargets) {
24626            var options = {};
24627            var isReturn = true;
24628            var bCheckNum = false;
24629            oTargets.each(function() {
24630                if (isReturn === false) {
24631                    isReturn = false;
24632                    return;
24633                }
24634
24635                var optCode = EC$(this).attr('option_code');
24636                var optValNo = parseInt(EC$(this).val());
24637
24638                //
24639                // 필수입력값 체크
24640                //
24641                if (EC$(this).prop('required') === true) {
24642                    if (isNaN(optValNo) === true) {
24643                        isReturn = false;
24644                        return false;
24645                    }
24646                }
24647
24648                if (optCode == '' || optCode == null) {
24649                    isReturn = false;
24650                    return;
24651                }
24652
24653                if (isNaN(optValNo) === false) {
24654                    options[optCode] = optValNo;
24655                    bCheckNum = true;
24656                }
24657            });
24658
24659            if (isReturn === true) {
24660                return {
24661                    'product_code': sProductCode,
24662                    'options': options,
24663                    'bCheckNum': bCheckNum
24664                };
24665            }
24666
24667            return false;
24668        },
24669
24670        /*
24671         * 상단 옵션 선택후 alert후 옵션 재세팅 ( 상위 옵션이 재 세팅되면 해당 옵션에 하단 옵션들은 reset)
24672         */
24673        getOptionCheckData: function(oTarget) {
24674            //if ((/^\*+$/.test(oTarget.val()) === true && Boolean(oTarget.prop('required')) === true) || oTarget.attr('id') === undefined) {
24675            return !((Olnk.getCheckValue(oTarget.val(), '') === false && oTarget.prop('required') === true) || oTarget.attr('id') === undefined);
24676
24677
24678        },
24679        /**
24680         * 재고 체크 ( 구스킨에서 action시에 필요함.
24681         * 각각의 수량을 전부 합치고 그 합친 수량과 재고 체크
24682         * @param sOptionId 옵션 id
24683         * @returns 품절여부
24684         */
24685        getStockValidate: function (sOptionId , iQuantity) {
24686            var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
24687            var bSoldOut = false;
24688            var iStockNumber , bStock , bStockSoldOut;
24689            // get_stock_info
24690            if (aStockData[sOptionId] == undefined) {
24691                iStockNumber = -1;
24692                bStock = false;
24693                bStockSoldOut = 'F';
24694            } else {
24695                iStockNumber = aStockData[sOptionId].stock_number;
24696                bStock = aStockData[sOptionId].use_stock;
24697                bStockSoldOut = aStockData[sOptionId].use_soldout;
24698
24699            }
24700            if (bStockSoldOut == 'T' && bStock === true && (iStockNumber < iQuantity)) {
24701                bSoldOut = true;
24702            }
24703            return bSoldOut;
24704        },
24705        /*
24706         * check value
24707         */
24708        getCheckValue: function (oTargetValue , oTarget) {
24709            if (/^\*+$/.test(oTargetValue) === true) {
24710                if (oTarget !== '') {
24711                    oTarget.val('*');
24712                }
24713                return false;
24714            }
24715            return true;
24716        },
24717        /*
24718         * 추가 구성상품의 재고 체크
24719         * @param aOptionBoxInfo 추가 구성상품 데이터
24720         */
24721        getAddProductStock: function (aOptionBoxInfo) {
24722            var iTotalQuantity = aOptionBoxInfo['iTotalQuantity'];
24723            if (this.isLinkageType(aOptionBoxInfo['option_type']) === true) {
24724                EC$('.option_add_box_'+aOptionBoxInfo['product_no']).each(function() {
24725                    // 수량 증가시 본인꺼는 빼야 한다..
24726                    if (aOptionBoxInfo['sOptionBoxId'] !== EC$(this).attr('id')) {
24727                        iTotalQuantity += parseInt(iQuantity = EC$('#' + EC$(this).attr('id').replace('id','quantity')).val());
24728                    }
24729
24730                });
24731                if (aOptionBoxInfo['is_stock'] === true && aOptionBoxInfo['use_soldout'] === true && aOptionBoxInfo['stock_number'] < iTotalQuantity) {
24732                    alert(sprintf(__('%s의 재고가 부족합니다.'), aOptionBoxInfo['title']));
24733                    //alert(aOptionBoxInfo['title'] + ' - ' + __('의 재고가 부족합니다.'));
24734                    return false;
24735                }
24736            }
24737        },
24738        /*
24739         * 모든 상품의 옵션이 선택일때 옵션박스가 떨궈지지 않았을 경우 (아무것도 선택안하면 option_box 안생김)
24740         * @param aOptionBoxInfo 추가 구성상품 데이터
24741         */
24742        getProductAllSelected: function (sProductCode, oTargets, iQuantity) {
24743            var bAllSelected = true;
24744            var options = {};
24745            oTargets.each(function(i) {
24746                if (EC$(this).val().indexOf('||') >= 0) {
24747                    aOptionTmp = EC$(this).val().split('||');
24748                    for (i = 0; i < aOptionTmp.length; i++) {
24749                        if (aOptionTmp[i] !== '') {
24750                            aOptionData = aOptionTmp[i].split('_');
24751                        }
24752                        options[aOptionData[1]] = '';
24753                    }
24754                } else {
24755                    if (EC$(this).prop('required') === true || Olnk.getCheckValue(EC$(this).val() , '') === true) {
24756                        bAllSelected = false;
24757                        return false;
24758                    }
24759                    var optCode = EC$(this).attr('option_code');
24760                    var optValNo = parseInt(EC$(this).val());
24761
24762                    if (optCode == '' || optCode == null) {
24763                        return null;
24764                    }
24765                    if (isNaN(optValNo) === true) {
24766                        optValNo = '';
24767                    }
24768                    options[optCode] = optValNo;
24769                }
24770            });
24771
24772            if (bAllSelected === true) {
24773                return {
24774                    'product_code': sProductCode,
24775                    'quantity': iQuantity,
24776                    'options': options
24777                };
24778            } else {
24779                return false;
24780            }
24781
24782        },
24783
24784        /*
24785         * 옵션 추가버튼 ( 신규 스킨의 연동형 옵션일때 품목 추가 버튼 생김)
24786         * totalProducts가 있을때 신규 스킨
24787         * ( NewProductOption.js에 isNewProductSkin이 있지만 의존적 처리가 어려움)
24788         * oPushButton 품목 추가 버튼 Object
24789         */
24790        getOptionPushbutton: function(oPushButton) {
24791            if (typeof(option_push_button) !== 'undefined' && option_push_button === 'T' && oPushButton.length > 0 && isNewProductSkin() === true) {
24792                return true;
24793            } else {
24794                return false;
24795            }
24796
24797        },
24798
24799        /*
24800         * 옵션 추가버튼 action. php 에서 assign된 함수
24801         */
24802        setOptionPushButton: function() {
24803            Olnk.handleTotalPrice(option_stock_data, product_price, sIsDisplayNonmemberPrice , true);
24804        },
24805        /**
24806         * 옵션 추가 버튼 연동형 옵션인 경우에만 동작 하자.(이건 추가구성상품)
24807         * @param iProductNum 상품번호
24808         */
24809        setAddOptionPushButton: function(iProductNum) {
24810            ProductAdd.setAddProductOptionPushButton(iProductNum);
24811        },
24812        setSetOptionPushButton: function(iProductNum) {
24813            ProductSet.setSetProductOptionPushButton(iProductNum);
24814        },
24815
24816        /**
24817         * custom_data에 필요한 품주코드
24818         * @param {string} sProductCode 상품코드
24819         * @param {int} iTotalOptionCount 선택된 품목 개수
24820         * @param {int} iCurrentIndex 현재 인덱스
24821         * @returns {string}
24822         */
24823        getCustomOptionItemCode: function (sProductCode, iTotalOptionCount, iCurrentIndex) {
24824            return sProductCode + '000A_' + (iTotalOptionCount - iCurrentIndex);
24825        }
24826    };
24827
24828    //
24829    // 공개 인터페이스
24830    //
24831    window['Olnk'] = $Olnk;
24832
24833})($);
24834
24835
24836CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS = {
24837    aLoadProductNo : [],
24838    aApiResponseData : [],
24839    oElement : null,
24840    initialize : function() {
24841        var sModuleName = (EC$('[module="ec-product-wms-stock-manage-detail"]').length > 0) ? 'ec-product-wms-stock-manage-detail' : 'ec-product-wms-stock-manage';
24842        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.oElement = EC$('[module="'+sModuleName+'"]');
24843        if (CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.oElement.length < 1) {
24844            return;
24845        }
24846
24847        EC$(window).on('scrollEnd', function() {
24848            CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.loadStock(sModuleName);
24849        });
24850    },
24851
24852    loadStock : function(sModuleName) {
24853        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.setStockStatus(sModuleName)
24854        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.loadWmsStockStatus(sModuleName);
24855    },
24856
24857    setStockStatus : function(sModuleName) {
24858        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.oElement = EC$('[module="'+sModuleName+'"]').not('[hasLoaded="T"]'); // 이미 불러온것은 제외
24859        if (CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.oElement.length < 1) {
24860            return;
24861        }
24862
24863        var bDetailModule = sModuleName === 'ec-product-wms-stock-manage-detail';
24864        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.oElement.each(function () {
24865            var iElementTop = EC$(this).offset().top + EC$(this).height();
24866
24867            var iWindowScroll = EC$(window).scrollTop();
24868            var iWindowTop = iWindowScroll + EC$(window).height();
24869            if ((iElementTop < iWindowTop && iElementTop > iWindowScroll) || bDetailModule === true) {
24870                CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aLoadProductNo.push(EC$(this).attr('product_no'));
24871            }
24872        });
24873
24874        CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.loadWmsStockStatus(sModuleName);
24875    },
24876
24877    loadWmsStockStatus : function(sModuleName) {
24878        if (CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aLoadProductNo.length < 1) {
24879            return;
24880        }
24881
24882        var sType = 'product';
24883        // 상품 상세
24884        var bDetailModule = EC$('[module="ec-product-wms-stock-manage-detail"]').length > 0;
24885        if (bDetailModule === true) {
24886            sType = 'option';
24887        }
24888
24889        EC$.ajax({
24890            url: '/exec/front/Shop/ApiProductWms',
24891            type: 'get',
24892            async: false,
24893            data: {
24894                'product_no': CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aLoadProductNo.join(','),
24895                'type' : sType
24896            },
24897            dataType: 'json',
24898            success: function(oReturn) {
24899                if (oReturn.passed === true) {
24900                    CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aApiResponseData = oReturn.data;
24901
24902                    if (bDetailModule === false) {
24903                        for (x in oReturn.data) {
24904                            //IE8..
24905                            if (x !== 'indexOf') {
24906                                EC$('[module="' + sModuleName + '"][product_no="' + x + '"]').removeAttr('class').addClass(oReturn.data[x].product.class).html(oReturn.data[x].product.text);
24907                            }
24908                        }
24909                    }
24910                }
24911            },
24912            complete: function() {
24913                CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aLoadProductNo.forEac
24913h(function(iProductNo) {
24914                    EC$('[module="'+sModuleName+'"][product_no="'+iProductNo+'"]').attr('hasLoaded', 'T')
24915                });
24916                CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aLoadProductNo = [];
24917            }
24918        });
24919    }
24920};
24921
24922EC$(document).ready(function() {
24923    CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.initialize();
24924});
24925
24926var ECFrontProductjQueryExtent = {};
24927ECFrontProductjQueryExtent.scrollEndTimeout = null;
24928ECFrontProductjQueryExtent.scrollEnd = {
24929    delegateType:"scroll",
24930    bindType:"scroll",    handle:function(event){
24931        var me = this;
24932        var handleObj = event.handleObj;
24933        var arg = arguments;
24934        clearTimeout(ECFrontProductjQueryExtent.scrollEndTimeout);
24935        ECFrontProductjQueryExtent.scrollEndTimeout = setTimeout(function(){
24936            handleObj.handler.apply( me, arg );
24937        },50);
24938    }
24939};
24940jQuery.event.special.scrollEnd = ECFrontProductjQueryExtent.scrollEnd;
24941
24942// 상품 목록
24943CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.setStockStatus('ec-product-wms-stock-manage');
24944
24945// 상품 상세
24946CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.setStockStatus('ec-product-wms-stock-manage-detail');
24947
24948/**
24949 * 품절품목일 경우 품절 문구에대한 처리
24950 */
24951CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT = {
24952    /**
24953     * 품절문구 설정 정보
24954     */
24955    aSoldoutText: null,
24956
24957    /**
24958     * 필수 메서드
24959     * @param iProductNum 상품번호
24960     * @param sItemCode 품목코드
24961     * @returns 설정에따라 품절문구 리턴
24962     * @final
24963     */
24964    get: function(iProductNum, sItemCode) {
24965        return this.getStockText(iProductNum, sItemCode);
24966    },
24967
24968    /**
24969     * 품절문구 설정(기존로직 그대로
24970     * @param iProductNum 상품번호
24971     * @returns 해당 상품의 품절 설정 문구
24972     */
24973    getSoldoutDiplayText: function (iProductNum) {
24974        if (typeof aSoldoutDisplay === 'undefined') {
24975            return CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_SOLDOUT_DEFAULT_TEXT;
24976        }
24977
24978        if (this.aSoldoutText === null) {
24979            if (typeof aSoldoutDisplay === 'string') {
24980                this.aSoldoutText = CAFE24.UTIL.parseJSON(aSoldoutDisplay);
24981            } else {
24982                this.aSoldoutText = aSoldoutDisplay;
24983            }
24984        }
24985
24986        if (typeof this.aSoldoutText[iProductNum] === 'undefined') {
24987            this.aSoldoutText[iProductNum] = CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_SOLDOUT_DEFAULT_TEXT;
24988        }
24989
24990        return this.aSoldoutText[iProductNum];
24991    },
24992
24993    /**
24994     * 해당 품목이 품목일 경우 표시될 품절표시 Text
24995     * @param iProductNum 상품번호
24996     * @param sItemCode 아이템코드
24997     * @returns 표시될 품절문구
24998     */
24999    getStockText: function(iProductNum, sItemCode) {
25000        var sSoldoutText = '';
25001        var bIsSoldout = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isSoldout(iProductNum, sItemCode);
25002
25003        if (bIsSoldout === true) {
25004            sSoldoutText = ' [' + this.getSoldoutDiplayText(iProductNum) + ']';
25005        }
25006
25007        if (typeof(aReserveStockMessage) === 'undefined') {
25008            return sSoldoutText;
25009        }
25010
25011        var aStockData = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getProductStockData(iProductNum);
25012
25013        if (typeof(aStockData[sItemCode]) === 'undefined') {
25014            return sSoldoutText;
25015        }
25016
25017        if (aStockData[sItemCode].is_reserve_stat !== 'N') {
25018            sSoldoutText = aReserveStockMessage[aStockData[sItemCode].is_reserve_stat];
25019            sSoldoutText = sSoldoutText.replace(aReserveStockMessage['stock_message_replace_name'], aStockData[sItemCode].stock_number);
25020            sSoldoutText = sSoldoutText.replace('[:PRODUCT_STOCK:]', aStockData[sItemCode].stock_number);
25021        }
25022
25023        return sSoldoutText;
25024    }
25025};
25026
25027var EC_SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT');
25028
25029/**
25030 * 해당 품목에 대한 추가금액 표시여부
25031 */
25032CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_PRICE = {
25033    /**
25034     * 추가금액 표시여부 설정
25035     */
25036    aOptionPriceDisplayConf: [],
25037
25038    oChooseObject: null,
25039
25040    /**
25041     * 필수 메서드
25042     * @param iProductNum 상품번호
25043     * @param sItemCode 품목코드
25044     * @param eChooseObject 현재 선택한 옵션 Object
25045     * @returns 설정에따라 표시할 경우 품목의 추가금액 리턴
25046     * @final
25047     */
25048    get: function(iProductNum, sItemCode, eChooseObject) {
25049        this.oChooseObject = eChooseObject;
25050        return this.getAddPriceText(iProductNum, sItemCode);
25051    },
25052
25053    /**
25054     * 각 옵션선택시마다 실행되는 가격관련 메서드
25055     * @param oOptionChoose 구분할 옵션박스 object
25056     * @returns bool
25057     */
25058    eachCallback: function(oOptionChoose) {
25059        //구스킨에서 옵션선택시마다 표시항목 판매가부분의 가격에 옵션추가듬액 계산
25060        this.setDisplayProductPriceForOldSkin(oOptionChoose);
25061    },
25062
25063    /**
25064     * 구스킨에서 옵션선택시마다 표시항목 판매가부분의 가격에 옵션추가듬액 계산
25065     * @param oOptionChoose 구분할 옵션박스 object
25066     */
25067    setDisplayProductPriceForOldSkin: function(oOptionChoose) {
25068        //뉴스킨이라면 패스 (ECHOSTING-241102 모바일 관심상품리스트 오류)
25069        if (EC$('#totalProducts').length > 0) {
25070            return;
25071        }
25072
25073        //해당 function이 존재할때만 실행
25074        if (typeof(setOldTotalPrice) !== 'function') {
25075            return;
25076        }
25077
25078        var sID = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionChooseID(oOptionChoose);
25079
25080        //상품상세 메인상품에 대해서만 실행
25081        if (/^product_option_id+/.test(sID) !== true) {
25082            return;
25083        }
25084
25085        //구스킨일 경우 각 옵션선택시마다 실행
25086        try {
25087            setOldTotalPrice();
25088        } catch (e) {
25089            CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oOptionCh
25089oose, '*');
25090        }
25091    },
25092
25093    /**
25094     * 옵션 추가금액에대한 Display텍스트
25095     * @param iProductNum 상품번호
25096     * @param sItemCode 품목코드
25097     * @returns string 옵션 추가금액 Text
25098     */
25099    getAddPriceText: function(iProductNum, sItemCode) {
25100        //추가금액 표시여부
25101        var bIsDisplayOptionPrice = this.getOptionPriceDisplay(iProductNum);
25102
25103        if (bIsDisplayOptionPrice === false) {
25104            return '';
25105        }
25106
25107        var iAddPrice = this.getAddPrice(iProductNum, sItemCode);
25108
25109        if (iAddPrice !== false) {
25110            var sPrefix = '';
25111            if (iAddPrice > 0.00) {
25112                sPrefix = '+';
25113            } else {
25114                sPrefix = '-';
25115            }
25116
25117            //화폐단위가 +- 기호 뒤에와야해서 여기서 양수로 바꿈
25118            iAddPrice = Math.abs(iAddPrice);
25119            // [ECQAINT-79686] presentment 활성 시 결제화폐 환산+통화기호 (비활성 시 헬퍼 내부에서 기존 포맷 폴백)
25120            var sStr = ' (' + sPrefix + (SHOP.isG2G() === true ? CAFE24.SHOP_PRICE.toShopPricePresentment(iAddPrice) : CAFE24.SHOP_PRICE_FORMAT.toShopPricePresentment(iAddPrice)) +')';
25121            //그냥 값을 더할경우 원표시(\)가 &#8361;로 변환되어서 clone으로 다시가져오게 처리
25122            return EC$('<div>').append(sStr).html();
25123        }
25124
25125        return '';
25126    },
25127
25128    /**
25129     * 해당 품목의 추가금액을 가져온다(없을 경우에는 false를 리턴
25130     * @param iProductNum 상품번호
25131     * @param sItemCode 품목코드
25132     * @returns int|boolean 추가금액
25133     */
25134    getAddPrice: function(iProductNum, sItemCode)
25135    {
25136        var aStockData = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getProductStockData(iProductNum);
25137        if (typeof(aStockData[sItemCode].stock_price) !== 'undefined' && parseFloat(aStockData[sItemCode].stock_price) !== 0.00) {
25138            return parseFloat(aStockData[sItemCode].stock_price);
25139        }
25140
25141        return false;
25142    },
25143
25144    /**
25145     * 옵션 추가금액 표시여부 설정
25146     * @param iProductNum 상품번호
25147     * @returns 표시여부
25148     */
25149    getOptionPriceDisplay: function(iProductNum) {
25150        if (typeof CAFE24.SHOP_FRONT_NEW_OPTION_DATA.aOptionPriceDisplayConf[iProductNum] === 'undefined') {
25151            return 'T';
25152        }
25153
25154        return (CAFE24.SHOP_FRONT_NEW_OPTION_DATA.aOptionPriceDisplayConf[iProductNum] === 'T');
25155    }
25156};
25157
25158var EC_SHOP_FRONT_NEW_OPTION_EXTRA_PRICE = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_PRICE');
25159
25160/**
25161 * 옵션 선택 또는 품목선택완료시 상세이미지 변경
25162 */
25163CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE = {
25164    /**
25165     * 모바일과 상세이미지 클래스가 틀려서
25166     */
25167    sDetailImageClass: '',
25168
25169    /**
25170     * 세트상품의 이미지 영역
25171     */
25172    sSetProductImageID: '',
25173
25174    /**
25175     * 스와이프기능을 사용하는 상품상세인지 확인(모바일전용)
25176     */
25177    isSwipe: false,
25178
25179    /**
25180     * 세트상품인지 여부
25181     */
25182    bIsSetProduct: false,
25183
25184    /**
25185     * 각 옵션선택시마다 이미지가 있다면 상세이미지에 반영되도록 함
25186     * @param oOptionChoose 구분할 옵션박스 object
25187     */
25188    eachCallback: function(oOptionChoose) {
25189        this.bIsSetProduct = false;
25190
25191        //세트상품일 경우에 대한 처리
25192        if (/^setproduct_option_+/.test(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectGroup(oOptionChoose)) === true) {
25193            this.bIsSetProduct = true;
25194            this.sSetProductImageID = '#ec-set-product-composed-product-';
25195        }
25196
25197        if (/^addproduct_option_+/.test(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectGroup(oOptionChoose)) === true) {
25198            this.bIsSetProduct = true;
25199            this.sSetProductImageID = '#ec-add-product-composed-product-';
25200        }
25201
25202        if (this.isDisplayImage(oOptionChoose) === false) {
25203            return;
25204        }
25205
25206        var oSelectedOption = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedElement(oOptionChoose);
25207
25208        if (typeof(oSelectedOption.attr('link_image')) === 'undefined' || oSelectedOption.attr('link_image').length < 1) {
25209            return;
25210        }
25211
25212        this.setImage(oSelectedOption.attr('link_image'), true, oOptionChoose);
25213    },
25214
25215    /**
25216     * 옵션 전체 선택완료후 해당 옵션품목에 연결된 이미지를 상세이미지에 반영되도록 함
25217     * @param oOptionChoose 구분할 옵션박스 object
25218     */
25219    completeCallback: function(oOptionChoose) {
25220        //연동형은 제외
25221        if (Olnk.isLinkageType(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionType(oOptionChoose)) === true) {
25222            return;
25223        }
25224
25225        if (this.isDisplayImage(oOptionChoose) === false) {
25226            return;
25227        }
25228
25229        var sItemCode = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getItemCode(oOptionChoose);
25230
25231        if (sItemCode === false) {
25232            return;
25233        }
25234
25235        var iProductNo = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oOptionChoose);
25236
25237        var aStockData = CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getProductStockData(iProductNo);
25238
25239        if (typeof(aStockData[sItemCode].item_image_file) !== 'undefined' && CAFE24.UTIL.trim(aStockData[sItemCode].item_image_file) !== '') {
25240            this.setImage(aStockData[sItemCode].item_image_file, false, oOptionChoose);
25241        }
25242    },
25243
25244    /**
25245     * 이미지 출력이 가능한지 확인
25246     * @param oOptionChoose 구분할 옵션박스 object
25247     * @returns bool
25248     */
25249    isDisplayImage: function(oOptionChoose) {
25250        //세트상품일 경우에 대한 처리
25251        if (this.bIsSetProduct === true) {
25252            return this.isDisplayImageDesignForSetProduct(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oOptionChoose));
25253        } else {
25254            //추가구성상품등은 모두 제외하고 상품상세의 대표상품만 변경
25255            return this.isDisplayImageDesign();
25256        }
25257    },
25258
25259    /**
25260     * 세트상품에서 구성상품의 옵션선택시 이미비 변경 가능여부
25261     * @param iProductNum 상품번호
25262     * @returns {boolean}
25263     */
25264    isDisplayImageDesignForSetProduct: function(iProductNum)
25265    {
25266        var oSetProductImageElement = EC$(this.sSetProductImageID + iProductNum);
25267
25268        //해당 구성상품의 이미지영역이 없거나 id가 지정되지 않았으면 false
25269        if (oSetProductImageElement.length < 1) {
25270            return false;
25271        }
25272
25273        return true;
25274    },
25275
25276    /**
25277     * 디자인에서 이미지가 노출될수있는 디자인인지 확인
25278     * 상품상세에서 동일하게 사용하기위해서 따로 메서드로 분리
25279     * @returns {boolean}
25280     */
25281    isDisplayImageDesign: function()
25282    {
25283        var isMobile = false;
25284        if (typeof(mobileWeb) !== 'undefined' && mobileWeb === true) {
25285            isMobile = true;
25286            this.sDetailImageClass = '.bigImage';
25287        } else {
25288            this.sDetailImageClass = '.BigImage';
25289        }
25290
25291        if (isMobile === true) {
25292            if (EC$('.xans-product-mobileimage').length > 0) {
25293                this.isSwipe = true;
25294            }
25295        }
25296
25297        //상세이미지가 없다면 패스
25298        if (this.isSwipe === false && EC$(this.sDetailImageClass).length < 1) {
25299            return false;
25300        }
25301
25302        return true;
25303    },
25304
25305    /**
25306     * 각 디자인에 따라 옵션 도는 품목이미지를 상세이미지에 노출
25307     * @param sUrl 이미지주소
25308     * @param isOptionFlag 각 옵션의 이미지가 아닌 모든옵션 선택후 품목의 이미지이면 false
25309     * @param oOptionChoose 구분할 옵션박스 object
25310     */
25311    setImage: function(sUrl, isOptionFlag, oOptionChoose)
25312    {
25313        if (this.bIsSetProduct === true) {
25314            EC$(this.sSetProductImageID + CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oOptionChoose)).attr('src', sUrl);
25315        } else {
25316            //스와이프기능을 사용할때
25317            if (this.isSwipe === true) {
25318                if (isOptionFlag === false) {
25319                    //모든 옵션 선택후 품목에 연결이미지
25320                    this.setSwipeImage(sUrl, false);
25321                } else {
25322                    //각 업션에 대한 옵션이미지
25323                    this.setSwipeImage('', true);
25324
25325                    var iIndex = EC$('div.xans-product-mobileimage').find('li img[src="' + sUrl + '"]').parent().index();
25326                    EC$('div.typeSwipe').find('span > button').eq(iIndex).trigger('click');
25327                }
25328            } else {
25329                //스와이프기능을 사용안할때
25330                EC$(this.sDetailImageClass).attr('src', sUrl);
25331            }
25332        }
25333    },
25334
25335    /**
25336     * 모바일 상품상세에서 스와이프 사용중일때
25337     * 각 옵션의 연결이미지는 기존스와이프 영역으로
25338     * 각 품목의 연결이미지는 원래 대표이미지 영역이 나오도록 함
25339     * @param sSrc 해당 이미지 주소(품목 연결이미지일떄만)
25340     * @param bIsShowSlide true => 각 옵션별 연결이미지, false => 각 품목별 연결이미지
25341     * @param iButtonIndex 이미지 선택 버튼 순서값
25342     * @param oTarget 처리할 스와이프 모듈 Object
25343     */
25344    setSwipeImage: function(sSrc, bIsShowSlide, iButtonIndex, oTarget)
25345    {
25346        var oElement = EC$('div.xans-product-mobileimage');
25347        var oSwipe = EC$('div.typeSwipe');
25348        if (bIsShowSlide === true) {
25349            oElement.find('ul.eOptionImageCloneTemplate').remove();
25350            oElement.find('ul').show();
25351
25352            //품목이미지가 노출된후 다시 슬라이드버튼을 누르때 시간차로인대 css가 먹지 않아서 추가
25353            if (typeof(iButtonIndex) !== 'undefined') {
25354
25355                // 만약 파라미터로 받은 특정 스와이프 모듈 Object가 존재하면 해당 모듈에서만 처리하도록 추가
25356                if (typeof(oTarget) !== 'undefined') {
25357                    oSwipe = oTarget;
25358                }
25359
25360                oSwipe.find('span > button').eq(iButtonIndex).addClass('selected');
25361            }
25362        } else {
25363
25364            //첫번째 이미지를 기준으로 height가 정해지기때문에
25365            //두번째 이미지에 할당함
25366            oSwipe.find('span > button').eq(1).trigger('click');
25367            var oClone = oElement.find('ul').clone();
25368            oClone.addClass('eOptionImageCloneTemplate');
25369
25370            //추가이미지가 1개만 있을경우에는 따로 삭제하지 않음
25371            //추가이미지가 하개이면 버튼이 원래 두개이므로 따로 삭제하지 않아도 됨
25372            if (oSwipe.find('span > button').length > 2) {
25373                oClone.find('li').not('li').eq(0).not('li').eq(1).remove();
25374            }
25375            oClone.find('li').eq(1).find('img').attr('src', sSrc);
25376
25377            oSwipe.find('span > button').removeClass('selected');
25378
25379            oElement.find('ul').hide();
25380
25381            oElement.find('ul').eq(0).before(oClone);
25382        }
25383    }
25384};
25385
25386var EC_SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE');
25387
25388/**
25389 * 버튼 또는 미리보기 옵션일 경우 지정된 엘리먼트에 선택한 옵션값 보여주기
25390 */
25391CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM = {
25392    TARGET_ELEMENT_CLASS: '.ec-shop-front-product-option-desc-trigger',
25393    /**
25394     * 각 옵션선택시마다 이미지가 있다면 상세이미지에 반영되도록 함
25395     * @param oOptionChoose 구분할 옵션박스 objectboolean
25396     */
25397    eachCallback: function(oOptionChoose) {
25398        //버튼 또는 미리보기 옵션이 아니면 리턴
25399        if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(oOptionChoose) === false) {
25400            return;
25401        }
25402
25403        //셀렉터에 ""를 안붙이면 가끔 특정상횡에서 스크립트오류
25404        var oTargetOptionChoose = EC$(oOptionChoose).parent();
25405        var oTarget = oTargetOptionChoose.find("" + this.TARGET_ELEMENT_CLASS + "");
25406
25407        //디자인이 없다면 패스
25408        if (EC$(oTarget).length < 1) {
25409            if (CAFE24.checkChannelUI() === true) {
25410                // 부모창을 한번더 찾기
25411                var oTmpTarget = oTargetOptionChoose.parent().find("" + this.TARGET_ELEMENT_CLASS + "");
25412
25413                //그래도 없다면 종료
25414                if (EC$(oTmpTarget).length < 1) {
25415                    return;
25416                }
25417                oTarget = oTmpTarget;
25418            } else {
25419                return;
25420            }
25421        }
25422
25423        var sText = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedText(oOptionChoose);
25424
25425        //선택항목에 text가 있다면
25426        //추후에 셀렉트박스가 추가된다면... *나 **가 선택되었다면 예외처리해야함
25427        if (typeof(sText) !== 'undefined' && CAFE24.UTIL.trim(sText) !== '') {
25428            EC$(oTarget).removeClass('ec-product-value').addClass('ec-product-value');
25429            EC$(oTarget).html(sText);
25430        } else {
25431            EC$(oTarget).removeClass('ec-product-value');
25432            EC$(oTarget).html(EC$(oTarget).attr('data-option_msg'));
25433        }
25434    }
25435};
25436
25437var EC_SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM');
25438
25439CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_ITEMSELECTION = {
25440    oCommon: null,
25441    initObject: function()
25442    {
25443        if (this.oCommon !== null) {
25444            return;
25445        }
25446        this.oCommon = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON;
25447    },
25448    sOptionKey: null,
25449    prefetch: function(oOptionChoose)
25450    {
25451        this.initObject();
25452
25453        if (oSingleSelection.isItemSelectionTypeM() === true) {
25454            return;
25455        }
25456
25457        // 동일한 키로 선택된 상품이 없다면 prefetch는 할일이 없음
25458        var oTarget = this.getDeleteTriggerElement(oOptionChoose);
25459        if (oTarget.length === 0) {
25460            return;
25461        }
25462
25463        if (this.oCommon.getOptionType(oOptionChoose) === 'F') {
25464            return this.prefetchOptionTypeF(oOptionChoose);
25465        }
25466
25467        if (this.oCommon.getOptionType(oOptionChoose) === 'E') {
25468            return this.prefetchOptionTypeE(oOptionChoose);
25469        }
25470
25471        oTarget.click();
25472    },
25473    prefetchOptionTypeE: function(oOptionChoose)
25474    {
25475        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25476        if (sOptionGroup.indexOf('setproduct') < 0) {
25477            this.getDeleteTriggerElement(oOptionChoose).click();
25478            return;
25479        }
25480        var oTarget = this.getDeleteTriggerElement(oOptionChoose);
25481
25482        var sOptionId = oTarget.attr('id').substring(0, oTarget.attr('id').lastIndexOf('_'));
25483        var sOptionKey = EC$('#'+sOptionId+'_id').val();
25484        this.sOptionKey = sOptionKey;
25485
25486        var sContext = this.getDeleteTriggerContext(oOptionChoose);
25487        EC$(sContext).remove();
25488
25489        this.hookIndividualSetProductParameter(sOptionKey);
25490    },
25491    prefetchOptionTypeF: function(oOptionChoose)
25492    {
25493        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25494        var oTarget = this.getDeleteTriggerElement(oOptionChoose);
25495        var sOptionId = oTarget.attr('id').substring(0, oTarget.attr('id').lastIndexOf('_'));
25496        var sOptionKey = EC$('#'+sOptionId+'_id').val();
25497        this.sOptionKey = sOptionKey;
25498
25499        // 추가구성상품
25500        if (sOptionGroup.indexOf('addproduct') > -1) {
25501            var aOptionInfo = EC$('#'+sOptionId+'_id').val().split('||');
25502            sOptionKey = aOptionInfo[0];
25503            this.sOptionKey = sOptionKey;
25504            ProductAdd.delOptionBoxData(sOptionKey);
25505        }
25506
25507        // 일반상품, 추가구성상품 동일
25508        TotalAddSale.removeProductData(sOptionKey);
25509
25510        // 세트상품
25511        if (sOptionGroup.indexOf('setproduct') > -1) {
25512            this.hookIndividualSetProductParameter(sOptionKey);
25513        }
25514    },
25515    eachCallback: function(oOptionChoose)
25516    {
25517        if (oSingleSelection.isItemSelectionTypeM() === true) {
25518            return;
25519        }
25520        var sOptionType = this.oCommon.getOptionType(oOptionChoose);
25521
25522        if (sOptionType === 'F') {
25523            return this.eachCallbackOptionTypeF(oOptionChoose);
25524        }
25525        if (sOptionType === 'E') {
25526            return this.eachCallbackOptionTypeE(oOptionChoose);
25527        }
25528    },
25529    eachCallbackOptionTypeE: function(oOptionChoose)
25530    {
25531        // 뭔가 값이 선택됐을때는 원래 돌던대로 돌린다
25532        if (this.oCommon.getOptionSelectedValue(oOptionChoose) !== '*') {
25533            return;
25534        }
25535        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25536        // 선택한 값이 취소된 경우에만 이 로직을 실행한다
25537        // 모두 선택인 경우에는 하나라도 선택되었는지
25538        if (this.oCommon.validation.checkRequiredOption(sOptionGroup) === false) {
25539            bIsSelectedRequiredOption = this.oCommon.validation.isOptionSelected(oOptionChoose);
25540        } else {
25541            bIsSelectedRequiredOption = this.oCommon.validation.isSelectedRequiredOption(sOptionGroup);
25542        }
25543        // 뭔가 하나 선택되어있는 경우
25544        if (this.oCommon.getItemCode(oOptionChoose) === false && bIsSelectedRequiredOption === true) {
25545            var oOptionGroup = this.oCommon.getOptionLastSelectedElement(sOptionGroup);
25546            if (sOptionGroup.indexOf('addproduct') > -1) {
25547                var iProductNum = this.oCommon.getOptionProductNum(oOptionChoose);
25548                if (this.oCommon.isOptionStyleButton(oOptionChoose) === true) {
25549                    ProductAdd.setAddProductOptionPushButton(iProductNum);
25550                }
25551            } else {
25552                if (typeof(ProductSet) === 'object') {
25553                    if (this.oCommon.isOptionStyleButton(oOptionGroup) === true) {
25554                        var oOptionGroup = EC$('select[product_option_area_select="' + EC$(oOptionGroup).attr('product_option_area') + '"][id="' + EC$(oOptionGroup).attr('ec-dev-id') + '"]');
25555                    }
25556                    oSingleSelection.setProductTargetKey(oOptionGroup, 'setproduct');
25557                    ProductSet.procOptionBox(oOptionGroup);
25558                } else {
25559                    if (typeof(setPrice) === 'function') {
25560                        var sID = this.oCommon.getOptionChooseID(oOptionGroup);
25561                        setPrice(false, true, sID);
25562                    }
25563                }
25564            }
25565        } else {
25566            if (sOptionGroup.indexOf('setproduct') === -1) {
25567                return;
25568            }
25569            this.hookIndividualSetProductParameter(this.sOptionKey);
25570            if (Object.keys(ProductSet.getSetIndividualList()).length > 0) {
25571                TotalAddSale.getCalculatorSalePrice(ProductSet.setTotalPrice);
25572            }
25573        }
25574    },
25575    hookIndividualSetProductParameter: function(sOptionKey)
25576    {
25577        ProductSet.delOptionBoxData(sOptionKey);
25578        // 분리세트 상품 코드 삭제
25579        var oSetIndividualList = ProductSet.getSetIndividualList();
25580        delete oSetIndividualList[sOptionKey];
25581        TotalAddSale.setParam('unit_set_product_no', oSetIndividualList);
25582
25583        // 할인 금액 품목 코드 삭제
25584        TotalAddSale.removeProductData(sOptionKey);
25585
25586        // 아무 옵션이 없는 경우
25587        if (Object.keys(oSetIndividualList).length === 0) {
25588            TotalAddSale.setParam('product', oProductList);
25589            TotalAddSale.setTotalAddSalePrice(0);
25590            ProductSet.setTotalPrice();
25591        } else {
25592            var aProductNo = [];
25593            for (var i = 0; i < Object.keys(oSetIndividualList).length; i++) {
25594                var iProductNum = oSetIndividualList[Object.keys(oSetIndividualList)[i]];
25595                if (aProductNo.indexOf(iProductNum) === -1) {
25596                    aProductNo.push(iProductNum);
25597                }
25598            }
25599            if (aProductNo.length === 1) {
25600                TotalAddSale.setParam('product_no', aProductNo[0]);
25601                TotalAddSale.setParam('is_set', false);
25602            } else {
25603                TotalAddSale.setParam('product_no', iProductNo);
25604                TotalAddSale.setParam('is_set', true);
25605            }
25606        }
25607
25608    },
25609    eachCallbackOptionTypeF: function(oOptionChoose)
25610    {
25611        if (this.oCommon.getOptionSelectedValue(oOptionChoose) === '*') {
25612            var oTarget = this.getDeleteTriggerElement(oOptionChoose);
25613            // 옵션이 실제로 취소되었음
25614            oTarget.click();
25615        } else {
25616            // 다른 옵션으로 변경되었음 - 삭제 액션이 아니라 삭제된거처럼 만들어야함
25617            var sContext = this.getDeleteTriggerContext(oOptionChoose);
25618            EC$(sContext).remove();
25619        }
25620        return true;
25621    },
25622    getDeleteTriggerElement: function(oOptionChoose)
25623    {
25624        var sSelector = this.getDeleteTriggerSelector(oOptionChoose);
25625        var sContext = this.getDeleteTriggerContext(oOptionChoose);
25626
25627        return EC$(sSelector, sContext);
25628    },
25629    getTargetKey: function(oOptionChoose)
25630    {
25631        // 기본상품(옵션없는 상품, 조합형옵션 상품, 연동형 옵션 상품, 일체형 세트상품) : 상품번호
25632        // 독립형 옵션 상품 : 상품번호|옵션순서
25633        // 분리세트 상품 : 구성상품번호|세트상품번호
25634        // 분리세트상품의 독립형 옵션 상품 : 구성상품번호|세트상품번호|옵션순서
25635        var sTargetKey = this.oCommon.getOptionProductNum(oOptionChoose);
25636        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25637        if (sOptionGroup.indexOf('setproduct') > -1) {
25638            if (sSetProductType === 'S') {
25639                sTargetKey = sTargetKey + '|' + iProductNo;
25640            } else {
25641                sTargetKey = iProductNo;
25642            }
25643        }
25644        if (this.oCommon.getOptionType(oOptionChoose) === 'F') {
25645            sTargetKey = sTargetKey + '|' + this.oCommon.getOptionSortNum(oOptionChoose);
25646        }
25647        return sTargetKey;
25648
25649    },
25650    getDeleteTriggerContext: function(oOptionChoose)
25651    {
25652        var sOptionElementType = 'tr';
25653
25654        if (CAFE24.checkChannelUI() === true) {
25655            sOptionElementType = 'div';
25656        }
25657
25658        if (typeof(ProductSet) === 'object') {
25659            sOptionElementType = ProductSet.getOptionElementType();
25660        }
25661
25662        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25663        var sContext = sOptionElementType +'.add_product';
25664        if (sOptionGroup.indexOf('addproduct') < 0) {
25665            sContext = sOptionElementType +'.option_product';
25666        }
25667        var sTargetKey = this.getTargetKey(oOptionChoose);
25668        return sContext+'[target-key="'+ sTargetKey +'"]';
25669    },
25670    getDeleteTriggerSelector: function(oOptionChoose)
25671    {
25672        var sOptionGroup = this.oCommon.getOptionSelectGroup(oOptionChoose);
25673        var sSelector = '.option_add_box_del';
25674        if (sOptionGroup.indexOf('addproduct') < 0) {
25675            sSelector = '.option_box_del';
25676        }
25677        return sSelector;
25678    }
25679};
25680
25681var EC_SHOP_FRONT_NEW_OPTION_EXTRA_ITEMSELECTION = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_ITEMSELECTION');
25682
25683var oSingleSelection = function()
25684{
25685    var sProductTargetKey = null;
25686    var sSingleQuantityInputSelector = 'input.single-quantity-input';
25687    var sIndexKey = '#PRODUCTNUM#';
25688    var sSingleObjectName = 'oSingleItemData['+sIndexKey+']';
25689    var sItemSelectionType = null;
25690
25691    var getTotalPriceSelector = function()
25692    {
25693        return EC$('#totalProducts .total:visible').length > 0 ? '#totalProducts .total' : '.xans-product-detail #totalPrice .total, .xans-product-zoom #totalPrice .total';
25694    };
25695
25696    var isItemSelectionTypeS = function()
25697    {
25698        var bSingleQuantityInputSelector = EC$(sSingleQuantityInputSelector).filter(':visible').length > 0;
25699        // 반응형일시에는 노출되지 않음. 하지만 존재함
25700        if (bSingleQuantityInputSelector === false && CAFE24.checkChannelUI() === true) {
25701            if (sItemSelectionType === 'S') {
25702                return true;
25703            }
25704        }
25705
25706        return bSingleQuantityInputSelector;
25707
25708    };
25709
25710    var isItemSelectionTypeM = function()
25711    {
25712        return EC$(sSingleQuantityInputSelector).filter(':visible').length === 0;
25713    };
25714
25715    var getProductNum = function(oQuantityObject)
25716    {
25717        if (EC$(oQuantityObject).hasClass('single-quantity-input') === true) {
25718            return parseInt(EC$(oQuantityObject).attr('product-no'), 10);
25719        }
25720        if (EC$(oQuantityObject).attr('product-no')) {
25721            return EC$(oQuantityObject).attr('product-no');
25722        }
25723        var sProductNumClass = EC$.grep(EC$(oQuantityObject).attr('class').split(' '), function(sClassName,i) {
25724            return CAFE24.UTIL.trim(sClassName).indexOf('product-no-') === 0;
25725        })[0];
25726        return parseInt(sProductNumClass.replace('product-no-', ''), 10);
25727    };
25728
25729    var getOptionSequenceNum = function(oQuantityObject)
25730    {
25731        if (EC$(oQuantityObject).hasClass('single-quantity-input') === true) {
25732            return parseInt(EC$(oQuantityObject).attr('option-sequence'), 10);
25733        }
25734        if (EC$(oQuantityObject).attr('has-option') === 'F') {
25735            return 1;
25736        }
25737        if (EC$(oQuantityObject).attr('option_type') === 'F' && EC$(oQuantityObject).attr('option_sort_no')) {
25738            return parseInt(EC$(oQuantityObject).attr('option_sort_no'), 10);
25739        }
25740        var sSequenceClass = EC$.grep(EC$(oQuantityObject).attr('class').split(' '), function(sClassName,i) {
25741            return CAFE24.UTIL.trim(sClassName).indexOf('option-sequence-') === 0;
25742        })[0];
25743
25744        return parseInt(sSequenceClass.replace('option-sequence-', ''), 10);
25745    };
25746
25747    var setProductTargetKey = function(oElement, sType)
25748    {
25749        var iTargetProductNum = iProductNo;
25750        var sTargetKey = iProductNo;
25751        var iOptionSequence = 1;
25752        if (typeof(oElement) !== 'undefined') {
25753            if (oElement.hasClass('single-quantity-input') === true || oElement.hasClass('quantity-h
25753andle') === true) {
25754                iTargetProductNum = getProductNum(oElement);
25755                iOptionSequence = getOptionSequenceNum(oElement);
25756            } else {
25757                var oOptionChoose = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setOptionBoxElement(oElement);
25758                iTargetProductNum = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oOptionChoose);
25759                if (isNaN(iTargetProductNum) === true) {
25760                    iTargetProductNum = EC$(oElement).attr('product-no');
25761                }
25762                iOptionSequence = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSortNum(oOptionChoose);
25763            }
25764            sTargetKey = iTargetProductNum;
25765        }
25766        if (sType === 'setproduct') {
25767            if (sSetProductType === 'S') {
25768                sTargetKey = iTargetProductNum+'|'+iProductNo;
25769            }
25770        }
25771        var bAddProductOptionF = false;
25772        var bSetProductOptionF = false;
25773        if (sType === 'addproduct') {
25774            var oOptionChoose = EC$('select#addproduct_option_id_'+iTargetProductNum+'_'+iOptionSequence);
25775            bAddProductOptionF = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionType(oOptionChoose) === 'F';
25776        }
25777        if (sType === 'setproduct') {
25778            var oOptionChoose = EC$('select#setproduct_option_id_'+iTargetProductNum+'_'+iOptionSequence);
25779            bSetProductOptionF = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionType(oOptionChoose) === 'F';
25780        }
25781        if ((typeof(sType) === 'undefined' && option_type === 'F') || bSetProductOptionF === true || bAddProductOptionF === true) {
25782            sTargetKey = sTargetKey+'|'+iOptionSequence;
25783        }
25784        sProductTargetKey = sTargetKey;
25785    };
25786
25787    return {
25788        getProductTargetKey: function()
25789        {
25790            return sProductTargetKey;
25791        },
25792        setProductTargetKey: function(oElement, sType)
25793        {
25794            return setProductTargetKey(oElement, sType);
25795        },
25796        getTotalPriceSelector: function()
25797        {
25798            return getTotalPriceSelector();
25799        },
25800        getProductNum: function(oQuantityButtnObject)
25801        {
25802            return getProductNum(oQuantityButtnObject);
25803        },
25804        getOptionSequence: function(oQuantityButtnObject)
25805        {
25806            return getOptionSequenceNum(oQuantityButtnObject);
25807        },
25808        getQuantityInput: function(oQuantityButtonObject, sContext)
25809        {
25810            var iSequenceNum = getOptionSequenceNum(oQuantityButtonObject);
25811            var iProductNum = getProductNum(oQuantityButtonObject);
25812            if (typeof(sContext) === 'undefined') {
25813                sContext = null;
25814            }
25815
25816            return EC$(sSingleQuantityInputSelector+'[option-sequence='+iSequenceNum+'][product-no='+iProductNum+']', sContext);
25817        },
25818        isItemSelectionTypeS: function()
25819        {
25820            return isItemSelectionTypeS();
25821        },
25822        isItemSelectionTypeM: function()
25823        {
25824            return isItemSelectionTypeM();
25825        },
25826        setItemSelectionType: function(sType)
25827        {
25828            if (typeof(sType) !== 'undefined') {
25829                sItemSelectionType = sType;
25830            }
25831        }
25832    };
25833}();
25834
25835CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET = {
25836    /**
25837     * 장바구니 담기 Ajax완료여부
25838     */
25839    bIsLoadedPriceAjax: false,
25840
25841    /**
25842     * 옵션 선택시 장바구니 바로 담기 기능 사용 여부
25843     */
25844    bIsUseDirectBasket: false,
25845
25846    /**
25847     * 옵션선택후 주석옵션이 선언되어있다면 바로 장바구니담기
25848     * @param oOptionChoose 구분할 옵션박스 object
25849     */
25850    completeCallback: function(oOptionChoose) {
25851        if (this.isAvailableDirectBasket(oOptionChoose) === false) {
25852            return;
25853        }
25854
25855        var oInterval = setInterval(function () {
25856            if (CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET.bIsLoadedPriceAjax === true) {
25857                
25858                //장바구니 담기
25859                product_submit(2, '/exec/front/order/basket/', this);
25860                CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET.bIsLoadedPriceAjax = false;
25861
25862                //옵션박스 제거
25863                EC$('.option_box_del').each(function() {
25864                    EC$(this).trigger('click');
25865                });
25866
25867                //옵션선택값 초기화
25868                EC$('[product_option_area="' + EC$(oOptionChoose).attr('product_option_area') + '"]').each(function() {
25869                    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this, '*', true, true);
25870                });
25871
25872                clearInterval(oInterval);
25873            }
25874        }, 300);
25875    },
25876
25877    /**
25878     * 사용가능한 상태인지 확인
25879     * @param oOptionChoose 값을 가져오려는 옵션박스 object
25880     * @return boolean true : 사용가능, false : 사용불가
25881     */
25882    isAvailableDirectBasket: function (oOptionChoose) {
25883
25884        if (this.bIsUseDirectBasket === false) {
25885            return false;
25886        }
25887
25888        oOptionChoose = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setOptionBoxElement(oOptionChoose);
25889        if (EC$(oOptionChoose).attr('product_type') !== 'product_option') {
25890            return false;
25891        }
25892
25893        return true;
25894    },
25895
25896    /**
25897     * 옵션선택시 장바구니 바로담기 기능
25898     */
25899    setUseDirectBasket: function () {
25900        this.bIsUseDirectBasket = true;
25901    }
25902};
25903
25904var EC_SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET');
25905
25906CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING = {
25907    sCurrentCompositionCode: null,
25908    prefetch: function(oOptionChoose)
25909    {
25910    },
25911    completeCallback: function(oOptionChoose)
25912    {
25913    },
25914    eachCallback: function(oOptionChoose)
25915    {
25916        if (typeof(EC$(oOptionChoose).attr('composition-code')) === 'undefined') {
25917            return true;
25918        }
25919        var sCompositionCode = EC$(oOptionChoose).attr('composition-code');
25920        EC$('input.selected-funding-item[composition-code="'+sCompositionCode+'"]').remove();
25921        this.sCurrentCompositionCode = sCompositionCode;
25922        var sItemCode = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getItemCode(oOptionChoose);
25923        if (sItemCode === false) {
25924            return true;
25925        }
25926        /*
25927        var oItemCode = EC$('<input>').attr({
25928            'type' : 'hidden',
25929            'composition-code' : sCompositionCode
25930        }).addClass('selected-funding-item option_box_id').val(sItemCode);
25931        EC$('.EC-funding-checkbox[value="'+sCompositionCode+'"]').append(oItemCode);
25932         */
25933    }
25934};
25935
25936var EC_SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING');
25937
25938/**
25939 * 재고플러스 사용하는 몰 상품상세 재고현황 표시
25940 */
25941CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS = {
25942
25943    /**
25944     * 조합 분리형 옵션일경우 마지막 옵션 선택시 추가되어야할 문구
25945     * @param iProductNo 상품번호
25946     * @param sItemCode 품목코드
25947     * @returns string 재고현황 텍스트
25948     */
25949    get: function(iProductNo, sItemCode) {
25950        return this.getStockStatus(iProductNo, sItemCode);
25951    },
25952
25953    /**
25954     * 재고 현황 텍스트 반환
25955     * @param iProductNo 상품번호
25956     * @param sItemCode 아이템코드
25957     * @returns string 재고 현황 텍스트
25958     */
25959    getStockStatus: function(iProductNo, sItemCode) {
25960        var sStockText = '';
25961        var oStock;
25962
25963        if (this.getCheckUseWms() === false) {
25964            return sStockText;
25965        }
25966
25967        var oResponse = CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.aApiResponseData;
25968        if (EC$.inArray(iProductNo.toString(), Object.keys(oResponse)) < 0) {
25969            return sStockText;
25970        }
25971
25972        if (typeof sItemCode === 'undefined') {
25973            oStock = oResponse[iProductNo]['product'];
25974        } else {
25975            if (EC$.inArray(sItemCode, Object.keys(oResponse[iProductNo]['option'])) < 0) {
25976                return sStockText;
25977            }
25978            oStock = oResponse[iProductNo]['option'][sItemCode];
25979        }
25980
25981        sStockText = typeof oStock['text'] === 'string' ? ' [' +oStock['text'] + ']' : sStockText;
25982        return sStockText;
25983    },
25984
25985    /**
25986     * 재고플러스 사용여부
25987     * @returns boolean
25988     */
25989    getCheckUseWms: function() {
25990        return typeof CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS !== 'undefined' && CAFE24.SHOP_FRONT_NEW_PRODUCT_WMS_STOCK_STATUS.hasOwnProperty('aApiResponseData') === true;
25991    },
25992
25993    /**
25994     * 재고 현황 텍스트 설정
25995     */
25996    setStockStatus: function() {
25997        if (this.getCheckUseWms() === false) {
25998            return;
25999        }
26000
26001        if (has_option === 'T') {
26002            CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.setHasOptionT();
26003        } else {
26004            CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.setHasOptionF();
26005        }
26006    },
26007
26008    /**
26009     * 옵션 있는 상품 재고현황 텍스트 설정 (조합 일체형)
26010     */
26011    setHasOptionT: function() {
26012        EC$('select[option_select_element="ec-option-select-finder"], ul[option_select_element="ec-option-select-finder"]').each(function() {
26013            var oThis = this;
26014            var iProductNo = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oThis);
26015
26016            if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(oThis) === true) {
26017                EC$(oThis).find('li').each(function() {
26018                    var sOptionText = EC$(this).attr('title') + CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.getStockStatus(iProductNo, EC$(this).attr('option_value'));
26019                    EC$(this).attr('title', sOptionText);
26020                });
26021            } else {
26022                EC$(oThis).find('option').each(function() {
26023                    var sOptionText = EC$(this).text() + CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.getStockStatus(iProductNo, EC$(this).val());
26024                    EC$(this).text(sOptionText);
26025                });
26026            }
26027        });
26028    },
26029
26030    /**
26031     * 옵션 없는 상품 재고현황 텍스트 설정
26032     */
26033    setHasOptionF: function() {
26034        var oStockText = EC$('.ec_product_stockText');
26035        if (oStockText.length < 1) {
26036            return;
26037        }
26038
26039        var sStockText = CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.getStockStatus(iProductNo);
26040        if (sStockText === '') {
26041            return;
26042        }
26043
26044        var sProductStockText = oStockText.html() + sStockText;
26045        oStockText.html(sProductStockText);
26046    }
26047
26048};
26049
26050
26051/**
26052 * 뉴상품 옵션 셀렉트 공통파일
26053 */
26054CAFE24.SHOP_FRONT_NEW_OPTION_COMMON = {
26055    cons: null,
26056
26057    data: null,
26058
26059    bind: null,
26060
26061    validation: null,
26062
26063    /**
26064     * 페이지 로드가 완료되었는지
26065     */
26066    isLoad: false,
26067
26068    initObject: function() {
26069        this.cons = CAFE24.SHOP_FRONT_NEW_OPTION_CONS;
26070        this.data = CAFE24.SHOP_FRONT_NEW_OPTION_DATA;
26071        this.bind = CAFE24.SHOP_FRONT_NEW_OPTION_BIND;
26072        this.validation = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION;
26073    },
26074
26075    /**
26076     * 페이지 로딩시 초기화
26077     */
26078    init: function() {
26079        var oThis = this;
26080        //조합분리형이지만 옵션이 1개인경우
26081        var bIsSolidOption = false;
26082        //첫 로드시에는 첫번째 옵션만 검색
26083        EC$('select[option_select_element="ec-option-select-finder"][option_sort_no="1"], ul[option_select_element="ec-option-select-finder"][option_sort_no="1"]').each(function() {
26084            //연동형이 아닌고 분리형일때만 실행
26085            bIsSolidOption = false;
26086            if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isSeparateOption(this) === true) {
26087                if (Olnk.isLinkageType(EC$(this).attr('option_type')) === false) {
26088                    if (parseInt(EC$('[product_option_area="'+oThis.getOptionSelectGroup(this)+'"]').length) < 2) {
26089                        bIsSolidOption = true;
26090                    }
26091
26092                    oThis.data.initializeSoldoutFlag(EC$(this));
26093
26094                    oThis.setOptionText(EC$(this), bIsSolidOption);
26095                }
26096            }
26097        });
26098    },
26099
26100    /**
26101     * 옵션상품인데 모든옵션이 판매안함+진열안함일때 예외처리
26102     * @param sProductOptionID 옵션 Selectbox ID
26103     */
26104    isValidOptionDisplay: function(sProductOptionID)
26105    {
26106        var iOptionCount = 0;
26107        EC$('select[option_select_element="ec-option-select-finder"][id^="' + sProductOptionID + '"], ul[option_select_element="ec-option-select-finder"][ec-dev-id^="' + sProductOptionID + '"]').each(function() {
26108
26109            if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(this) === true) {
26110                iOptionCount += EC$(this).find('li').length;
26111            } else {
26112                iOptionCount += EC$(this).find('option').length - 2;
26113            }
26114        });
26115
26116        return iOptionCount > 0;
26117    },
26118
26119    /**
26120     * 각 옵션에대해 전체품절인지 확인후
26121     */
26122    setOptionText: function(oOptionChoose, bIsSolidOption) {
26123        var bIsStyleButton = this.isOptionStyleButton(oOptionChoose);
26124        var oTargetOption = null;
26125        if (bIsStyleButton === true) {
26126            oTargetOption = EC$(oOptionChoose).find('li');
26127        } else {
26128            oTargetOption = EC$(oOptionChoose).find('option').filter('[value!="*"][value!="**"]');
26129        }
26130
26131        var bIsDisplaySolout = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isSoldoutOptionDisplay();
26132        var iProductNum = this.getOptionProductNum(oOptionChoose);
26133        var oThis = this;
26134
26135        EC$(oTargetOption).each(function() {
26136            var sValue = oThis.getOptionValue(oOptionChoose, EC$(this));
26137            var isSoldout = CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getSoldoutFlag(iProductNum, sValue);
26138            var bIsDisplay = CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getDisplayFlag(iProductNum, sValue);
26139            var sOptionText = oThis.getOptionText(oOptionChoose, this);
26140
26141            if (bIsDisplay === false) {
26142                EC$(this).remove();
26143                return;
26144            }
26145
26146            //조합분리형인데 옵션이 1개인경우 옵션추가금액을 세팅)
26147            if (bIsSolidOption === true) {
26148                var sItemCode = oThis.data.getItemCode(iProductNum, sValue);
26149
26150                var sAddText = CAFE24.SHOP_FRONT_NEW_OPTION_BIND.setAddText(iProductNum, sItemCode, oOptionChoose);
26151                if (sAddText !== '') {
26152                    sOptionText = sOptionText + sAddText;
26153                }
26154            }
26155
26156            if (isSoldout === true) {
26157                //품절표시안함일때 안보여주도록함(첫번째옵션이라서.. 어쩔수없이 여기서 ㅋ)
26158                //두번째옵션부터는 동적생성이니깐 bind에서처리
26159                if (bIsDisplaySolout === false) {
26160                    EC$(this).remove();
26161                    return;
26162                }
26163                //해당 옵션값 객체가 넘어오면 바로 적용
26164                if (bIsStyleButton === true && CAFE24.checkChannelUI() === false) {
26165                    EC$(this).addClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_SOLDOUT_CLASS);
26166                }
26167
26168                //분리형이면서 전체상품이 품절이면
26169                if (bIsSolidOption !== true) {
26170                    var sSoldoutText = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getSoldoutText(oOptionChoose, sValue);
26171                    sOptionText = sOptionText + ' ' + sSoldoutText;
26172
26173                }
26174            }
26175
26176            oThis.setText(this, sOptionText);
26177
26178        });
26179    },
26180
26181    /**
26182     * 품목이 아닌 각 옵션별로 전체품절인지 황니후 품절이면 품절문구 반환
26183     * @param oOptionChoose
26184     * @param sValue
26185     * @returns {String}
26186     */
26187    getSoldoutText: function(oOptionChoose, sValue) {
26188        var sText = '';
26189
26190        var iProductNum = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionProductNum(oOptionChoose);
26191
26192        if (CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getSoldoutFlag(iProductNum, sValue) === true) {
26193            return '[' + CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT.getSoldoutDiplayText(iProductNum) + ']';
26194        }
26195
26196        return sText;
26197    },
26198
26199    /**
26200     * 셀렉트박스형 옵션인지 버튼형 옵션이지 확인
26201     * @param oOptionChoose 구분할 옵션박스 object
26202     * @returns true => 버튼형옵션, false => 기존 select형 옵션
26203     */
26204    isOptionStyleButton: function(oOptionChoose) {
26205        var sOptionStyle = EC$(oOptionChoose).attr(this.cons.OPTION_STYLE);
26206        if (sOptionStyle === 'preview' || sOptionStyle === 'button' || sOptionStyle === 'radio') {
26207            return true;
26208        }
26209
26210        return false;
26211    },
26212
26213    /**
26214     * div 셀렉트박스형 옵션인지 확인
26215     * @param oOptionChoose 구분할 옵션박스 object
26216     * @returns true => 버튼형옵션, false => 기존 select형 옵션
26217     */
26218    isOptionStyleDivSelect: function(oOptionChoose) {
26219        return (EC$(oOptionChoose).hasClass(this.cons.OPTION_STYLE_DIV_SELECT_CLASS) === true) ? true : false;
26220    },
26221
26222    /**
26223     * 해당 옵션의 옵션출력타입(분리형 : S, 일체형 : C)
26224     * @param oOptionChoose 구분할 옵션박스 object
26225     * @returns 옵션타입
26226     */
26227    getOptionListingType: function(oOptionChoose)
26228    {
26229        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26230        return EC$(oOptionChoose).attr(this.cons.OPTION_LISTING_TYPE);
26231    },
26232
26233    /**
26234     * 해당 옵션의 옵션타입(조합형 : T, 연동형 : E, 독립형 : F)
26235     * @param oOptionChoose 구분할 옵션박스 object
26236     * @returns 옵션타입
26237     */
26238    getOptionType: function(oOptionChoose) {
26239        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26240        return EC$(oOptionChoose).attr(this.cons.OPTION_TYPE);
26241    },
26242
26243    /**
26244     * 해당 옵션의 옵션그룹명을 가져온다
26245     * @param oOptionChoose 구분할 옵션박스 object
26246     * @returns 옵션그룹이름
26247     */
26248    getOptionSelectGroup: function(oOptionChoose) {
26249        return EC$(oOptionChoose).attr(this.cons.GROUP_ATTR_NAME);
26250    },
26251
26252    /**
26253     * sOptionStyleConfirm 에 해당하는 옵션인지 확인
26254     * @param oOptionChoose 구분할 옵션박스 object
26255     * @param sOptionStyleConfirm 옵션스타일(CAFE24.SHOP_FRONT_NEW_OPTION_CONS : OPTION_STYLE_PREVIEW 또는 OPTION_STYLE_BUTTON)
26256     * @return boolean 확인결과
26257     */
26258    isOptionStyle: function(oOptionChoose, sOptionStyleConfirm) {
26259        var sOptionStype = EC$(oOptionChoose).attr(this.cons.OPTION_STYLE);
26260        if (sOptionStype === sOptionStyleConfirm) {
26261            return true;
26262        }
26263
26264        return false;
26265    },
26266
26267    /**
26268     * 해당 옵션의 선택된 Text내용을 가져옴
26269     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26270     * @returns 옵션 내용Text
26271     */
26272    getOptionSelectedText: function(oOptionChoose) {
26273        if (this.isOptionStyleButton(oOptionChoose) === true) {
26274            return EC$(oOptionChoose).find('li.' + this.cons.BUTTON_OPTION_SELECTED_CLASS).attr('title');
26275        } else {
26276            return EC$(oOptionChoose).find('option:selected').text();
26277        }
26278    },
26279
26280    /**
26281     * 해당 옵션의 선택된 값을 가져옴
26282     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26283     * @returns string 옵션값
26284     */
26285    getOptionSelectedValue: function(oOptionChoose) {
26286        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26287
26288        if (this.isOptionStyleButton(oOptionChoose) === true) {
26289            var oTarget = EC$(oOptionChoose).find('li.' + this.cons.BUTTON_OPTION_SELECTED_CLASS);
26290
26291            //버튼형옵션은 *, **값이 없기떄문에 선택된게 없다면 강제리턴
26292            if (oTarget.length < 1) {
26293                return '*';
26294            } else {
26295                return oTarget.attr('option_value');
26296            }
26297        } else {
26298            var sValue = EC$(oOptionChoose).val();
26299            return (CAFE24.UTIL.trim(sValue) === '') ? '*' : sValue;
26300        }
26301    },
26302
26303    /**
26304     * 해당 Element의 값을 가져옴
26305     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26306     * @param oOptionChooseElement 값을 가져오려는 옵션 항목
26307     * @returns string 옵션값
26308     */
26309    getOptionValue: function(oOptionChoose, oOptionChooseElement) {
26310        if (this.isOptionStyleButton(oOptionChoose) === true) {
26311            return EC$(oOptionChooseElement).attr('option_value');
26312        } else {
26313            return EC$(oOptionChooseElement).val();
26314        }
26315    },
26316
26317    /**
26318     * 해당 Element의 Text값을 가져옴
26319     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26320     * @param oOptionChooseElement 값을 가져오려는 옵션 항목
26321     * @returns string 옵션값
26322     */
26323    getOptionText: function(oOptionChoose, oOptionChooseElement) {
26324        if (this.isOptionStyleButton(oOptionChoose) === true) {
26325            return EC$(oOptionChooseElement).attr('title');
26326        } else {
26327            return EC$(oOptionChooseElement).text();
26328        }
26329    },
26330
26331    /**
26332     * 선택된 옵션의 Element를 가져온다
26333     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26334     * @returns 선택옵션의 DOM Element
26335     */
26336    getOptionSelectedElement: function(oOptionChoose) {
26337        if (this.isOptionStyleButton(oOptionChoose) === true) {
26338            return EC$(oOptionChoose).find('li.' + this.cons.BUTTON_OPTION_SELECTED_CLASS);
26339        } else {
26340            return EC$(oOptionChoose).find('option:selected');
26341        }
26342    },
26343
26344    getOptionLastSelectedElement: function(sOptionGroup)
26345    {
26346        var oOptionGroup = this.getGroupOptionObject(sOptionGroup);
26347        var aTempResult = [];
26348        oOptionGroup.each(function(i) {
26349            if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(oOptionGroup[i]) !== '*') {
26350                aTempResult.push(oOptionGroup[i]);
26351            }
26352        });
26353        return EC$(aTempResult[aTempResult.length - 1]);
26354    },
26355
26356    /**
26357     * 해당 옵션의 상품번호를 가져옴
26358     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26359     * @returns int 상품번호
26360     */
26361    getOptionProductNum: function(oOptionChoose) {
26362        return parseInt(EC$(oOptionChoose).attr(this.cons.OPTION_PRODUCT_NUM));
26363    },
26364
26365    /**
26366     * 해당 옵션의 순번을 가져옴
26367     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26368     * @returns int 해당 옵션의 순서 번호
26369     */
26370    getOptionSortNum: function(oOptionChoose) {
26371        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26372        return parseInt(EC$(oOptionChoose).attr(this.cons.OPTION_SORT_NUM));
26373    },
26374
26375    /**
26376     * 이벤트 옵션까지에대해 현재까지 선택된 옵션값 배열
26377     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26378     * @param bIsString 값이 true이면 선택된 옵션들을 구분자로 join해서 받아온다
26379     * @returns 현재까지 선택된 옵션값 배열
26380     */
26381    getAllSelectedValue: function(oOptionChoose, bIsString) {
26382        var iOptionSortNum = this.getOptionSortNum(oOptionChoose);
26383
26384        //지금까지 선택된 옵션의 값
26385        var aSelectedValue = [];
26386        EC$('[product_option_area="'+EC$(oOptionChoose).attr(this.cons.GROUP_ATTR_NAME)+'"]').each(function() {
26387            if (parseInt(EC$(this).attr('option_sort_no')) <= iOptionSortNum) {
26388                aSelectedValue.push(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(EC$(this)));
26389            }
26390        });
26391
26392        return (bIsString === true) ? aSelectedValue.join(this.cons.OPTION_GLUE) : aSelectedValue;
26393    },
26394
26395    /**
26396     * iSelectedOptionSortNum 의 하위옵션을 초기화(0일때는 모두초기화)ㅅ
26397     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26398     * @param iSelectedOptionSortNum 하위옵션을 초기화할 대상 옵션 순번
26399     */
26400    setInitializeDefault: function(oOptionChoose, iSelectedOptionSortNum) {
26401        var sOptionGroup = EC$(oOptionChoose).attr(this.cons.GROUP_ATTR_NAME);
26402        var iProductNum = this.getOptionProductNum(oOptionChoose);
26403        this.bind.setInitializeDefault(sOptionGroup, iSelectedOptionSortNum, iProductNum);
26404    },
26405
26406    /**
26407     * 외부에서 기존스크립트가 호출할때는 버튼형옵션객체가 아니라 숨겨진 셀렉트박스에서 호출하므로 버튼형옵션객체를 찾아서 리턴
26408     */
26409    setOptionBoxElement: function(oOptionChoose) {
26410        if (typeof(EC$(oOptionChoose).attr('product_option_area_select')) !== 'undefined') {
26411            oOptionChoose = EC$('ul[product_option_area="'+EC$(oOptionChoose).attr('product_option_area_select')+'"][ec-dev-id="'+EC$(oOptionChoose).attr('id')+'"]');
26412        }
26413
26414        return oOptionChoose;
26415    },
26416
26417    /**
26418     * 선택한 옵션 하위옵션 모두 초기화(추가구성상품에서 연동형옵션때문에...)
26419     * @param oOptionChoose
26420     */
26421    setAllClear: function(oOptionChoose) {
26422        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26423
26424        var iSortNo = parseInt(this.getOptionSortNum(oOptionChoose));
26425        EC$(this.getGroupOptionObject(this.getOptionSelectGroup(oOptionChoose))).each(function() {
26426            if (iSortNo < parseInt(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSortNum(EC$(this)))) {
26427                CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(EC$(this), '*');
26428            }
26429        });
26430    },
26431
26432    /**
26433     * 멀티옵션(구스킨)에서 사용할때 해당 옵션의 id값을 바꾸는기능이 있어서 추가
26434     * @param oOptionChooseOrg
26435     * @param sId
26436     */
26437    setID: function(oOptionChooseOrg, sId) {
26438        if (EC$(oOptionChooseOrg).attr('option_style') === 'select') {
26439            oOptionChoose = oOptionChooseOrg;
26440        } else {
26441            oOptionChoose = EC$(oOptionChooseOrg).parent().find('ul[option_style="preview"], [option_style="button"], [option_style="radio"]');
26442        }
26443
26444        if (this.isOptionStyleButton(oOptionChoose) === true) {
26445            EC$(oOptionChoose).attr('ec-dev-id', sId);
26446            EC$(oOptionChooseOrg).attr('id', sId);
26447        } else {
26448            EC$(oOptionChoose).attr('id', sId);
26449        }
26450    },
26451
26452    /**
26453     * 멀티옵션(구스킨)에서 사용할때 해당 옵션의 id값을 바꾸는기능이 있어서 추가
26454     * @param oOptionChooseOrg
26455     * @param sGroupID
26456     */
26457    setGroupArea: function(oOptionChooseOrg, sGroupID) {
26458        var oOptionChoose = null;
26459        if (EC$(oOptionChooseOrg).attr('option_style') === 'select') {
26460            oOptionChoose = oOptionChooseOrg;
26461        } else {
26462            oOptionChoose = EC$(oOptionChooseOrg).parent().find('ul[option_style="preview"], [option_style="button"], [option_style="radio"]');
26463        }
26464
26465        if (this.isOptionStyleButton(oOptionChoose) === true) {
26466            EC$(oOptionChoose).attr('product_option_area', sGroupID);
26467            EC$(oOptionChooseOrg).attr('product_option_area_select', sGroupID);
26468        } else {
26469            EC$(oOptionChoose).attr('product_option_area', sGroupID);
26470        }
26471    },
26472
26473    /**
26474     * 해당 선택한 옵션의 text값을 세팅
26475     */
26476    setText: function(oSelectecOptionChoose, sText) {
26477        oOptionChoose = this.setOptionBoxElement(EC$(oSelectecOptionChoose).parent());
26478
26479        if (this.isOptionStyleButton(oOptionChoose) === true) {
26480            var sValue = EC$(oSelectecOptionChoose).attr('option_value');
26481            var oTarget = EC$(oOptionChoose).find('li[option_value="'+sValue+'"]');
26482            EC$(oTarget).attr('title', sText);
26483        }
26484
26485        if (sYtshopping === 'T' || sIsYoutubeShops === 'T') {
26486            // 조합분리형, 옵션이 한개, 유튜브샵스인경우
26487            EC$(oTarget).find('a>span').text(sText);
26488        }
26489
26490        if (this.isOptionStyleButton(EC$(oSelectecOptionChoose).parent()) !== true) {
26491            EC$(oSelectecOptionChoose).text(sText);
26492        }
26493    },
26494
26495    /**
26496     * 추가 이미지에서 추출한 품목 코드를 바탕으로 옵션 선택
26497     * @param sItemCode 품목 코드
26498     */
26499    setValueByAddImage: function(sItemCode) {
26500        if (typeof(sItemCode) === 'undefined') {
26501            return;
26502        }
26503
26504        this.selectItemCode('product_option_' + iProductNo + '_0', sItemCode);
26505    },
26506
26507    /**
26508     * 외부에서 옵션을 선택하는걸 호출할 경우 해당 옵션의 product_option_area값과 품목코드를 전달
26509     * @param sOptionArea 옵션 element의 product_option_area값 attribute값
26510     * @param sItemCode 품목코드
26511     */
26512    selectItemCode: function(sOptionArea, sItemCode)
26513    {
26514        var oSelect = EC$('[product_option_area="' + sOptionArea + '"]');
26515        oSelect = this.setOptionBoxElement(oSelect);
26516
26517        var sOptionListType = this.getOptionListingType(oSelect);
26518        var sOptionType = this.getOptionType(oSelect);
26519
26520        //조합일체형이나 독립형인경우
26521        if (sOptionListType === 'C' || sOptionType === 'F') {
26522            this.setValue(oSelect, sItemCode, true, true);
26523        } else {
26524            var iProductNo = this.getOptionProductNum(oSelect);
26525            var oItemData = this.getProductStockData(iProductNo);
26526
26527            if (oItemData === null) {
26528                return;
26529            }
26530
26531            if (oItemData.hasOwnProperty(sItemCode) === false) {
26532                return;
26533            }
26534
26535            var aOptionValue = oItemData[sItemCode].option_value_orginal;
26536
26537            oSelect.each(function (i) {
26538                CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this, aOptionValue[i], true, true);
26539            });
26540        }
26541    },
26542
26543    /**
26544     * 해당 Element의 값을 강제로 지정
26545     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26546     * @param sValue set 하려는 value
26547     * @param bIsInitialize false인 경우에는 클릭이벤트를 발생하지 않도록 한다
26548     * @param bChange change 이벤트 발생 여부
26549     */
26550    setValue: function(oOptionChoose, sValue, bIsInitialize, bChange) {
26551        // 값 세팅시 각 페이지에서 EC$(this).val()로 값을 지정할경우
26552        // 본래 버튼형 옵션이면 타겟을 버튼형 옵션으로 이어준다
26553        oOptionChoose = this.setOptionBoxElement(oOptionChoose);
26554
26555        if (this.isOptionStyleButton(oOptionChoose) === true) {
26556            //옵션이 선택되어있는상태면 초기화후 선택
26557            if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isOptionSelected(oOptionChoose) === true) {
26558
26559                // div 셀렉트박스형 옵션은 제외하고 실행
26560                if (EC$(oOptionChoose).hasClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_DIV_SELECT_CLASS) === false) {
26561                    EC$(oOptionChoose).find('li.' + this.cons.BUTTON_OPTION_SELECTED_CLASS).trigger('click');
26562                }
26563            }
26564
26565            var oTarget = EC$(oOptionChoose).find('li[option_value="' + sValue + '"]');
26566
26567            if (EC$(oTarget).length > 0) {
26568                EC$(oTarget).trigger('click');
26569            } else {
26570                if (bIsInitialize !== false) {
26571                    // 선택값이 없다면 셀렉트박스 초기화
26572                    var iProductNum = this.getOptionProductNum(oOptionChoose);
26573                    var iSelectedOptionSortNum = this.getOptionSortNum(oOptionChoose);
26574                    var sOptionGroup = this.getOptionSelectGroup(oOptionChoose);
26575                    var bIsRequired = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(oOptionChoose);
26576
26577                    if (CAFE24.SHOP_FRONT_NEW_OPTION_BIND.isEnabledOptionInit(oOptionChoose) === true) {
26578                        CAFE24.SHOP_FRONT_NEW_OPTION_BIND.setInitializeDefault(sOptionGroup, iSelectedOptionSortNum, iProductNum, bIsRequired);
26579                    }
26580
26581                    CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM.eachCallback(oOptionChoose);
26582                    CAFE24.SHOP_FRONT_NEW_OPTION_BIND.setRadioButtonSelect(oTarget, oOptionChoose, false);
26583                }
26584
26585                this.setTriggerSelectbox(oOptionChoose, sValue);
26586            }
26587        } else {
26588            EC$(oOptionChoose).val(sValue);
26589
26590            if (typeof(bChange) !== 'undefined') {
26591                EC$(oOptionChoose).trigger('change');
26592            }
26593        }
26594    },
26595
26596    /**
26597     * 버튼 또는 이미지형 옵션일 경우 동적 selectbox와 동기화 시킴
26598     * @param oOptionChoose 선택한 옵션 Object
26599     * @param sValue set 하려는 value
26600     * @param bIsTrigger 셀렉트박스의 change 이벤트를 발생시키지 않을때(ex:모바일의 옵션선택 레이어..)
26601     */
26602    setTriggerSelectbox: function(oOptionChoose, sValue, bIsTrigger)
26603    {
26604        if (this.isOptionStyleButton(oOptionChoose) === true) {
26605            var oTargetSelect = EC$('select[product_option_area_select="' + EC$(oOptionChoose).attr('product_option_area') + '"][id="' + EC$(oOptionChoose).attr('ec-dev-id') + '"]');
26606            var bChange = true;
26607
26608            var sText = '';
26609            if (this.validation.isItemCode(sValue) === false) {
26610                sValue = '*';
26611                sText = 'empty';
26612
26613                bChange = false;
26614            } else {
26615                sValue = this.getOptionSelectedValue(oOptionChoose);
26616                sText = this.getOptionSelectedText(oOptionChoose);
26617            }
26618
26619            if (sValue !== '*') {
26620                EC$(oTargetSelect).find('option[value="' + sValue + '"]').remove('option');
26621
26622                var sOptionsHtml = this.cons.OPTION_STYLE_SELECT_HTML.replace('[value]', sValue).replace('[text]', sText);
26623
26624                EC$(oTargetSelect).append(EC$(sOptionsHtml));
26625            }
26626
26627            EC$(oTargetSelect).val(sValue);
26628
26629            if (bChange === true && bIsTrigger !== false) {
26630                EC$(oTargetSelect).trigger('change');
26631            }
26632        }
26633    },
26634
26635    /**
26636     * 해당 상품의 옵션 재고 관련 데이터를 리턴
26637     * @param iProductNum 상품번호
26638     * @returns option_stock_data 데이터
26639     */
26640    getProductStockData: function(iProductNum) {
26641        return this.data.getProductStockData(iProductNum);
26642    },
26643
26644    /**
26645     * 선택상품의 아이템코드를 반환(선택이 안되어있다면 false)
26646     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26647     * @returns 아이템 코드 OR false
26648     */
26649    getItemCode: function(oOptionChoose) {
26650        //분리조합형일경우
26651        if (this.validation.isSeparateOption(oOptionChoose) === true) {
26652            var sSelectedValue = this.getAllSelectedValue(oOptionCh
26652oose, true);
26653            var iProductNum = this.getOptionProductNum(oOptionChoose);
26654            return this.data.getItemCode(iProductNum, sSelectedValue);
26655        }
26656
26657        //그외의 경우에는 현재 선택된 옵션의 value가 아이템코드
26658        var sItemCode = this.getOptionSelectedValue(oOptionChoose);
26659
26660        return (this.validation.isItemCode(sItemCode) === true) ? sItemCode : false;
26661    },
26662
26663    /**
26664     * 해당 그룹내의 모든옵션에대해 선택된 품목코드를 반환
26665     * @param sOptionGroup 옵션 그룹 (@see : CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS)
26666     * @param bIsAbleSoldout 품절품목에 대한 아이템코드도 포함
26667     * @returns array 선택된 아이템코드 배열
26668     */
26669    getGroupItemCodes: function(sOptionGroup, bIsAbleSoldout) {
26670        var aItemCode = [];
26671        var sItemCode = '';
26672        var oTarget = EC$('[' + this.cons.GROUP_ATTR_NAME + '^="' + sOptionGroup + '"]');
26673
26674        //뉴스킨인 경우에는 옵션박스 레이어에 생성된 input에서 가져온다
26675        if (isNewProductSkin() === true) {
26676            EC$('.' + CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS.DETAIL_OPTION_BOX_PREFIX).each(function() {
26677                //옵션박스에 생성된 input태그이므로 val()로 가져온다
26678                sItemCode = EC$(this).val();
26679                if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isItemCode(sItemCode) === true) {
26680                    aItemCode.push(sItemCode);
26681                }
26682            });
26683
26684            //품절품목에 대한 아이템코드도 포함시킨다 - 현재는 관심상품담을경우에 쓰이는것으로 보임
26685            if (bIsAbleSoldout === true) {
26686                EC$('.' + CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS.DETAIL_OPTION_BOX_SOLDOUT_PREFIX).each(function() {
26687                    aItemCode.push(EC$(this).val());
26688
26689                    if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isItemCode(sItemCode) === true) {
26690                        aItemCode.push(sItemCode);
26691                    }
26692                });
26693            }
26694        } else {
26695            //구스킨인 경우에는 해당하는 옵션에 선택된 값만 가져옴
26696            EC$(oTarget).each(function() {
26697                sItemCode = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getItemCode(this);
26698
26699                //이미 저장된 아이템코드이면 제와(분리형인경우 같은 값이 여러개 들어올수있음)
26700                //조합형을 따로 처리하기보다는 그냥 두는게 더 간단하다는 핑계임
26701                if (EC$.inArray(sItemCode, aItemCode) > -1) {
26702                    return true;//continue
26703                }
26704
26705                if (sItemCode !== false) {
26706                    aItemCode.push(sItemCode);
26707                }
26708            });
26709        }
26710
26711        return aItemCode;
26712    },
26713
26714    /**
26715     * 해당 품목의 품절 여부
26716     * @param iProductNum 상품번호
26717     * @param sItemCode 품목코드
26718     * @returns boolean 품절여부
26719     */
26720    isSoldout: function(iProductNum, sItemCode) {
26721        var aStockData = this.getProductStockData(iProductNum);
26722
26723        if (typeof(aStockData[sItemCode]) === 'undefined') {
26724            return false;
26725        }
26726
26727        //재고를 사용하고 재고수량이 1개미만이면 품절
26728        if (aStockData[sItemCode].use_stock === true && parseInt(aStockData[sItemCode].stock_number) < 1) {
26729            return true;
26730        }
26731
26732        //판매안함 상태이면 품절
26733        if (aStockData[sItemCode].is_selling === 'F') {
26734            return true;
26735        }
26736
26737        return false;
26738    },
26739
26740    /**
26741     * 진열여부 확인
26742     */
26743    isDisplay: function(iProductNum, sItemCode) {
26744        var aStockData = this.getProductStockData(iProductNum);
26745
26746        if (typeof(aStockData[sItemCode]) === 'undefined') {
26747            return false;
26748        }
26749
26750        if (aStockData[sItemCode].is_display !== 'T') {
26751            return false;
26752        }
26753
26754        return true;
26755    },
26756
26757    /**
26758     * sOptionGroup에 해당하는 옵션셀렉트박스의 Element를 가져온다
26759     * @param sOptionGroup sOptionGroup 옵션 그룹 (@see : CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS)
26760     * @returns 해당 옵션셀렉트박스 Element전체
26761     */
26762    getGroupOptionObject: function(sOptionGroup) {
26763        return EC$('[' + this.cons.GROUP_ATTR_NAME + '^="' + sOptionGroup + '"]');
26764    },
26765
26766    /**
26767     * 해당 옵션그룹에서 필수옵션의 갯수를 가져온다
26768     * @param sOptionGroup sOptionGroup 옵션 그룹 (@see : CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS)
26769     * @returns 필수옵션 갯수
26770     */
26771    getRequiredOption: function(sOptionGroup) {
26772        return this.getGroupOptionObject(sOptionGroup).filter('[required="true"],[required="required"]');
26773    },
26774
26775    /**
26776     * 해당 옵션의 전체 Value값을 가져옴(옵션그룹이 아니라 단일 옵션 셀렉츠박스)
26777     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26778     * @returns {Array}
26779     */
26780    getAllOptionValues: function(oOptionChoose) {
26781        //일반 셀렉트박스일때
26782        var aOptionValue = [];
26783        if (this.isOptionStyleButton(oOptionChoose) === false) {
26784            EC$(oOptionChoose).find('option[value!="*"][value!="**"]').each(function() {
26785                aOptionValue.push(EC$(this).val());
26786            });
26787        } else {
26788            //버튼형 옵션일경우
26789            EC$(oOptionChoose).find('li[option_value!="*"][option_value!="**"]').each(function() {
26790                aOptionValue.push(EC$(this).attr('option_value'));
26791            });
26792        }
26793
26794        return aOptionValue;
26795    },
26796
26797    /**
26798     * 해당 옵션의 실제 id값을 리턴
26799     * @param oOptionChoose 값을 가져오려는 옵션박스 object
26800     * @returns {String}
26801     */
26802    getOptionChooseID: function(oOptionChoose) {
26803        var sID = '';
26804        if (this.isOptionStyleButton(oOptionChoose) === true) {
26805            sID = EC$(oOptionChoose).attr('ec-dev-id');
26806        } else {
26807            sID = EC$(oOptionChoose).attr('id');
26808        }
26809
26810        return sID;
26811    },
26812    selectOptionItem: function (sItemCode) {
26813        try {
26814            if (typeof ProductSet !== 'undefined') {
26815                return ProductSet.selectOptionItem(sItemCode);
26816            }
26817
26818            if (typeof option_stock_data === 'undefined') {
26819                return;
26820            }
26821
26822            var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
26823
26824            if (typeof aStockData[sItemCode] === 'undefined') {
26825                return;
26826            }
26827
26828            EC_SHOP_FRONT_NEW_OPTION_COMMON.selectItemCode(CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS.DETAIL_OPTION_GROUP_ID + iProductNo + '_0', sItemCode);
26829        } catch (e) {
26830            console.error("option select error", e);
26831        }
26832    }
26833};
26834
26835var EC_SHOP_FRONT_NEW_OPTION_COMMON = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_COMMON');
26836
26837EC$(function() {
26838    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isLoad = true;
26839
26840    //표시된 옵션 선택박스에 대해  디폴트 옵션데이터 정리
26841    CAFE24.SHOP_FRONT_NEW_OPTION_DATA.setDefaultData();
26842
26843    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.init();
26844});
26845/**
26846 * 옵션에대한 Attribute 및 구분자 모음
26847 */
26848CAFE24.SHOP_FRONT_NEW_OPTION_CONS = {
26849    /**
26850     * 옵션 그룹 Attribute Key(각 상품 및 영역별 구분을 위한 값)
26851     */
26852    GROUP_ATTR_NAME: 'product_option_area',
26853
26854    /**
26855     * 옵션 스타일 Attribute Key
26856     */
26857    OPTION_STYLE: 'option_style',
26858
26859    /**
26860     * 상품번호 Attribute Key
26861     */
26862    OPTION_PRODUCT_NUM: 'option_product_no',
26863
26864    /**
26865     * 각 옵션의 옵션순서 Attribute Key
26866     */
26867    OPTION_SORT_NUM: 'option_sort_no',
26868
26869    /**
26870     * 옵션 타입 Attribute Key
26871     */
26872    OPTION_TYPE: 'option_type',
26873
26874    /**
26875     * 옵션 출력 타입 Attribute Key
26876     */
26877    OPTION_LISTING_TYPE: 'item_listing_type',
26878
26879    /**
26880     * 옵션 값 구분자
26881     */
26882    OPTION_GLUE: '#$%',
26883
26884    /**
26885     * 미리보기형 옵션
26886     */
26887    OPTION_STYLE_PREVIEW: 'preview',
26888
26889    /**
26890     * 버튼형 옵션
26891     */
26892    OPTION_STYLE_BUTTON: 'button',
26893
26894    /**
26895     * 기존 셀렉트박스형 옵션
26896     */
26897    OPTION_STYLE_SELECT: 'select',
26898
26899    /**
26900     * 라디오박스형 옵션
26901     */
26902    OPTION_STYLE_RADIO: 'radio',
26903
26904    /**
26905     * 각 옵션마다 연결된 이미지 Attribute
26906     */
26907    OPTION_LINK_IMAGE: 'link_image',
26908
26909    /**
26910     * 셀렉트박스형 옵션의 Template
26911     */
26912    OPTION_STYLE_SELECT_HTML: '<option value="[value]">[text]</option>',
26913
26914    /**
26915     * 기본 품절 문구
26916     */
26917    OPTION_SOLDOUT_DEFAULT_TEXT: __("품절"),
26918
26919    /**
26920     * 버튼형 옵션의 품절표시 class
26921     */
26922    BUTTON_OPTION_SOLDOUT_CLASS: 'ec-product-soldout',
26923
26924    /**
26925     * 버튼형 옵션의 선택불가 class
26926     */
26927    BUTTON_OPTION_DISABLE_CLASS: 'ec-product-disabled',
26928
26929    /**
26930     * 버튼형 옵션의 선택된 옵션값을 구분하기위한 상수
26931     */
26932    BUTTON_OPTION_SELECTED_CLASS: 'ec-product-selected',
26933
26934    /**
26935     * div 셀렉트박스형 옵션 class
26936     */
26937    OPTION_STYLE_DIV_SELECT_CLASS: 'ec-option-div-select',
26938
26939    /**
26940     * 세트상품 옵션없음 class
26941     */
26942    OPTION_SET_PRODUCT_NONE_CLASS: 'ec-setproduct-option-none'
26943};
26944
26945var EC_SHOP_FRONT_NEW_OPTION_CONS = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_CONS');
26946
26947/**
26948 * 각 옵션그룹에 대한 Key 정의
26949 */
26950CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS = {
26951    /**
26952     * 상품디테일의 메인 옵션 그룹
26953     */
26954    DETAIL_OPTION_GROUP_ID: 'product_option_',
26955
26956    /**
26957     * 뉴스킨 상품상세의 옵션선택시 쩔어지는 옵션박스레이어 class명
26958     */
26959    DETAIL_OPTION_BOX_PREFIX: 'option_box_id',
26960
26961    /**
26962     * 뉴스킨 상품상세의 옵션선택시 쩔어지는 옵션박스레이어 class명(품절일경우의 prefix)
26963     * Prefix존누 많음
26964     */
26965    DETAIL_OPTION_BOX_SOLDOUT_PREFIX: 'soldout_option_box_id'
26966};
26967
26968var EC_SHOP_FRONT_NEW_OPTION_GROUP_CONS = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_GROUP_CONS');
26969
26970CAFE24.SHOP_FRONT_NEW_OPTION_BIND = {
26971
26972    /**
26973     * 선택한 옵션 그룹(product_option_상품번호 : 상품상세일반상품)
26974     */
26975    sOptionGroup: null,
26976
26977    /**
26978     * 옵션이 모두 선택되었을때 해당하는 item_code를 Set
26979     */
26980    sItemCode: false,
26981
26982    /**
26983     * 선택한 옵션의 상품번호
26984     */
26985    iProductNum: 0,
26986
26987    /**
26988     * 선택한 옵션의 순번
26989     */
26990    iOptionIndex: null,
26991
26992    /**
26993     * 선택한 옵션의 옵션 스타일(select : 셀렉트박스, preview : 미리보기, button : 버튼형)
26994     */
26995    sOptionStyle: null,
26996
26997    /**
26998     * 해당 상품 옵션 갯수
26999     */
27000    iOptionCount: 0,
27001
27002    /**
27003     * 품절옵션 표시여부
27004     */
27005    bIsDisplaySolout: true,
27006
27007    /**
27008     * 선택한 옵션의 객체(셀렉트박스 또는 버튼형 옵션 박스(ul태그))
27009     */
27010    oOptionObject: null,
27011
27012    /**
27013     * 선택한 옵션의 다음옵션 Element
27014     */
27015    oNextOptionTarget: null,
27016
27017    /**
27018     * 선택된 옵션 값
27019     */
27020    aOptionValue: [],
27021
27022    /**
27023     * 옵션텍스트에 추가될 항목에대한 정의
27024     */
27025    aExtraOptionText: [
27026        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_PRICE,
27027        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT,
27028        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE,
27029        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM,
27030        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_ITEMSELECTION,
27031        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET,
27032        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING,
27033        CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS
27034    ],
27035
27036    /**
27037     * CAFE24.SHOP_FRONT_NEW_OPTION_CONS 객체 Alias
27038     */
27039    cons: null,
27040
27041    /**
27042     * CAFE24.SHOP_FRONT_NEW_OPTION_COMMON 객체 Alias
27043     */
27044    common: null,
27045
27046    /**
27047     * CAFE24.SHOP_FRONT_NEW_OPTION_DATA 객체 Alias
27048     */
27049    data: null,
27050
27051    /**
27052     * CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION 객체 Alias
27053     */
27054    validation: null,
27055
27056    isEnabledOptionInit: function(oOptionChoose)
27057    {
27058        var iProductNum = EC$(oOptionChoose).attr('option_product_no');
27059        //연동형이면서 옵션추가버튼설정이면 순차로딩제외
27060        if (Olnk.isLinkageType(this.common.getOptionType(oOptionChoose)) === true && (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isUseOlnkButton() === true || CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isBindUseOlnkButton(iProductNum) === true)) {
27061            return false;
27062        }
27063
27064        if (this.common.getOptionType(oOptionChoose) === 'F') {
27065            return false;
27066        }
27067
27068        return true;
27069    },
27070
27071    /**
27072     * 각 옵션값에 대한 이벤트 처리
27073     * @param oThis 옵션 셀렉트박스 또는 버튼박스
27074     * @param oSelectedElement 선택한 옵션값
27075     * @param bIsUnset true 이명 deselected된상태로 초기화(setValue를 통해서 틀어왔을떄만 값이 있음)
27076     */
27077    initialize: function(oThis, oSelectedElement, bIsUnset)
27078    {
27079        this.sItemCode = false;
27080        this.oOptionObject = oThis;
27081
27082        // 실제 옵션 처리전에 처리해야할 내용을 모아 놓는다
27083        this.prefetch(oThis);
27084
27085        if (oSelectedElement !== null) {
27086            if (EC$(oSelectedElement).hasClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_DISABLE_CLASS) === true) {
27087                this.setRadioButtonSelect(oSelectedElement, oThis, false);
27088                return;
27089            }
27090
27091            //선택 옵션에대한 disable처리나 활성화 처리
27092            this.setSelectButton(oSelectedElement, bIsUnset);
27093
27094            //필수정보 Set
27095            this.setSelectedOptionConf();
27096
27097            //연동형이면서 옵션추가버튼설정이면 순차로딩제외..
27098            if (this.isEnabledOptionInit(this.oOptionObject) === true) {
27099                var bIsDelete = true;
27100                var bIsRequired = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(this.oOptionObject);
27101                //해당 옵션이 연동형이면서 선택형 옵션이면 하위 옵션은 값만 초기화
27102                if (Olnk.isLinkageType(this.common.getOptionType(this.oOptionObject)) === true && bIsRequired=== false) {
27103                    bIsDelete = false;
27104                }
27105
27106                //선택한 옵션이 옵션이 아닐경우 하위옵션 초기화
27107                //선택한 옵션이 옵션이 아니면 아래 로직은 타지 않고 eachCallback은 실행함
27108                this.setInitializeDefault(this.sOptionGroup, this.iOptionIndex, this.iProductNum, bIsRequired);
27109
27110                if (bIsDelete === true && EC$(oSelectedElement).hasClass(this.cons.BUTTON_OPTION_DISABLE_CLASS) === false && this.validation.isOptionSelected(this.oOptionObject) === true) {
27111                    //선택한 옵션의 다음옵션값을 Parse
27112                    //연동형일경우에는 제외 / 조합분리형만 처리되도록 함
27113                    if (Olnk.isLinkageType(this.sOptionType) === false && this.validation.isSeparateOption(this.oOptionObject) === true) {
27114                        this.data.initializeOptionValue(this.oOptionObject);
27115                    }
27116
27117                    //각 옵션을 초기화및 옵션 리스트 HTML생성
27118                    //조합분리형일때만 처리
27119                    if (this.validation.isSeparateOption(this.oOptionObject) === true) {
27120                        this.setOptionHTML();
27121                    }
27122                }
27123            }
27124
27125            //해당 값이 true나 false이면 setValue를 통해서 들어온것이기때문에 다시 실행할 필요 없음
27126            //if (typeof(bIsUnset) === 'undefined') {
27127                //셀렉트박스 동기화
27128                this.common.setTriggerSelectbox(this.oOptionObject, this.common.getOptionSelectedValue(this.oOptionObject));
27129            //}
27130
27131            //옵션이 모두 선택되었다면 아이템코드를 세팅
27132            this.setItemCode();
27133        }
27134
27135        //옵션선택이 끝나면 각 옵션마다 처리할 프로세스(각 추가기능에서)
27136        this.eachCallback(oThis);
27137
27138        //모든 옵션이 선택되었다면
27139        if (this.sItemCode !== false) {
27140
27141            var sID = this.common.getOptionChooseID(this.oOptionObject);
27142
27143            //상세 메인 상품에서만 실행되도록 예외처리
27144            if (typeof(setPrice) === 'function' && /^product_option_id+/.test(sID) === true) {
27145                setPrice(false, true, sID);
27146            }
27147
27148            //모든 옵션선택이 끝나면 처리할 프로세스(각 추가기능에서)
27149            this.completeCallback(oThis);
27150        }
27151    },
27152
27153    /**
27154     * 실제 옵션의 선택여부를 해제하기전 실행하는 액션
27155     */
27156    prefetch: function(oThis)
27157    {
27158        EC$(this.aExtraOptionText).each(function() {
27159            if (typeof(this.prefetch) === 'function') {
27160                this.prefetch(oThis);
27161            }
27162        });
27163    },
27164
27165    /**
27166     * 각 옵션 선택시마다 처리할 Callback(Extra에 있는 추가기능)
27167     */
27168    eachCallback: function(oThis)
27169    {
27170        EC$(this.aExtraOptionText).each(function() {
27171            if (typeof(this.eachCallback) === 'function') {
27172                this.eachCallback(oThis);
27173            }
27174        });
27175    },
27176
27177    /**
27178     * 옵션선택을 하고 품목이 정해졌을때 Callback(Extra에 있는 추가기능)
27179     */
27180    completeCallback: function(oThis)
27181    {
27182        EC$(this.aExtraOptionText).each(function() {
27183            if (typeof(this.completeCallback) === 'function') {
27184                this.completeCallback(oThis);
27185            }
27186        });
27187    },
27188
27189    /**
27190     * iSelectedOptionSortNum보다 하위 옵션들을 초기상태로 변경함
27191     * @param sOptionGroup 옵션선택박스 그룹
27192     * @param iSelectedOptionSortNum 하위옵션을 초기화할 대상 옵션 순번
27193     * @param iProductNum 상품번호
27194     * @param bIsSetValue COMMON.setValue에서 호출시에는 다시 setValue를 하지 않는다
27195     */
27196    setInitializeDefault: function(sOptionGroup, iSelectedOptionSortNum, iProductNum, bSelectedOptionRequired) {
27197        var iSortNum = 0;
27198        var sHtml = '';
27199        var bIsDelete = null;
27200
27201        EC$('['+this.cons.GROUP_ATTR_NAME+'="'+sOptionGroup+'"]').each(function() {
27202
27203            iSortNum = parseInt(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSortNum(this));
27204
27205            //선택한 옵션의 하위옵션들을 초기화
27206            if (iSelectedOptionSortNum < iSortNum) {
27207
27208                var bIsRequired = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(this);
27209
27210                //선택했던 옵션이 연동형이면서 선택형 옵션이면 값만 초기화
27211                //bIsDelete = (bIsDelete = null && isOlnk === true && bSelectedOptionRequired === true && bIsRequired === false) ? false : true;
27212                if (bIsDelete === null) {
27213                    //선택했던 옵션이 선택형 옵션이면 처리하지 않음
27214                    if (bSelectedOptionRequired === false) {
27215                        bIsDelete = false;
27216                    } else if (bSelectedOptionRequired === true) {//선택했던 옵션이 필수옵션이면 진행
27217                        //선택했던 옵션이 필수이면서 현재 옵션이 필수이면 초기화
27218                        if (bIsRequired === true) {
27219                            bIsDelete = true;
27220                        } else {
27221                            //선택했던 옵션이 필수이면서 현재옵션이 선택형옵션이면 다음옵션에서 체크
27222                            bIsDelete = null;
27223                        }
27224                    }
27225                }
27226
27227                if (bIsDelete === true) {
27228                    sHtml = CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getDefaultOptionHTML(iProductNum, iSortNum);
27229                    EC$(this).html('');
27230                    EC$(this).append(sHtml);
27231                }
27232
27233                //셀렉트박스이면서 필수옵션이라면 기본값을 제외하고 option삭제
27234                if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyle(this, CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_SELECT) === true) {
27235
27236                    if (bIsDelete === true && bIsRequired === true) {
27237                        EC$(this).find('option').prop('disabled', false);
27238                        EC$(this).find('option[value!="*"][value!="**"]').remove('option');
27239                    } else {
27240                        CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this, '*', false);
27241                    }
27242                }
27243
27244                if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(this) === true) {
27245                    if (bIsDelete === true && bIsRequired === true) {
27246                        EC$(this).find('li').removeClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_DISABLE_CLASS).addClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_DISABLE_CLASS);
27247                        var oDropDown = EC$(this).closest('.mDropDown');
27248                        oDropDown.addClass("ec-option-disabled").find('.eDropDown > span').html(__('옵션 선택'));
27249                        oDropDown.find('button').attr('disabled', 'disabled');
27250
27251                    } else {
27252                        // 하위 옵션중 선택(div)형
27253                        if (EC$(this).hasClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_DIV_SELECT_CLASS) === true) {
27254                            var oDropDown = EC$(this).closest('.mDropDown');
27255                            oDropDown.find('.eDropDown > span').html(__('옵션 선택'));
27256                            EC$(this).removeClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_SELECTED_CLASS);
27257                        }
27258                    }
27259
27260                    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this, '*', false);
27261                    //옵션 텍스트 초기화
27262                    CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DISPLAYITEM.eachCallback(this);
27263                }
27264
27265                //첫번째 필수 옵션은 그대로 두고 두번째 필수옵션부터 remove
27266                if (bIsDelete !== null && bIsRequired === true) {
27267                    bIsDelete = true;
27268                }
27269            }
27270        });
27271    },
27272
27273    /**
27274     * 옵션이 모두 선택되었다면 아이템코드 Set
27275     */
27276    setItemCode: function() {
27277        //연동형 상품 : 예외적인경우가 많아서 어쩔수가 없음...
27278        if (Olnk.isLinkageType(this.common.getOptionType(this.oOptionObject)) === true) {
27279            //선택한 값이 옵션이 아니라면 false
27280            if (this.validation.isItemCode(this.common.getOptionSelectedValue(this.oOptionObject)) === false) {
27281                return false;
27282            }
27283
27284            //연동형 옵션
27285            var aSelectedValues = this.common.getAllSelectedValue(this.oOptionObject);
27286
27287            //필수옵션 갯수
27288            var iRequiredOption = this.common.getRequiredOption(this.sOptionGroup).length;
27289
27290            //선택한 옵션갯수보다 필수옵션이 많다면 false
27291            if (iRequiredOption > EC$(aSelectedValues).length) {
27292                return false;
27293            }
27294            //실제 필수옵션이 체크되어있는지
27295            var aOptionValues = [];
27296            var bIsExists = false;
27297            var iRequireSelectedOption = 0;
27298
27299            //필수항목만 검사
27300            this.common.getRequiredOption(this.sOptionGroup).each(function() {
27301                bIsExists = false;
27302                aOptionValues = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getAllOptionValues(this);
27303
27304                //필수 항목 옵션의 값을 실제 선택한옵션가눙데 존재하는지 일일히 확인해야한다
27305                EC$(aSelectedValues).each(function(i, iNo) {
27306                    //선택된 옵션중에 존재한다면 필수값이 선택된것으로 확인
27307                    if (EC$.inArray(iNo, aOptionValues) > -1) {
27308                        bIsExists = true;
27309                        return;
27310                    }
27311                });
27312
27313                if (bIsExists === true) {
27314                    iRequireSelectedOption++;
27315                }
27316            });
27317
27318            //전체 필수값 갯수가 선택된 필수옵션보다 많다면 false
27319            if (iRequiredOption > iRequireSelectedOption) {
27320                return false;
27321            }
27322
27323            this.sItemCode = aSelectedValues;
27324        } else if (this.validation.isSeparateOption(this.oOptionObject) === true) {
27325            //조합분리형은 옵션값으로 파싱해서 가져와야함
27326            if (parseInt(this.iOptionCount) > parseInt(this.aOptionValue.length)) {
27327                return false;
27328            }
27329
27330            this.sItemCode = this.data.getItemCode(this.iProductNum, this.aOptionValue.join(this.cons.OPTION_GLUE));
27331        } else {
27332            //조합분리형 이외에는 선택한 옵션의 value가 아이템코드
27333            this.sItemCode = this.common.getOptionSelectedValue(this.oOptionObject);
27334        }
27335
27336    },
27337
27338    /**
27339     * 각 옵션을 초기화및 옵션 리스트 HTML생성
27340     */
27341    setOptionHTML: function() {
27342        //하위옵션이 없다면(마지막 옵션을 선택한경우) 하위옵션이 없음으로 따로 만들지 않아도 된다
27343        if (parseInt(this.iOptionCount) === parseInt(this.aOptionValue.length)) {
27344            return;
27345        }
27346
27347        if (this.oNextOptionTarget === null) {
27348            return;
27349        }
27350
27351        var sSelectedOption = this.aOptionValue.join(this.cons.OPTION_GLUE);
27352
27353        var aOptions = this.data.getOptionValueArray(this.iProductNum, sSelectedOption);
27354
27355        //셀렉트박스일때 다음옵션 박스 초기화
27356        if (this.common.isOptionStyleButton(this.oNextOptionTarget) === false) {
27357            this.setOptionHtmlForSelect(aOptions, sSelectedOption);
27358        } else {
27359            this.setOptionHtmlForButton(aOptions, sSelectedOption);
27360        }
27361    },
27362
27363    /**
27364     * 버튼형 옵션일 경우 해당 버튼 HTML초기화 및 해당 옵션값 Set
27365     * @param aOptions 옵션값 리스트
27366     * @param sSelectedOption 현재까지 선택된 옵션조합
27367     */
27368    setOptionHtmlForButton: function(aOptions, sSelectedOption) {
27369        //선택한값이 *sk ** 이면 다음옵션을 disable처리
27370        if (this.validation.isItemCode(this.common.getOptionSelectedValue(this.oOptionObject)) === false) {
27371            this.oNextOptionTarget.find('li').removeClass(this.cons.BUTTON_OPTION_DISABLE_CLASS).addClass(this.cons.BUTTON_OPTION_DISABLE_CLASS);
27372        } else {
27373            this.oNextOptionTarget.find('li').removeClass(this.cons.BUTTON_OPTION_DISABLE_CLASS);
27374        }
27375
27376        //연동형일경우에는 disable /  select만 제거
27377        if (Olnk.isLinkageType(this.sOptionType) === true) {
27378            //하위옵션들만 selected클래스 삭제
27379            if (parseInt(EC$(this.oOptionObject).attr('option_sort_no')) < parseInt(EC$(this.oNextOptionTarget).attr('option_sort_no'))) {
27380                EC$(this.oNextOptionTarget).find('li').removeClass(this.cons.BUTTON_OPTION_SELECTED_CLASS);
27381                CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this.oNextOptionTarget, '*', false);
27382
27383                EC$(this.oNextOptionTarget).closest('.mDropDown.ec-option-disabled').removeClass('ec-option-disabled').find('button').removeAttr('disabled');
27384            }
27385            return;
27386        }
27387
27388        this.oNextOptionTarget.find('li').remove('li');
27389
27390        var iNextOptionSortNum = this.common.getOptionSortNum(this.oNextOptionTarget);
27391
27392        var bIsLastOption = false;
27393        //생성될 옵션이 마지막 옵션이면 옵션 Text에 추가 항목(옵션가 품절표시등)을 처리
27394        if (parseInt(iNextOptionSortNum) === this.iOptionCount) {
27395            bIsLastOption = true;
27396        }
27397
27398        var oObject = this;
27399        var sOptionsHtml = '';
27400
27401        //옵션 셀렉트박스 Text에 추가될 문구 처리
27402        var sAddText = '';
27403        var sItemCode = false;
27404        //품절옵션인데 품절옵션표시안함설정이면 삭제
27405        var bIsSoldout = false;
27406        var bIsDisplay = true;
27407
27408        EC$(aOptions).each(function(i, oOption) {
27409            sAddText = '';
27410            bIsSoldout = false;
27411            bIsDisplay = true;
27412            //페이지 로딩시 저장된 해당 옵션의 HTML을 가져온다
27413            sOptionsHtml = oObject.data.getButonOptionHtml(oObject.iProductNum, iNextOptionSortNum, oOption.value);
27414
27415            sOptionsHtml = EC$(sOptionsHtml).clone().removeClass(oObject.cons.BUTTON_OPTION_DISABLE_CLASS);
27416            //마지막 옵션일 경우에는
27417            if (bIsLastOption === true) {
27418                sItemCode = oObject.data.getItemCode(oObject.iProductNum, sSelectedOption + oObject.cons.OPTION_GLUE + oOption.value);
27419
27420                //진열안함이면 패스
27421                if (oObject.common.isDisplay(oObject.iProductNum, sItemCode) === false) {
27422                    bIsDisplay = false;
27423                }
27424
27425                sAddText = oObject.setAddText(oObject.iProductNum, sItemCode);
27426
27427                //품절상품인경우 품절class추가
27428                if (oObject.common.isSoldout(oObject.iProductNum, sItemCode) === true) {
27429                    EC$(sOptionsHtml).removeClass(oObject.cons.BUTTON_OPTION_SOLDOUT_CLASS).addClass(oObject.cons.BUTTON_OPTION_SOLDOUT_CLASS);
27430                    bIsSoldout = true;
27431                }
27432            } else {
27433                var sOptionText = sSelectedOption + oObject.cons.OPTION_GLUE + oOption.value;
27434                sAddText = oObject.common.getSoldoutText(oObject.oNextOptionTarget, sOptionText);
27435
27436                if (sAddText !== '') {
27437                    EC$(sOptionsHtml).addClass(oObject.cons.BUTTON_OPTION_SOLDOUT_CLASS);
27438                    bIsSoldout = true;
27439                }
27440
27441                if (oObject.data.getDisplayFlag(oObject.iProductNum, sOptionText) === false) {
27442                    bIsDisplay = false;
27443                }
27444            }
27445
27446            if ((oObject.bIsDisplaySolout === false && bIsSoldout === true) || bIsDisplay === false) {
27447                EC$(this).remove();
27448                return;
27449            }
27450
27451            if (CAFE24.checkChannelUI() === true) {
27452                oObject.oNextOptionTarget.append(EC$(sOptionsHtml).find('span').html(function(_, oldText) {
27453                    return oldText + sAddText;
27454                }).end().attr('title', oOption.value + sAddText));
27455            } else {
27456                oObject.oNextOptionTarget.append(EC$(sOptionsHtml).attr('title', oOption.value + sAddText));
27457            }
27458        });
27459
27460        oObject.oNextOptionTarget.closest('.mDropDown.ec-option-disabled').removeClass('ec-option-disabled').find('button').removeAttr('disabled')
27461
27462        CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(this.oNextOptionTarget, '*', false);
27463    },
27464
27465    /**
27466     * 셀렉트박스형 옵션일 경우 selectbox초기화 및 해당 옵션값 Set
27467     * @param aOptions 옵션값 리스트
27468     * @param sSelectedOption 현재까지 선택된 옵션조합 배열
27469     */
27470    setOptionHtmlForSelect: function(aOptions, sSelectedOption) {
27471        // 구분선 제외
27472        this.oNextOptionTarget.find('option[value!="**"]').prop('disabled', false);
27473
27474        //연동형일경우에는 초기화 시키고  disable제거
27475        //if (Olnk.isLinkageType(this.sOptionType) === true && CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(this.oNextOptionTarget)) {
27476        if (Olnk.isLinkageType(this.sOptionType) === true) {
27477            var sHtml = this.data.getDefaultOptionHTML(this.common.getOptionProductNum(this.oNextOptionTarget), this.common.getOptionSortNum(this.oNextOptionTarget));
27478            EC$(this.oNextOptionTarget).find('option').remove();
27479            EC$(this.oNextOptionTarget).append(sHtml);
27480            EC$(this.oNextOptionTarget).find('option[value!="**"]').prop('disabled', false);
27481            EC$(this.oNextOptionTarget).val('*');
27482            return;
27483        }
27484
27485        //옵션이 아닌 Default선택값을 제외하고 모두 삭제
27486        this.oNextOptionTarget.find('option[value!="*"][value!="**"]').remove();
27487
27488        //선택한 옵션의 다음순서옵션항목
27489        var iNextOptionSortNum = this.common.getOptionSortNum(this.oNextOptionTarget);
27490
27491        var bIsLastOption = false;
27492        //생성될 옵션이 마지막 옵션이면 옵션 Text에 추가 항목(옵션가 품절표시등)을 처리
27493        if (parseInt(iNextOptionSortNum) === this.iOptionCount) {
27494            bIsLastOption = true;
27495        }
27496
27497        var oObject = this;
27498        var sOptionsHtml = '';
27499
27500        var sItemCode = false;
27501
27502        //옵션 셀렉트박스 Text에 추가될 문구 처리
27503        var sAddText = '';
27504        //품절옵션인데 품절옵션표시안함설정이면 삭제
27505        var bIsSoldout = false;
27506        EC$(aOptions).each(function(i, oOption) {
27507            sAddText = '';
27508            bIsSoldout = false;
27509            bIsDisplay = true;
27510
27511            sOptionsHtml = oObject.data.getButonOptionHtml(oObject.iProductNum, iNextOptionSortNum, oOption.value);
27512            sOptionsHtml = EC$(sOptionsHtml).clone();
27513
27514            //마지막 옵션일 경우에는 설정에따라 옵션title에 추가금액등의 text를 붙인다
27515            if (bIsLastOption === true) {
27516                sItemCode = oObject.data.getItemCode(oObject.iProductNum, sSelectedOption + oObject.cons.OPTION_GLUE + oOption.value);
27517
27518                //진열안함이면 패스
27519                if (oObject.common.isDisplay(oObject.iProductNum, sItemCode) === false) {
27520                    bIsDisplay = false;
27521                }
27522
27523                sAddText = oObject.setAddText(oObject.iProductNum, sItemCode);
27524
27525                bIsSoldout = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isSoldout(oObject.iProductNum, sItemCode);
27526            } else {
27527                //품절문구(각 옵션마다도 보여줘야함...)
27528                var sOptionText = sSelectedOption + oObject.cons.OPTION_GLUE + oOption.value;
27529                sAddText = oObject.common.getSoldoutText(oObject.oNextOptionTarget, sOptionText);
27530                bIsSoldout = (sAddText === '') ? false : true;
27531
27532                if (oObject.data.getDisplayFlag(oObject.iProductNum, sOptionText) === false) {
27533                    bIsDisplay = false;
27534                }
27535            }
27536
27537            if ((oObject.bIsDisplaySolout === false && bIsSoldout === true) || bIsDisplay === false) {
27538                EC$(this).remove();
27539                return;
27540            }
27541
27542            EC$(sOptionsHtml).val(oOption.value);
27543            EC$(sOptionsHtml).prop('disabled', false);
27544            EC$(sOptionsHtml).text(oOption.value + sAddText);
27545
27546            oObject.oNextOptionTarget.append(EC$(sOptionsHtml));
27547        });
27548    },
27549
27550    /**
27551     * 마지막 옵션에 추가될 추가항목들(추가금액, 품절 등)
27552     * @param iProductNum 상품번호
27553     * @param sItemCode 아이템 코드
27554     * @param oOptionElement 옵션셀렉트박스를 임의로 지정할경우
27555     */
27556    setAddText: function(iProductNum, sItemCode, oOptionElement) {
27557        var aText = [];
27558
27559        if (typeof(oOptionElement) !== 'object') {
27560            oOptionElement = this.oOptionObject;
27561        }
27562
27563        EC$(this.aExtraOptionText).each(function() {
27564            if (typeof(this.get) === 'function') {
27565                aText.push(this.get(iProductNum, sItemCode, oOptionElement));
27566            }
27567        });
27568
27569        return aText.join('');
27570    },
27571
27572    /**
27573     * 옵션 선택박스(셀렉트박스나 버튼)에 click 또는 change에 대한 이벤트 할당
27574     */
27575    initChooseBox: function() {
27576        this.cons = CAFE24.SHOP_FRONT_NEW_OPTION_CONS;
27577        this.common = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON;
27578        this.data = CAFE24.SHOP_FRONT_NEW_OPTION_DATA;
27579        this.validation = CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION;
27580
27581        var oThis = this;
27582
27583        //live로 할경우에 기존 이벤트가 없어짐.
27584        EC$('select[option_select_element="ec-option-select-finder"]').off('change focus').change(function() {
27585            if (oThis.common.isOptionStyleButton(this) === true) {
27586                return false;
27587            }
27588
27589            //페이지 로드가 되었는지 확인.
27590            if (typeof(oThis.common.isLoad) === false) {
27591                EC$(this).val('*');
27592                return false;
27593            }
27594
27595            oThis.initialize(this, this);
27596        }).focus(function () {
27597            // select box change 이벤트 발생을 위해, selectedIndex 초기화
27598            // @see ECHOSTING-438245 다중선택형 옵션인 경우에만 동작하도록 조건 추가
27599            if (oSingleSelection.isItemSelectionTypeM() === true && this.selectedIndex > 0) {
27600                this.selectedIndex = 0;
27601            }
27602        });
27603
27604        try {
27605            const sOptionSelector = 'ul[option_select_element="ec-option-select-finder"] > li';
27606            EC$(document).off('click', sOptionSelector).on('click', sOptionSelector, function (e) {
27607                // [ECHOSTING-573085] 버튼형 옵션 내 a 태그 클릭 시 페이지 이동 방지
27608                if (EC$(e.target).closest('a').length > 0) {
27609                    e.preventDefault();
27610                }
27611                var oOptionChoose = EC$(this).parent('ul');
27612
27613                /*
27614                    ECHOSTING-194895 처리를 위해 삭제 (추가 이미지 클릭 시 해당 품목 선택 기능)
27615                    if (e.target.tagName === 'LI') {
27616                        return false;
27617                    }
27618                */
27619
27620                if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(oOptionChoose) === false) {
27621                    return false;
27622                }
27623
27624                //페이지 로드가 되었는지 확인.
27625                if (typeof CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isLoad === false) {
27626                    return false;
27627                }
27628
27629                //라디오버튼일경우 label태그에 상속되기때문에 click이벤트가 label input에 대해 두번 발생함
27630                //라디오버튼 속성이면서 발생위치가 label이면 이벤트 발생하지않고 그냥 return
27631                //return false이면 label클릭시 checked가 안되니깐 그냥 return
27632                //input 태그 자체에 이벤트를 주면 상관없지만 li태그에 이벤트를 할당하기때문에 생기는 현상같음
27633                if (oThis.common.isOptionStyle(oOptionChoose, oThis.cons.OPTION_STYLE_RADIO) === true && e.target.tagName.toUpperCase() === 'LABEL') {
27634                    return;
27635                }
27636
27637                oThis.initialize(EC$(this).parent('ul'), this);
27638            });
27639        } catch (e) {}
27640
27641        try {
27642            EC$('.mDropDown > button').off('click').on('click', function() {
27643                // // 선택옵션 div 셀렉트박스
27644                var oUlElement = EC$(this).siblings('.dropdown').find('ul.' + CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_DIV_SELECT_CLASS + ':not([required])');
27645                if (oUlElement.length > 0) {
27646                    var mDropDownElement = oUlElement.closest('.mDropDown');
27647                    mDropDownElement.find('.eDropDown > span').text(__('옵션 선택'));
27648                    oUlElement.find('li.selected').removeClass('selected ' + CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_SELECTED_CLASS);
27649                    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oUlElement, '*', false);
27650                    oThis.initialize(oUlElement, null);
27651                }
27652            });
27653        } catch (e) {}
27654    },
27655
27656    /**
27657     * 멀팁옵션에서 옵션추가시 이벤트 재정의(버튼형은 live로 되어있으니 상관없고 select형만)
27658     * @param oOptionElement
27659     */
27660    initChooseBoxMulti: function()
27661    {
27662        var oThis = this;
27663
27664        //live로 할경우에 기존 이벤트가 없어짐.
27665        EC$('.xans-product-multioption select[option_select_element="ec-option-select-finder"]').off('change').change(function() {
27666            if (oThis.common.isOptionStyleButton(this) === true) {
27667                return false;
27668            }
27669
27670            //페이지 로드가 되었는지 확인.
27671            if (typeof(oThis.common.isLoad) === false) {
27672                EC$(this).val('*');
27673                return false;
27674            }
27675
27676            oThis.initialize(this, this);
27677        });
27678    },
27679
27680    /**
27681     * 옵션 선택시 필요한 attribute값등을 SET
27682     */
27683    setSelectedOptionConf: function() {
27684        //선택한 옵션 그룹
27685        this.sOptionGroup = this.common.getOptionSelectGroup(this.oOptionObject);
27686
27687        //선택한 옵션값 순번
27688        this.iOptionIndex = parseInt(this.common.getOptionSortNum(this.oOptionObject));
27689
27690        //선택한 옵션 스타일
27691        this.sOptionStyle = EC$(this.oOptionObject).attr(this.cons.OPTION_STYLE);
27692
27693        //현재까지 선택한 옵션의 value값을 가져온다
27694        this.aOptionValue = this.common.getAllSelectedValue(this.oOptionObject);
27695
27696        //상풉번호
27697        this.iProductNum = this.common.getOptionProductNum(this.oOptionObject);
27698
27699        //옵션타입
27700        this.sOptionType = this.common.getOptionType(this.oOptionObject);
27701
27702        //품절 옵션 표시여부
27703        this.bIsDisplaySolout = this.validation.isSoldoutOptionDisplay();
27704
27705        //선택한 옵션의 다음 옵션 Element
27706        //선택옵션을 제거한 다음옵션
27707        //1 : 필수, 2 : 선택, 3 : 필수일때 1번옵션 선택후 다음옵션을 3번(연동형)
27708        //[option_sort_no"'+this.iOptionIndex+'"]
27709        oThis = this;
27710        this.oNextOptionTarget = null;
27711        EC$('[product_option_area="'+this.sOptionGroup+'"][option_product_no="'+this.iProductNum+'"]').each(function() {
27712            //현재선택한 옵션의 하위옵션이 아니라 상위옵션이면 패스
27713            if (oThis.iOptionIndex >= parseInt(oThis.common.getOptionSortNum(this))) {
27714                return true;//continue
27715            }
27716            //선택옵션이면 패스
27717            if (oThis.validation.isRequireOption(this) === false) {
27718                return true;
27719            }
27720
27721            oThis.oNextOptionTarget = EC$(this);
27722            return false;//break
27723        });
27724
27725        //옵션 갯수
27726        this.iOptionCount = EC$('[product_option_area="'+this.sOptionGroup+'"]').length;
27727    },
27728
27729    /**
27730     * 버튼식 옵션일 경우 선택한 옵션을 선택처리
27731     */
27732    setSelectButton: function(oSelectedOption, bIsUnset) {
27733
27734        if (this.common.isOptionStyleButton(this.oOptionObject) === true) {
27735            //모두 선택이 안된상태로 이벤트 실행할수있도록 selected css를 지우고 리턴
27736            if (bIsUnset === true) {
27737                EC$(oSelectedOption).removeClass(this.cons.BUTTON_OPTION_SELECTED_CLASS);
27738                return;
27739            }
27740
27741            //이미 선택한 옵션값을 다시 클릭시에는 선택해제
27742            if (EC$(oSelectedOption).hasClass(this.cons.BUTTON_OPTION_SELECTED_CLASS) === true) {
27743                if (this.common.isOptionStyleDivSelect(this.oOptionObject) === false) {
27744                    EC$(oSelectedOption).removeClass(this.cons.BUTTON_OPTION_SELECTED_CLASS);
27745                    this.common.setValue(this.oOptionObject, '*', false);
27746                    this.setRadioButtonSelect(oSelectedOption, this.oOptionObject, false);
27747                }
27748            } else {
27749                //버튼형식의  옵션일 경우 선택한 옵션을 선택처리(class 명을 추가)
27750                //선택불가일때는 선택된상태로 보이지 않도록 하고 클리만 가능하도록 한다
27751                //disable상태이면 선택CSS는 적용되지 않게 처리
27752                var oTargetOptionElement = EC$(oSelectedOption).parent('ul');
27753                var sDevID = EC$(oTargetOptionElement).attr('ec-dev-id');
27754                var self = this;
27755
27756                //조합일체형에서 구분선이 있을경우 ul태그가 따로있지만 동일옵션이므로
27757                //동일 ul을 구해서 모두 unselect시킨다
27758                EC$(oTargetOptionElement).parent().find('ul[ec-dev-id="'+sDevID+'"]').each(function() {
27759                    EC$(this).find('li').removeClass(self.cons.BUTTON_OPTION_SELECTED_CLASS);
27760                });
27761
27762                EC$(oSelectedOption).addClass(this.cons.BUTTON_OPTION_SELECTED_CLASS);
27763                this.setRadioButtonSelect(oSelectedOption, this.oOptionObject, true);
27764            }
27765        } else {
27766            //셀렉트박스형 옵션일 경우 **를 선택했다면 옵션초기화
27767            if (this.validation.isItemCode(EC$(this.oOptionObject).val()) === false) {
27768                EC$(this.oOptionObject).val('*');
27769            }
27770        }
27771    },
27772
27773    /**
27774     * Disable인 옵션일 경우 체크박스를 다시 해제함
27775     * @param oSelectedOption
27776     * @param oOptionObject
27777     * @param bIsCheck
27778     */
27779    setRadioButtonSelect: function(oSelectedOption, oOptionObject, bIsCheck)
27780    {
27781        if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyle(oOptionObject, CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_RADIO) === false) {
27782            return;
27783        }
27784
27785        EC$(oOptionObject).find('input:radio').prop('checked', false);
27786
27787        //재선택시 체크해제하려면 e107c06faf31 참고
27788        if (bIsCheck === true) {
27789            EC$(oSelectedOption).find('input:radio').prop('checked', true);
27790        }
27791    }
27792};
27793
27794var EC_SHOP_FRONT_NEW_OPTION_BIND = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_BIND');
27795CAFE24.SHOP_FRONT_NEW_OPTION_DATA = {
27796
27797    /**
27798     * CAFE24.SHOP_FRONT_NEW_OPTION_CONS 객체 Alias
27799     */
27800    cons: CAFE24.SHOP_FRONT_NEW_OPTION_CONS,
27801
27802    /**
27803     * CAFE24.SHOP_FRONT_NEW_OPTION_COMMON 객체 Alias
27804     */
27805    common: CAFE24.SHOP_FRONT_NEW_OPTION_COMMON,
27806
27807    /**
27808     * 옵션값관 아이템코드 매칭 데이터(option_value_mapper)
27809     */
27810    aOptioValueMapper: [],
27811
27812    /**
27813     * 각 선택된 옵션값에대한 다음옵션값 리스트를 저장
27814     * aOptionValueData[상품번호][빨강#$%대형] = array(key : 1, value : 옵션값, text : 옵션 Text)
27815     */
27816    aOptionValueData: {},
27817
27818    /**
27819     * 각 상품의 품목데이터(재고 및 추가금액 정보)
27820     */
27821    aItemStockData: {},
27822
27823    /**
27824     * 옵션의 디폴트 HTML을 저장해둠
27825     */
27826    aOptionDefaultData: {},
27827
27828    /**
27829     * 디폴트 옵션을 저장할떄 중복을 제거하기위해서 추가
27830     */
27831    aCacheDefaultProduct: [],
27832
27833    /**
27834     * 버튼형 옵션 Element저장시 중복제거
27835     */
27836    aCacheButtonOption: [],
27837
27838    /**
27839     * 버튼형 옵션의 경우 각 옵션값별 컬러칩/버튼이미지/버튼이름등을 저장해둔다
27840     */
27841    aButtonOptionDefaultData: [],
27842
27843    /**
27844     * 추가금액 노출 설정
27845     */
27846    aOptionPriceDisplayConf: [],
27847
27848    /**
27849     * 연동형 옵션의 옵션내용을 저장
27850     */
27851    aOlnkOptionData: [],
27852
27853    /**
27854     * 각 옵션(품목이 아닌)마다 모두 품절이면 품절표시를 위해서 추가...
27855     */
27856    aOptionSoldoutFlag: [],
27857
27858    /**
27859     * 각 옵션(품목이 아닌)마다 모두 진열안함이면 false로 나오지 않게 하기 위해서 추가
27860     */
27861    aOptionDisplayFlag: [],
27862
27863    /**
27864     * 페이지 로딩시 각 옵션선택박스의 옵션정보를 Parse
27865     */
27866    initData: function() {
27867        var oThis = this;
27868        EC$('select[option_select_element="ec-option-select-finder"], ul[option_select_element="ec-option-select-finder"]').each(function() {
27869            // 중복 로드 시 DOM 요소별 초기화 중복 방지
27870            if (EC$(this).data('option-data-initialized') === true) {
27871                return true;
27872            }
27873            EC$(this).data('option-data-initialized', true);
27874
27875            //해당 옵션의 상품번호
27876            var iProductNum = oThis.common.getOptionProductNum(this);
27877            //해당 옵션의 옵션순서번호
27878            var iOptionSortNum = oThis.common.getOptionSortNum(this);
27879
27880            var sCacheKey = iProductNum + oThis.cons.OPTION_GLUE + iOptionSortNum;
27881
27882            CAFE24.SHOP_FRONT_NEW_OPTION_DATA.initializeOption(this, sCacheKey);
27883
27884            //버튼형 옵션일 경우 각 Element를 캐싱
27885            if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isOptionStyleButton(this) === true) {
27886                CAFE24.SHOP_FRONT_NEW_OPTION_DATA.initializeOptionForButtonOption(this, sCacheKey);
27887            } else {
27888                CAFE24.SHOP_FRONT_NEW_OPTION_DATA.initializeOptionForSelectOption(this, sCacheKey);
27889                //일반 셀렉트의 경우 기본값 (*, **)을 제외하고 삭제
27890                //첫번째 필수값은 option들이 disable이 아니므로 disable된 옵션들만 삭제
27891                var bIsProcLoading = true;
27892
27893                //필수옵션만 삭제
27894                if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(this) === false) {
27895                    bIsProcLoading = false;
27896                }
27897
27898                //disable만 풀어준다
27899                //연동형이지만 옵션추가버튼 사용시에는 지우지 않음...
27900                //기본으로 선택된값이 있다면 지우지 않음(구스킨 관심상품, 뉴스킨 장바구니등에서는 일단 선택한 옵션을 보여주고 선택후부터 순차로딩)
27901                var sValue = EC$(this).find('option[selected="selected"]').val();
27902                if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isItemCode(sValue) === true || (Olnk.isLinkageType(oThis.common.getOptionType(this)) === true && (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isUseOlnkButton() === true || CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isBindUseOlnkButton(iProductNum) === true))) {
27903                    bIsProcLoading = false;
27904                    EC$(this).find('option[value!="**"]').prop('disabled', false);
27905                }
27906
27907                if (bIsProcLoading === true) {
27908                    EC$(this).find('option[value!="*"][value!="**"]:disabled').remove('option');
27909                }
27910            }
27911        });
27912    },
27913
27914    /**
27915     * 각 상품의 옵션 디폴트 옵션 HTML을 저장해둔다
27916     * @param oOptionChoose 값을 가져오려는 옵션박스 object
27917     */
27918    initializeOption: function(oOptionChoose, sCacheKey) {
27919        //이미 데이터가 있다면 패스
27920        if (EC$.inArray(sCacheKey, this.aCacheDefaultProduct) > -1) {
27921            return;
27922        }
27923
27924        this.aCacheDefaultProduct.push(sCacheKey);
27925        this.aOptionDefaultData[sCacheKey] = EC$(oOptionChoose).html();
27926    },
27927
27928    initializeOptionForSelectOption: function(oOptionChoose, sCacheKey) {
27929        var iProductNum = EC$(oOptionChoose).attr('option_product_no');
27930        var oThis = this;
27931        //같은 상품이 여러개있을수있으므로 이미 캐싱이 안된 상품만
27932        if (EC$.inArray(sCacheKey, this.aCacheButtonOption) < 0) {
27933            var bDisabled = false;
27934            if (Olnk.isLinkageType(this.common.getOptionType(oOptionChoose)) === true && (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isUseOlnkButton() === true || CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isBindUseOlnkButton(iProductNum) === true)) {
27935                bDisabled = true;
27936            }
27937
27938            this.aCacheButtonOption.push(sCacheKey);
27939            this.aButtonOptionDefaultData[sCacheKey] = [];
27940
27941            EC$(oOptionChoose).find('option').each(function() {
27942                if (bDisabled === true && this.value !== '**') {
27943                    EC$(this).prop('disabled', false);
27944                }
27945                oThis.aButtonOptionDefaultData[sCacheKey][EC$(this).val()] = EC$('<div>').append(EC$(this).clone()).html();
27946            });
27947        }
27948    },
27949
27950    /**
27951     * 셀렉트박스 형식이 아닌 버튼이나 이미지형 옵션일 경우 HTML자체를 옵션값 별로 저장해둔다.
27952     * writejs쓰기싫음여
27953     */
27954    initializeOptionForButtonOption: function(oOptionChoose, sCacheKey) {
27955        var oThis = this;
27956        var iProductNum = EC$(oOptionChoose).attr('option_product_no');
27957
27958        //같은 상품이 여러개있을수있으므로 이미 캐싱이 안된 상품만
27959        if (EC$.inArray(sCacheKey, this.aCacheButtonOption) < 0) {
27960            var bDisabled = false;
27961            if (Olnk.isLinkageType(this.common.getOptionType(oOptionChoose)) === true && (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isUseOlnkButton() === true || CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isBindUseOlnkButton(iProductNum) === true)) {
27962                bDisabled = true;
27963            }
27964
27965            this.aCacheButtonOption.push(sCacheKey);
27966            this.aButtonOptionDefaultData[sCacheKey] = [];
27967
27968            EC$(oOptionChoose).find('li').each(function() {
27969                if (bDisabled === true) {
27970                    EC$(this).removeClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.BUTTON_OPTION_DISABLE_CLASS);
27971                }
27972                oThis.aButtonOptionDefaultData[sCacheKey][EC$(this).attr('option_value')] = EC$('<div>').append(EC$(this).clone()).html();
27973            });
27974        }
27975
27976        //조합일체형인 경우 기존생성된 셀렉트박스는 삭제
27977        if (EC$(oOptionChoose).attr('item_listing_type') === 'C') {
27978            EC$('select[product_option_area_select="addproduct_option_' + iProductNum + '"]').remove();
27979        }
27980
27981        var oTriggerSelect = this.getSelectClone(oOptionChoose);
27982
27983        oTriggerSelect.append(EC$('<option>').val('*').text('empty'));
27984
27985        var sTitle = '';
27986        var sValue = '';
27987        for (x in this.aButtonOptionDefaultData[sCacheKey]) {
27988            //IE8..
27989            if (x !== 'indexOf') {
27990                sTitle = EC$(oThis.aButtonOptionDefaultData[sCacheKey][x]).attr('title');
27991                sValue = EC$(oThis.aButtonOptionDefaultData[sCacheKey][x]).attr('option_value');
27992
27993                oTriggerSelect.append(EC$('<option>').val(sValue).text(sTitle));
27994            }
27995        }
27996
27997        oTriggerSelect.val('*');
27998        EC$(oOptionChoose).parent().append(oTriggerSelect);
27999    },
28000    /**
28001     * 옵션 선택 UI의 미러링 객체 생성
28002     * @param oOptionChoose
28003     * @returns {jQuery}
28004     */
28005    getSelectClone: function(oOptionChoose)
28006    {
28007        var aAttribute = {
28008            'product_option_area_select': EC$(oOptionChoose).attr('product_option_area'),
28009            'id': EC$(oOptionChoose).attr('ec-dev-id'),
28010            'name': EC$(oOptionChoose).attr('ec-dev-name'),
28011            'option_title': EC$(oOptionChoose).attr('option_title'),
28012            'option_type': EC$(oOptionChoose).attr('option_type'),
28013            'item_listing_type': EC$(oOptionChoose).attr('item_listing_type'),
28014            'composition-code': EC$(oOptionChoose).attr('composition-code'),
28015            'option_code': EC$(oOptionChoose).attr('option_code')
28016        };
28017        // 셀렉트 박스의 셀렉터가 ^=라서 클래스의 순서가 중요
28018        var aClass = [];
28019        if (typeof(EC$(oOptionChoose).attr('ec-dev-class')) !== 'undefined') {
28020            aClass.push(EC$(oOptionChoose).attr('ec-dev-class'));
28021        }
28022        aClass.push('displaynone');
28023
28024        if (EC$(oOptionChoose).hasClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_DIV_SELECT_CLASS) === true) {
28025            aClass.push(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_STYLE_DIV_SELECT_CLASS);
28026        }
28027
28028        if (EC$(oOptionChoose).hasClass(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_SET_PRODUCT_NONE_CLASS) === true) {
28029            aClass.push(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_SET_PRODUCT_NONE_CLASS);
28030        }
28031
28032        var oReturn = EC$('<select required="true">').attr(aAttribute).addClass(aClass.join(' '));
28033        if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isRequireOption(oOptionChoose) === false) {
28034            // true/false를 string으로 지정해야해서 먼저 string으로 지정해주고 필요없으면 제거
28035            oReturn.removeAttr('required');
28036        }
28037        return oReturn;
28038    },
28039
28040    /**
28041     * 버튼형 옵션의 상품 옵션값에 대한 옵션 HTML을 반환
28042     * @param iProductNum 상품번호
28043     * @param iOptionSortNum 옵션순서
28044     * @param sOptionValue 옵션값
28045     * @returns boolean 해당 옵션값에 대한 버튼 HTML
28046     */
28047    getButonOptionHtml: function(iProductNum, iOptionSortNum, sOptionValue) {
28048        var sCacheKey = iProductNum + this.cons.OPTION_GLUE + iOptionSortNum;
28049
28050        //없을경우에는 다시 초기화
28051        if (typeof(this.aButtonOptionDefaultData[sCacheKey]) === 'undefined') {
28052            this.initData();
28053        }
28054
28055        if (typeof(this.aButtonOptionDefaultData[sCacheKey][sOptionValue]) === 'undefined') {
28056            return false;
28057        }
28058
28059        return this.aButtonOptionDefaultData[sCacheKey][sOptionValue];
28060    },
28061
28062    /**
28063     * 옵션을 선택하지 않았을때 하위옵션을 초기화하기위해서 디폴트 HTML을 가져옴
28064     * @param iProductNum 상품번호
28065     * @param iOptionSortNum 옵션 순서
28066     */
28067    getDefaultOptionHTML: function(iProductNum, iOptionSortNum)
28068    {
28069        var sCacheKey = iProductNum + this.cons.OPTION_GLUE + iOptionSortNum;
28070
28071        if (typeof(this.aOptionDefaultData[sCacheKey]) === 'undefined') {
28072            return;
28073        }
28074
28075        return this.aOptionDefaultData[sCacheKey];
28076    },
28077
28078    /**
28079     * 해당 상품의 옵션 재고 관련 데이터를 리턴
28080     * @param iProductNum 상품번호
28081     */
28082    getProductStockData: function(iProductNum) {
28083        if (typeof(this.aItemStockData[iProductNum]) === 'undefined') {
28084            try {
28085                var rawData = window["option_stock_data" + iProductNum];
28086                if (rawData !== undefined) {
28087                    this.aItemStockData[iProductNum] = CAFE24.UTIL.parseJSON(rawData);
28088                }
28089            } catch (e) {
28090                console.error('옵션 데이터를 불러오는 데 실패했습니다: ' + e.message);
28091            }
28092        }
28093
28094        if (this.aItemStockData.hasOwnProperty(iProductNum) === false) {
28095            return null;
28096        }
28097
28098        return this.aItemStockData[iProductNum];
28099    },
28100
28101    /**
28102     * 옵션이 모두 선택되었다면 옵션값 리턴
28103     * @param iProductNum 상품번호
28104     * @param sSelectedOptionValue 선택된 전체 옵션값
28105     * @returns boolean 아이템코드
28106     */
28107    getItemCode: function(iProductNum, sSelectedOptionValue) {
28108        if (typeof(this.aOptioValueMapper[iProductNum]) === 'undefined') {
28109            return false;
28110        }
28111
28112        if (typeof(this.aOptioValueMapper[iProductNum][sSelectedOptionValue]) === 'undefined') {
28113            return false;
28114        }
28115
28116        return this.aOptioValueMapper[iProductNum][sSelectedOptionValue];
28117    },
28118
28119    /**
28120     * 해당 상품의 선택된 옵션의 하위 옵션을 리턴
28121     * @param iProductNum 상품번호
28122     * @param sSelectedValue 현재까지 선택된 옵션값 String(옵션1값 + EC_SHOP_FRONT_NEW_OPTION_CONS.OPTION_GLUE + 옵션2값 형식)
28123     * @returns 옵션리스트
28124     */
28125    getOptionValueArray: function(iProductNum, sSelectedValue) {
28126        if (typeof(this.aOptionValueData[iProductNum]) === 'undefined') {
28127            return false;
28128        }
28129
28130        if (typeof(this.aOptionValueData[iProductNum][sSelectedValue]) === 'undefined') {
28131            return false;
28132        }
28133
28134        return this.aOptionValueData[iProductNum][sSelectedValue];
28135    },
28136
28137    /**
28138     * 옵션 생성에 필요한 기본데이터 정의
28139     */
28140    setDefaultData: function() {
28141        if (typeof(option_stock_data) !== 'undefined') {
28142            this.aItemStockData[iProductNo] = CAFE24.UTIL.parseJSON(option_stock_data);
28143        }
28144        if (typeof(option_value_mapper) !== 'undefined') {
28145            this.aOptioValueMapper[iProductNo] = CAFE24.UTIL.parseJSON(option_value_mapper);
28146        }
28147        if (typeof(product_option_price_display) !== 'undefined') {
28148            this.aOptionPriceDisplayConf[iProductNo] = product_option_price_display;
28149        }
28150
28151        if (typeof(add_option_data) !== 'undefined') {
28152            var aAddOptionJson = CAFE24.UTIL.parseJSON(add_option_data);
28153            for (var iAddProductNo in aAddOptionJson) {
28154                this.aItemStockData[iAddProductNo] = CAFE24.UTIL.parseJSON(aAddOptionJson[iAddProductNo].option_stock_data);
28155                if (typeof(aAddOptionJson[iAddProductNo].option_value_mapper) !== 'undefined') {
28156                    this.aOptioValueMapper[iAddProductNo] = CAFE24.UTIL.parseJSON(aAddOptionJson[iAddProductNo].option_value_mapper);
28157                }
28158
28159                this.aOptionPriceDisplayConf[iAddProductNo] = aAddOptionJson[iAddProductNo].product_option_price_display;
28160            }
28161        }
28162
28163        if (typeof(set_option_data) !== 'undefined') {
28164            var aSetProductData = CAFE24.UTIL.parseJSON(set_option_data);
28165            for (var iSetProductNo in aSetProductData) {
28166                this.aItemStockData[iSetProductNo] = CAFE24.UTIL.parseJSON(aSetProductData[iSetProductNo].option_stock_data);
28167
28168                if (typeof(aSetProductData[iSetProductNo].option_value_mapper) !== 'undefined') {
28169                    this.aOptioValueMapper[iSetProductNo] = CAFE24.UTIL.parseJSON(aSetProductData[iSetProductNo].option_value_mapper);
28170                }
28171
28172                this.aOptionPriceDisplayConf[iSetProductNo] = aSetProductData[iSetProductNo].product_option_price_display;
28173            }
28174        }
28175    },
28176
28177    /**
28178     * 이벤트 옵션의 다음옵션값을 세팅
28179     * @param oOptionChoose 값을 가져오려는 옵션박스 object
28180     */
28181    initializeOptionValue: function(oOptionChoose) {
28182        //상품번호
28183        var iProductNum = this.common.getOptionProductNum(oOptionChoose);
28184
28185        //현재까지 선택된 옵션값 배열
28186        var aSelectedValue = this.common.getAllSelectedValue(oOptionChoose);
28187
28188        var sSelectedValue = aSelectedValue.join(this.cons.OPTION_GLUE);
28189
28190        //기존 선언되지 않은 옵션에대한 처리면 뱌열로 미리 선언
28191        //이미 옵션값이 set되어있으면 바로 리턴
28192        if (typeof(this.aOptionValueData[iProductNum]) === 'undefined') {
28193            this.aOptionValueData[iProductNum] = {};
28194        }
28195        if (typeof(this.aOptionValueData[iProductNum][sSelectedValue]) === 'undefined') {
28196            this.aOptionValueData[iProductNum][sSelectedValue] = new Array();
28197        } else {
28198            return;
28199        }
28200
28201        //선택한 옵션의 순번
28202        var iOptionSortNum = this.common.getOptionSortNum(oOptionChoose);
28203
28204        //옵션값 순서
28205        var iCnt = 1;
28206        //중복옵션값 제거하기 위해서 저장할 옵션값
28207        var aCheckDuplicate = [];
28208
28209
28210        //장바구니 관심상품쪽은 데이터가 이렇게되어있어서 페이지로드시에 어떻게 할수가 없네요..
28211        if (typeof(this.aOptioValueMapper[iProductNum]) === 'undefined') {
28212            try {
28213                var rawData = window["option_value_mapper" + iProductNum];
28214                if (rawData !== undefined) {
28215                    this.aOptioValueMapper[iProductNum] = CAFE24.UTIL.parseJSON(rawData);
28216                }
28217            } catch (e) {
28218                console.error('옵션 데이터를 불러오는 데 실패했습니다: ' + e.message);
28219            }
28220        }
28221
28222        for (var x in this.aOptioValueMapper[iProductNum]) {
28223
28224            //옵션값을 구분자에 따라 배열로 분리(옵션값 => 아이템코드 형태
28225            var aOptions = x.split(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_GLUE);
28226
28227            //옵션값에서 기선택된 값과 비교하기위한 옵션값
28228            var sOptionValue = aOptions.splice(0, iOptionSortNum).join(this.cons.OPTION_GLUE);
28229
28230            //첫번째옵션부터 마지막선택한 옵션까지의 옵션값이 똑같으면서 기존처리된 옵션값이 아니라면 배열에 저장
28231            if (String(sOptionValue) === String(sSelectedValue) && EC$.inArray(aOptions[0], aCheckDuplicate) < 0) {
28232                this.aOptionValueData[iProductNum][sSelectedValue].push({key: iCnt, value: aOptions[0]});
28233                iCnt++;
28234                aCheckDuplicate.push(aOptions[0]);
28235            }
28236        }
28237    },
28238
28239    /**
28240     * 각 옵션값의 전체품절 여부
28241     * @param iProductNum 상품번호
28242     * @param sValue 옵션값
28243     * @returns
28244     */
28245    getSoldoutFlag: function(iProductNum, sValue) {
28246        if (typeof(this.aOptionSoldoutFlag[iProductNum][sValue]) === 'undefined') {
28247            return false;
28248        }
28249
28250        return this.aOptionSoldoutFlag[iProductNum][sValue];
28251    },
28252
28253    /**
28254     * 각 옵션값의 진열 여부
28255     * @param iProductNum 상품번호
28256     * @param sValue 옵션값
28257     * @returns
28258     */
28259    getDisplayFlag: function(iProductNum, sValue) {
28260
28261        if (typeof(this.aOptionDisplayFlag[iProductNum][sValue]) === 'undefined') {
28262            return false;
28263        }
28264
28265        return this.aOptionDisplayFlag[iProductNum][sValue];
28266    },
28267
28268    /**
28269     * 각각의 옵션값(품목말고)마다 해당 옵션전체가 품절인지 체크...
28270     * @param oOptionChoose
28271     */
28272    initializeSoldoutFlag: function(oOptionChoose) {
28273        //해당 옵션의 상품번호
28274        var iProductNum = this.common.getOptionProductNum(oOptionChoose);
28275
28276        if (typeof(this.aOptionSoldoutFlag[iProductNum]) === 'undefined') {
28277            this.aOptionSoldoutFlag[iProductNum] = [];
28278        }
28279
28280        if (typeof(this.aOptionDisplayFlag[iProductNum]) === 'undefined') {
28281            this.aOptionDisplayFlag[iProductNum] = [];
28282        }
28283
28284        //장바구니 관심상품쪽은 데이터가 이렇게되어있어서 페이지로드시에 어떻게 할수가 없네요..
28285        if (typeof(this.aOptioValueMapper[iProductNum]) === 'undefined') {
28286            try {
28287                var rawData = window["option_value_mapper" + iProductNum];
28288                if (rawData !== undefined) {
28289                    this.aOptioValueMapper[iProductNum] = CAFE24.UTIL.parseJSON(rawData);
28290                }
28291            } catch (e) {
28292                console.error('옵션 데이터를 불러오는 데 실패했습니다: ' + e.message);
28293            }
28294        }
28295
28296        for (var x in this.aOptioValueMapper[iProductNum]) {
28297            //옵션값을 구분자에 따라 배열로 분리(옵션값 => 아이템코드 형태
28298            var aOptions = x.split(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_GLUE);
28299
28300            var bIsSoldout = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isSoldout(iProductNum, this.aOptioValueMapper[iProductNum][x]);
28301
28302            var bIsDisplay = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isDisplay(iProductNum, this.aOptioValueMapper[iProductNum][x]);
28303
28304            for (var i = 1; i <= EC$(aOptions).length; i++) {
28305                var sOption = aOptions.slice(0, i).join(CAFE24.SHOP_FRONT_NEW_OPTION_CONS.OPTION_GLUE);
28306
28307                //일단 품절로 세팅하고 품절이 아닌게 하나라도있다면 false로 바꿔준다
28308                if (typeof(this.aOptionSoldoutFlag[iProductNum][sOption]) === 'undefined') {
28309                    this.aOptionSoldoutFlag[iProductNum][sOption] = true;
28310                }
28311
28312                if (bIsSoldout === false) {
28313                    this.aOptionSoldoutFlag[iProductNum][sOption] = false;
28314                }
28315
28316                //일단 진열안함으로 세팅후에 한개라도 진열함이있다면 true바꿔줌다
28317                if (typeof(this.aOptionSoldoutFlag[iProductNum][sOption]) === 'undefined') {
28318                    this.aOptionDisplayFlag[iProductNum][sOption] = false;
28319                }
28320
28321                if (bIsDisplay === true) {
28322                    this.aOptionDisplayFlag[iProductNum][sOption] = true;
28323                }
28324            }
28325        }
28326    }
28327};
28328
28329var EC_SHOP_FRONT_NEW_OPTION_DATA = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_DATA');
28330
28331CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION = {
28332    /**
28333     * CAFE24.SHOP_FRONT_NEW_OPTION_COMMON Obejct Alias
28334     */
28335    common: CAFE24.SHOP_FRONT_NEW_OPTION_COMMON,
28336
28337    cons: CAFE24.SHOP_FRONT_NEW_OPTION_CONS,
28338
28339    /**
28340     * 해당 옵션 그룹에 필수옵션이 속해있는지 여부 확인
28341     * @param sOptionGroup 옵션 그룹 (@see : CAFE24.SHOP_FRONT_NEW_OPTION_GROUP_CONS)
28342     * @returns 필수옵션 존재 여부
28343     */
28344    checkRequiredOption: function(sOptionGroup) {
28345        //해당 옵션 그룹의 필수옵션 갯수
28346        var iRequiredOption = EC$(this.common.getRequiredOption(sOptionGroup)).length;
28347
28348        return (parseInt(iRequiredOption) > 0) ? true : false;
28349    },
28350
28351    /**
28352     * 해당 옵션이 필수옵션인지 확인
28353     * @param oOptionChoose 값을 가져오려는 옵션박스 object
28354     */
28355    isRequireOption: function(oOptionChoose) {
28356        return (Boolean(EC$(oOptionChoose).attr('required')) === true);
28357    },
28358
28359    /**
28360     * 해당 값이 아이템코드인지 확인
28361     * @param sItemCode 선택한 아이템코드
28362     * @returns true이면 아이템코드
28363     * @todo 아이템코드 정규식을 추가..해야하나?? 그래야한다면 선택값여부를(*, **) 따로두고 실제 아이템코드인지 여부를 더 확인해야함
28364     */
28365    isItemCode: function(sItemCode) {
28366        return (EC$.inArray(sItemCode, ['*', '**']) > -1 || typeof(sItemCode) === 'undefined') ? false : true;
28367    },
28368
28369    /**
28370     * 옵션값이 선택되어있는지 확인
28371     * @param oOptionChoose 값을 가져오려는 옵션박스 object
28372     */
28373    isOptionSelected: function(oOptionChoose) {
28374        return (EC$.inArray(this.common.getOptionSelectedValue(oOptionChoose), ['*', '**']) > -1) ? false : true;
28375    },
28376    
28377    /**
28378     * 옵션그룹에서 하나라도 선택이 되었는지 확인
28379     */
28380    isOptionGroupSelected: function(sOptionGroup)
28381    {
28382        var oThis = this;
28383        var bIsChoosen = false;
28384        EC$('[' + this.cons.GROUP_ATTR_NAME + '^="' + sOptionGroup + '"]').each(function() {
28385            if (oThis.isOptionSelected(this) === true) {
28386                bIsChoosen = true;
28387                return false;
28388            }
28389        });
28390        return bIsChoosen;
28391    },
28392    
28393    /**
28394     * 필수 옵션이 모두 선택된 상태인지 여부 확인
28395     * @param sOptionGroup 선택한 아이템코드
28396     * @returns boolean true이면 아이템코드
28397     */
28398    isSelectedRequiredOption: function(sOptionGroup) {
28399        //필수옵션이 하나도 없다면 바로 true
28400        if (this.checkRequiredOption(sOptionGroup) === false) {
28401            return true;
28402        }
28403
28404        var oThis = this;
28405        var bIsComplete = true;
28406        EC$('[' + this.cons.GROUP_ATTR_NAME + '^="' + sOptionGroup + '"]').each(function() {
28407
28408            //핑수옵션이지만 값이 선택되지 않았을경우 false
28409            if (oThis.isRequireOption(this) === true && oThis.isOptionSelected(this) === false) {
28410                bIsComplete = false;
28411                return false;
28412            }
28413        });
28414
28415        return bIsComplete;
28416    },
28417
28418    /**
28419     * 조합분리형만 아이템코드를 가져오는방식이 틀려서 확인용을 추가(연동형도 일단 조합분리형으로 인식하도록 함)
28420     * @param oOptionChoose 구분할 옵션박스 object
28421     * @returns true => 조합분리형, false => 기타옵션타입
28422     */
28423    isSeparateOption: function(oOptionChoose) {
28424        var sOptionTypeStr = EC$(oOptionChoose).attr('option_type');
28425        var sOptionListStr = EC$(oOptionChoose).attr('item_listing_type');
28426        return (Olnk.isLinkageType(sOptionTypeStr) === true || (sOptionTypeStr === 'T' && sOptionListStr === 'S')) ? true : false;
28427    },
28428
28429    /**
28430     * 연동형 옵션 추가 버튼 사용설정을 사용하면 또 순차로딩 하지 않음
28431     * @returns
28432     */
28433    isUseOlnkButton: function() {
28434        return Olnk.getOptionPushbutton(EC$('#option_push_button'));
28435    },
28436    /**
28437     * 세트상품에서 연동형 옵션 추가 버튼 사용설정을 사용하면 또 순차로딩 하지 않음
28438     * @returns
28439     */
28440    isBindUseOlnkButton: function(iProductNum) {
28441        return EC$('#add_option_push_button_'+iProductNum).length > 0;
28442    },
28443    isSoldoutOptionDisplay: function() {
28444        return (typeof(bIsDisplaySoldoutOption) !== 'undefined') ? bIsDisplaySoldoutOption : true;
28445    }
28446};
28447
28448var EC_SHOP_FRONT_NEW_OPTION_VALIDATION = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_OPTION_VALIDATION');
28449
28450//수량 input id
28451var quantity_id = '#quantity:not(.ec-debug)';
28452var bRestockChange = false;
28453
28454EC$(function()
28455{
28456    // 기존 레거시 코드(혹 사용하는몰이 있을까 하여 유지)
28457    if (EC$('.ec-product-couponAjax').length > 0) {
28458        getPrdDetailNewAjax();
28459    }
28460
28461    // 신규 기본디자인에 반영
28462    if (EC$('.ec-product-coupon').length > 0) {
28463        CAFE24.SHOP_FRONT_PRODUCT_INFO_COUPON.getPrdDetailCouponAjax(iProductNo,iCategoryNo);
28464    }
28465
28466    // ECHOSTING-90301 모바일 zoom.html 페이지에서 에러 - 예외처리
28467    try { TotalAddSale.setParam('product_no', iProductNo); } catch (e) {}
28468
28469    EC$("select[id*='product_option_id']").each(function () {
28470        EC$(this).val('*');
28471
28472    });
28473
28474    // 디자인 마이그레이션 - 이걸 여기서 해야할까..
28475    if (EC$('#NewProductQuantityDummy').length > 0 && EC$('#totalProducts').length > 0) {
28476        EC$('#NewProductQuantityDummy').parents('tr').remove();
28477    }
28478
28479    // 수량 초기화
28480    EC$(quantity_id).val(CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity());
28481    EC$('input.single-quantity-input[product-no='+iProductNo+']').val(CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity());
28482    // 펀딩
28483    EC$('input.quantity').val(CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity());
28484
28485    // 품절일 경우 수량 0 설정
28486    if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm === true && EC_FRONT_JS_CONFIG_SHOP.bSoldout === true) {
28487        EC$(quantity_id).val(0);
28488    }
28489
28490    // 판매가 초기화
28491    try {
28492        setPrice(true, false, '');
28493    } catch (e) {}
28494
28495
28496    // 배송타입 초기화
28497    if (delvtype == 'A') {
28498        EC$('#delv_type_A').prop('checked', true);
28499    }
28500
28501    // 배송타입 선택
28502    EC$('[id^="delv_type_"]').change(function()
28503    {
28504        delvtype = EC$(this).val();
28505
28506        // 해외배송이면 선결제 고정
28507        if (delvtype == 'B') {
28508            EC$('#delivery_cost_prepaid').val('P');
28509            if (EC$('.delv_price_C').length > 0) {
28510                EC$('.delv_price_B').hide();
28511                EC$('.delv_price_C').show();
28512            }
28513            try {
28514                if (document.getElementById('NaverChk_Button') != null) {
28515                    document.getElementById('NaverChk_Button').style.display = 'none';
28516                }
28517                if (document.getElementById('kakao-checkout-button') !== null) {
28518                    document.getElementById('kakao-checkout-button').style.display = 'none';
28519                }
28520            } catch (e) {}
28521        } else {
28522            EC$('.delv_price_B').show();
28523            EC$('.delv_price_C').hide();
28524            try {
28525                if (document.getElementById('NaverChk_Button') != null) {
28526                    document.getElementById('NaverChk_Button').style.display = '';
28527                }
28528                if (document.getElementById('kakao-checkout-button') !== null) {
28529                    document.getElementById('kakao-checkout-button').style.display = '';
28530                }
28531            } catch (e) {}
28532        }
28533
28534    });
28535
28536    // 해외 배송 전용 상품은 hidden값 처리
28537    var oHiddenDeliveryType = EC$('[name="delv_type"]:hidden:not(:radio)');
28538    if (oHiddenDeliveryType.length > 0) {
28539        if (EC$('input:radio[id^="delv_type_"]').is(':visible') === true) {
28540            delvtype = EC$('input:radio[id^="delv_type_"]:checked').val();
28541        } else {
28542            oHiddenDeliveryType.each(function() {
28543                // delv_type의 input태그 존재 자체가 해외배송을 사용한다는 의미
28544                if (EC$(this).attr('product_no') == iProductNo) {
28545                    delvtype = 'B';
28546                    return false;
28547                }
28548            });
28549        }
28550    }
28551
28552    if (oSingleSelection.isItemSelectionTypeS() === true) {
28553
28554        // 본체 상품만
28555        oSingleSelection.setProductTargetKey();
28556
28557        EC$(document).on('click change', 'input.single-quantity-input, img.quantity-handle.product-no-' + iProductNo + ', a.quantity-handle.product-no-' + iProductNo, function(e) {
28558
28559            var eSelf = EC$(this);
28560            oSingleSelection.setProductTargetKey(eSelf);
28561            var iBuyUnit = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getBuyUnitQuantity();
28562            var iQuantity = parseInt(oSingleSelection.getQuantityInput(eSelf).val(),10);
28563            if (eSelf.hasClass('up') === true) {
28564                iQuantity = iQuantity + iBuyUnit;
28565            } else if (eSelf.hasClass('down') === true) {
28566                iQuantity = iQuantity - iBuyUnit;
28567            }
28568
28569            var sQuantityInputSelector = ':text,input[type=tel]';
28570            if (CAFE24.checkChannelUI() === true) {
28571                var sContext = 'div[target-key="'+oSingleSelection.getProductTargetKey()+'"]';
28572                if (has_option === 'F') {
28573                    sContext = '#totalProducts div:not(.add_products):not(#dynamic_option)';
28574                }
28575            } else {
28576                var sContext = 'tr[target-key="'+oSingleSelection.getProductTargetKey()+'"]';
28577                if (EC_MOBILE_DEVICE === true || EC_MOBILE === true) {
28578                    sQuantityInputSelector = '[type=number]';
28579                    if (has_option === 'F') {
28580                        sContext = '';
28581                        sQuantityInputSelector = quantity_id;
28582                    }
28583                } else {
28584                    if (has_option === 'F') {
28585                        sContext = '#totalProducts tbody:not(.add_products)';
28586                    }
28587                }
28588            }
28589
28590            EC$('input'+sQuantityInputSelector, sContext).not('.ec-debug').val(iQuantity).trigger('change');
28591            e.stopPropagation();
28592        });
28593
28594        EC$(document).on('click', '.xans-product-quantity a.eClearUp, .xans-product-quantity a.eClearDown', function () {
28595            EC$(this).find('.quantity-handle.product-no-' + iProductNo).click();
28596        });
28597    }
28598
28599
28600    try {
28601        var sContext = ((typeof(isOrderForm) !== 'undefined' && isOrderForm === 'T') || isNewProductSkin() === false || EC_MOBILE === true ? '' :'#totalProducts');
28602        if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
28603            sContext = '.xans-product-funding';
28604            quantity_id = '[id^="quantity_"]';
28605        }
28606        // 수량 증감 버튼(옵션 없는 상품)
28607        EC$(document).on({
28608            click: function() {
28609                setQuantity('click', this);
28610            },
28611            change: function() {
28612                setQuantity('change', this);
28613            }
28614        }, '.QuantityUp' + ',' + '.QuantityDown' + ',' + quantity_id+':not(.ec-debug)', sContext);
28615    } catch (e) {}
28616
28617    // 옵션박스 수량 증감 버튼
28618    try {
28619        EC$(document).on({
28620            click: function(e) {
28621                if (EC$(this).hasClass('eProductQuantityClass') === true) {
28622                    return;
28623                }
28624                setOptionBoxQuantity('click', this);
28625                e.stopPropagation();
28626            },
28627            change: function(e) {
28628                e.preventDefault();
28629                if (EC$(this).hasClass('single-quantity-input') === false && EC$(this).hasClass('eProductQuantityClass') === false) {
28630                    return;
28631                }
28632                setOptionBoxQuantity('change', this);
28633            }
28634        }, '.eProductQuantityClass' + ',' + '.option_box_up' + ',' + '.option_box_down');
28635
28636        EC$(document).on('click', 'a.eProductQuantityUpClass, a.eProductQuantityDownClass', function () {
28637            setOptionBoxQuantity('click', document.getElementById(EC$(this).data('target')));
28638        });
28639    } catch (e) {}
28640
28641
28642    // 옵션박스 선택상품 삭제
28643    try {
28644        EC$(document).on('click', '#totalProducts a.delete', function () {
28645            EC$(this).find('.option_box_del').click();
28646        });
28647        EC$(document).on('click', '.option_box_del', function (event) {
28648            var oSelf = EC$(this);
28649            // onlyone 옵션 셀렉트 박스 원복
28650            var eSelectedItem = EC$('#' + oSelf.attr('id').replace('_del', '_id'));
28651            EC$('option[value="' + eSelectedItem.val() + '"]').parent().removeAttr('is_selected');
28652
28653            if (CAFE24.checkChannelUI() === true) {
28654                oSelf.closest(".option_product").remove();
28655            } else {
28656                oSelf.parents('tr,li').last().remove();
28657            }
28658
28659            var sDelId = EC$(this).attr('id');
28660            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
28661                parent.EC$('option[value="' + eSelectedItem.val() + '"]').parent().removeAttr('is_selected');
28662                parent.EC$('#' + sDelId + '').parents('tr,li').last().remove();
28663            }
28664            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
28665                if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
28666                    EC$("#productOptionIframe").contents().find('option[value="' + eSelectedItem.val() + '"]').parent().removeAttr('is_selected');
28667                    EC$("#productOptionIframe").contents().find('#' + sDelId + '').parents('tr,li').last().remove();
28668                }
28669            }
28670
28671            var sItemCode = NEWPRD_ADD_OPTION.getPerItemCode(eSelectedItem.data('option-index'), eSelectedItem.val());
28672            FileOptionManager.remove('file_option_' + sItemCode);
28673
28674            if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm === true) {
28675                CAFE24.SHOP_FRONT_ORDERFORM_DIRECTBUY.proc.deleteBasketProduct({
28676                    'item_code': eSelectedItem.val(),
28677                    'opt_id': eSelectedItem.attr('data-option-id')
28678                });
28679            }
28680            if (TotalAddSale.needRecalculatorSalePrice() === true) {
28681                oProductList = TotalAddSale.getProductList();
28682                TotalAddSale.setSubscriptionParam();
28683                // 옵션삭제후 재계산
28684                delete oProductList[eSelectedItem.val()];
28685
28686                // 선택옵션없을시 ajax호출안함
28687                if (EC$.isEmptyObject(oProductList)) {
28688                    TotalAddSale.setParam('product', oProductList);
28689                    TotalAddSale.setTotalAddSalePrice(0);
28690                    setTotalData();
28691                } else if (EC$('input.quantity_opt').length > 0) {
28692                    TotalAddSale.setSoldOutFlag(false);
28693                    TotalAddSale.setParam('product', oProductList);
28694                    TotalAddSale.getCalculatorSalePrice(function () {
28695                        setTotalData();
28696
28697                        // 적립금 / 품목금액 갱신
28698                        TotalAddSale.updatePrice();
28699                    });
28700                }
28701            } else {
28702                setTotalData();
28703            }
28704
28705            try {
28706                if (EC$('#NaverChk_Button').length > 0) {
28707                    if (EC$('#NaverChk_Button').children().length < 1) {
28708                        event.stopPropagation(); // 이벤트 전파 중단
28709                        return;
28710                    }
28711                    var iSoldOut = 0;
28712                    EC$('.option_box_id, .soldout_option_box_id').each(function () {
28713                        if (checkSoldOut(EC$(this).val()) === true) {
28714                            iSoldOut++;
28715                        }
28716                    });
28717                    if (iSoldOut > 0) {
28718                        EC$('#NaverChk_Button').css('display', 'none');
28719                    } else {
28720                        EC$('#NaverChk_Button').css('display', 'block');
28721                    }
28722                }
28723            } catch (e) {}
28724
28725            event.stopPropagation();
28726        });
28727    } catch (e) {}
28728
28729    try {
28730        if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
28731            EC$(document).on('click', '.differentialShipping > a', function() {
28732               EC$('.differentialShipping > .layerShipping').show();
28733               return false;
28734            });
28735
28736            EC$(document).on('click', '.layerShipping .btnClose', function() {
28737                EC$(this).parent().hide();
28738                 return false;
28739             });
28740        }
28741    } catch (e) {}
28742
28743    // 차등 배송비 사용시 ToolTip 열기
28744    try {
28745        EC$(document).on('click', '.btnTooltip > a', function () {
28746            EC$('.btnTooltip > .differentialShipping').show();
28747        });
28748    } catch (e) {}
28749    // 차등 배송비 사용시 ToolTip 닫기
28750    EC$('.btnTooltip > .differentialShipping a').off().click(function() {
28751        EC$('.btnTooltip > .differentialShipping').hide();
28752    });
28753
28754    // 차등 배송비 사용시 ToolTip 열기 (모바일)
28755    EC$('.differentialShipping > .btnHelp').off().click(function() {
28756       EC$('.differentialShipping > .layerShipping').show();
28757    });
28758    // 차등 배송비 사용시 ToolTip 닫기 (모바일)
28759    EC$('.differentialShipping > .layerShipping > a').off().click(function() {
28760        EC$('.differentialShipping > .layerShipping').hide();
28761    });
28762
28763    try {
28764        // 추가입력옵션 글자 길이 체크
28765        EC$(document).on('keyup', '.input_addoption',function() {
28766            var eSelf = EC$(this);
28767            var iLimit = eSelf.attr('maxlength');
28768            addOptionWordWithObj(eSelf, eSelf.val(), iLimit);
28769        });
28770
28771        EC$(document).on('blur', '.input_addoption',function() {
28772            EC$(this).siblings('.txt_help').remove();
28773            EC$(this).parent('.ec-input-count').removeClass('error');
28774        });
28775    } catch (e) {}
28776
28777    EC$('ul.discountMember img.ec-front-product-show-benefit-icon').click(function() {
28778
28779        EC$('ul.discountMember li > div.discount_layer').hide();
28780
28781        if (EC$(this).parent().parent().has('div.discount_layer').length == 0) {
28782            var sBenefitType = EC$(this).attr('benefit');
28783            var oObj = EC$(this);
28784            var oHtml = EC$('<div>');
28785            var iBenefitProductNo = EC$(this).attr('product-no');
28786            oHtml.addClass('ec-base-tooltip discount_layer');
28787
28788            //회원등급관리의 등급할인인 경우 class추가
28789            if (sBenefitType == 'MG') {
28790                oHtml.addClass('member_rating');
28791            }
28792
28793            EC$(this).parent().parent().append(oHtml);
28794            EC$.post('/exec/front/Product/Benefitinfo', 'benefit_type='+sBenefitType+'&product_no=' + iBenefitProductNo, function(sHtml) {
28795                oHtml.html(sHtml);
28796            });
28797
28798        } else {
28799            EC$(this).parent().parent().find('div.discount_layer').show();
28800        }
28801        return false;
28802    });
28803
28804    try {
28805        EC$(document).on('click', 'div.discount_layer .close', function () {
28806            EC$(this).parent().hide();
28807            return false;
28808        });
28809    } catch (e) {}
28810
28811    EC$('div.shippingFee a').click(function() {
28812        EC$('ul.discountMember li > div.discount_layer').hide();
28813        EC$('ul.discountMember li > span.arrow').hide();
28814
28815        if (EC$(this).parent().parent().has('div.ec-base-tooltip').length == 0) {
28816            var sBenefitType = EC$(this).attr('benefit');
28817            var oObj = EC$(this);
28818            var oHtml = EC$('<div>');
28819            oHtml.addClass('ec-base-tooltip');
28820            oHtml.addClass('wrap');
28821
28822            //회원등급관리의 등급할인인 경우 class추가
28823            if (sBenefitType == 'MG') {
28824                oHtml.addClass('member_rating');
28825            }
28826
28827            EC$(this).parent().append(oHtml);
28828            EC$.post('/exec/front/Product/Benefitinfo', 'benefit_type=' + sBenefitType + '&product_no=' + iProductNo, function(sHtml) {
28829                oHtml.html(sHtml);
28830            });
28831        }
28832
28833        EC$(this).parent().parent().find('div.ec-base-tooltip').show();
28834        EC$(this).parent().parent().find('span.arrow').show();
28835        return false;
28836    });
28837
28838    try {
28839        EC$(document).on('click', '.ec-base-tooltip .close', function () {
28840            EC$(this).parent().hide();
28841            EC$(this).parent().parent().find('span.arrow').hide();
28842            EC$('.differentialShipping').hide();
28843            return false;
28844        });
28845    } catch (e) {}
28846
28847    var oMileageTooltipOrigin = $('#mileage_tooltip_origin');
28848    var oMileageTooltipClone = oMileageTooltipOrigin.clone();
28849    oMileageTooltipClone.attr('id', 'mileage_tooltip_clone').show();
28850    oMileageTooltipOrigin.parents('td').append(oMileageTooltipClone);
28851
28852    // 적립금 자세히보기
28853    EC$('div.mileage_tooltip a').click(function() {
28854
28855        if (EC$(this).parent().parent().has('.ec-base-tooltip.mileage_layer').length === 0) {
28856            var oThis = EC$(this);
28857            var sParam = 'product_no=' + iProductNo;
28858
28859            EC$.post('/exec/front/Product/Mileageinfo', sParam, function(sHtml) {
28860                oThis.parent().append(sHtml);
28861                oThis.parent().parent().find('div.ec-base-tooltip').show();
28862            });
28863        }
28864
28865        EC$(this).parent().parent().find('div.ec-base-tooltip').show();
28866        return false;
28867    });
28868
28869    // 단일 상품 품절일 경우 수량 0 설정
28870    if (EC_FRONT_JS_CONFIG_SHOP.bSoldout === true) {
28871        EC$(quantity_id).val(0);
28872    }
28873
28874    CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.setStockStatus(iProductNo);
28875
28876    // 구매옵션레이어 사용가능 여부 세팅
28877    // Controller에서 확인하도록 바꿀까...
28878    CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.init();
28879    // sms 재입고 알림 레이어 팝업 노출여부 확인
28880    EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.setCheckSmsRestockLayerPopup();
28881
28882    // 바로구매 주문서 로그인페이지로 이동
28883    CAFE24.SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY.setAccessRestriction();
28884
28885    // ch_ref값 추가전달
28886    try { TotalAddSale.setParam('ch_ref', CAFE24.getChRefData()); } catch (e) {}
28887
28888    // GE 활성 시 페이지 로드 시점에 세금/관세 안내 문구 부착
28889    // 옵션 X 상품 또는 옵션 미선택 상태(setProductTotalPrice 미호출)에서도 부착되도록 트리거
28890    try { setGlobaleTaxPolicyText(); } catch (e) {}
28891});
28892
28893/**
28894 * 모바일 상품옵션Layer 닫기
28895 * @param bIsOptionInit 옵션선택 레이어 닫을때 선택된 옵션을 부모창과 동기화할것인지 여부
28896 */
28897function closeBuyLayer(bIsOptionInit)
28898{
28899    if (bIsOptionInit !== false) {
28900        var iTotalOptCnt = EC$('select[id^="' + product_option_id + '"]').length;
28901        EC$('select[id^="' + product_option_id + '"]').each(function (i) {
28902            //독립형은 이미 선택되어있는 상태이기때문에 Pass
28903            if (CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionType(this) === 'F') {
28904                return;
28905            }
28906            var sSelectOptionId = EC$(this).attr('id');
28907            var sParentVal = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(this);
28908            var oTarget = parent.EC$('#'+sSelectOptionId+'');
28909            parent.CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oTarget, sParentVal);
28910            if (i < iTotalOptCnt - 1) {
28911                parent.EC$('#'+sSelectOptionId+'').trigger('change');
28912            }
28913        });
28914
28915        // @see ECHOSTING-419410
28916        // 레이어(iframe) 내부에 선택된 품목을 부모창으로 싱크
28917        var oSelectedItem = TotalAddSale.getProductList();
28918
28919        if (Object.keys(oSelectedItem).length > 0) {
28920            EC$.each(oSelectedItem, function(sItemCode, iCount) {
28921                parent.TotalAddSale.setQuantity(sItemCode, iCount);
28922            });
28923        }
28924
28925        // 파일첨부 리스트 복사
28926        var eFileOption = EC$('[name^="file_option"]');
28927        if (eFileOption.length > 0) {
28928            var sId = eFileOption.attr('id');
28929            FileOptionManager.sync(sId, parent.EC$('ul#ul_' + sId));
28930        }
28931
28932        // 추가입력 복사
28933        var eAddOption = EC$('input.input_addoption');
28934        eAddOption.each(function () {
28935            if (EC$(this).val() !== '') {
28936                parent.EC$('input#'+ EC$(this).attr('id')+ '[add_product_code="' + EC$(this).attr('add_product_code') + '"]').val(EC$(this).val());
28937            }
28938        });
28939    }
28940    parent.EC$('html, body').css({'overflowY': 'auto', height: 'auto', width: '100%'});
28941    if (typeof(bIsOptionInit) === 'undefined') {
28942        parent.EC$('#opt_layer_window').remove();
28943    } else {
28944        parent.EC$('#opt_layer_window').hide();
28945    }
28946}
28947
28948
28949/**
28950 * 선택한 옵션 품절여부 체크
28951 * @param sOptionId 옵션 id
28952 * @returns 품절여부
28953 */
28954function checkSoldOut(sOptionId)
28955{
28956    var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
28957    var bSoldOut = false;
28958
28959    // get_stock_info
28960    if (aStockData[sOptionId] == undefined) {
28961        iStockNumber = -1;
28962        iOptionPrice = 0;
28963        bStock = false;
28964        sIsDisplay = 'T';
28965        sIsSelling = 'T';
28966    } else {
28967        iStockNumber = aStockData[sOptionId].stock_number;
28968        iOptionPrice = aStockData[sOptionId].option_price;
28969        bStock = aStockData[sOptionId].use_stock;
28970        sIsDisplay = aStockData[sOptionId].is_display;
28971        sIsSelling = aStockData[sOptionId].is_selling;
28972    }
28973    if (sIsSelling == 'F' || ((iStockNumber < buy_unit || iStockNumber <= 0) && (bStock === true || sIsDisplay == 'F'))) {
28974        bSoldOut = true;
28975    }
28976    return bSoldOut;
28977}
28978
28979
28980/**
28981 * 옵션없는 구매수량 체크
28982 * @param sEventType 이벤트 타입
28983 * @param oObj Object정보
28984 */
28985function setQuantity(sEventType, oObj)
28986{
28987    EC_SHOP_FRONT_DEBUG.log("fn - setQuantity");
28988
28989    // 단일 상품 품절일 경우 수량 계산 하지 않음.
28990    if (EC_FRONT_JS_CONFIG_SHOP.bSoldout === true) {
28991        return;
28992    }
28993
28994    var $oQuantityElement = EC$(quantity_id);
28995    if (EC$('.EC-funding-checkbox').length > 0) {
28996        $oQuantityElement = EC$(oObj).closest('.xans-product-funding').find('input.quantity');
28997    }
28998    var iQuantity = parseInt($oQuantityElement.val(),10);
28999    var iBuyUnit = parseInt(buy_unit);
29000    var iProductMin = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
29001
29002    if (sEventType == 'click') {
29003        var iProductCustom = EC$('#product_custom').val();
29004        var sQuantityClass = '.' + oObj.className;
29005        if (sQuantityClass.indexOf('.QuantityUp') >= 0 || EC$(oObj).hasClass('QuantityUp') || EC$(oObj).hasClass('up')) {
29006            iQuantity = iQuantity + iBuyUnit;
29007        } else if (sQuantityClass.indexOf('.QuantityDown') >= 0 || EC$(oObj).hasClass('QuantityDown') || EC$(oObj).hasClass('down')) {
29008            iQuantity = iQuantity - iBuyUnit;
29009        }
29010    }
29011
29012    // [ECHOSTING-604271] 재고수량과 최대주문수량 중 작은 값으로 보정
29013    var iMaxQuantity = (product_max > 0) ? parseInt(product_max, 10) : 0;
29014    if (typeof single_option_stock_data !== 'undefined') {
29015        var aSingleStock = CAFE24.UTIL.parseJSON(single_option_stock_data);
29016        if (aSingleStock.use_stock === true && aSingleStock.use_soldout === 'T') {
29017            var iStock = parseInt(aSingleStock.stock_number, 10);
29018            iMaxQuantity = (iMaxQuantity > 0) ? Math.min(iMaxQuantity, iStock) : iStock;
29019        }
29020    }
29021    // 구매단위(buy_unit) 보정
29022    if (iBuyUnit > 1) {
29023        iMaxQuantity = Math.floor(iMaxQuantity / iBuyUnit) * iBuyUnit;
29024    }
29025    if (iQuantity > iMaxQuantity && iMaxQuantity > 0) {
29026        alert(sprintf(__('최대 주문수량은 %s개 입니다.'), iMaxQuantity));
29027        $oQuantityElement.val(iMaxQuantity);
29028        return;
29029    }
29030
29031    // 최대 구매수량과 펀딩 제한 수량은 별개로 동작해야함
29032    if (EC$('.EC-funding-checkbox').length > 0) {
29033        var iCompositionLimit = parseInt($oQuantityElement.attr('limit-quantity'), 10);
29034        if (iCompositionLimit > 0 && iQuantity > iCompositionLimit) {
29035            alert(sprintf(__('최대 주문수량은 %s개 입니다.'), iCompositionLimit));
29036            $oQuantityElement.val(iCompositionLimit);
29037            return;
29038        }
29039    }
29040
29041    if (iQuantity < iProductMin) {
29042        alert(sprintf(__('최소 주문수량은 %s개 입니다.'), iProductMin));
29043        $oQuantityElement.val(iProductMin);
29044        return;
29045    }
29046
29047
29048    $oQuantityElement.val(iQuantity);
29049    if (oSingleSelection.isItemSelectionTypeS() === true) {
29050        EC$('input.single-quantity-input[product-no='+iProductNo+']').val(iQuantity);
29051    }
29052    if (EC$('.EC-funding-checkbox').length > 0) {
29053        var sCompositionCode = $oQuantityElement.attr('composition-code');
29054        EC$('.selected-funding-item.option_box_price[composition-code="'+sCompositionCode+'"]').attr('quantity', iQuantity);
29055    }
29056
29057    setPrice(false, false, '');
29058
29059    // 총 주문금액/수량 처리
29060    setTotalData();
29061
29062    // 구스킨인경우 판매금액 계산
29063    if (isNewProductSkin() === false) {
29064        setOldTotalPrice();
29065    }
29066}
29067
29068/**
29069 * 옵션박스 구매수량 체크
29070 * @param sEventType 이벤트별 수량 체크
29071 * @param oObj Object정보
29072 */
29073function setOptionBoxQuantity(sEventType, oObj)
29074{
29075    EC_SHOP_FRONT_DEBUG.log("fn - setOptionBoxQuantity");
29076
29077    var sOptionId = '', sOptionBoxId = '', sProductPrice = '';
29078    var iQuantity = 0;
29079    var iBuyUnit = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getBuyUnitQuantity();
29080
29081    if (sEventType == 'click') {
29082        // 구매수량 화살표로 선택
29083        var sType = EC$(oObj).attr('id').indexOf('_up') > 0 ? '_up' : '_down';
29084        sOptionBoxId = '#' + EC$(oObj).attr('id').substr(0, EC$(oObj).attr('id').indexOf(sType));
29085        iQuantity = parseInt(EC$(sOptionBoxId + '_quantity').val(), 10);
29086        sOptionId = EC$(sOptionBoxId + '_id').val();
29087        if (sType == '_up') {
29088            iQuantity = iQuantity + iBuyUnit;
29089        } else if (sType == '_down') {
29090            iQuantity = iQuantity - iBuyUnit;
29091        }
29092    } else if (sEventType == 'change') {
29093        // 구매수량 직접 입력
29094        sOptionBoxId = '#' + EC$(oObj).attr('id').substr(0, EC$(oObj).attr('id').indexOf('_quantity'));
29095        iQuantity = parseInt(EC$(oObj).val(), 10);
29096        sOptionId = EC$(sOptionBoxId + '_id').val();
29097    }
29098    // 최소 구매 수량 체크
29099    var iProductMin = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
29100
29101    if (iQuantity < iProductMin) {
29102        alert(sprintf(__('최소 주문수량은 %s개 입니다.'), iProductMin));
29103        iQuantity = iProductMin;
29104        EC$(oObj).val(iQuantity).blur();
29105        return;
29106    }
29107
29108    if (iQuantity > product_max && product_max > 0) {
29109        alert(sprintf(__('최대 주문수량은 %s개 입니다.'), product_max));
29110        iQuantity = product_max;
29111        EC$(oObj).val(iQuantity).blur();
29112        return;
29113    }
29114    var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
29115    var iOptionPrice = 0;
29116    var iTotalQuantity = iQuantity;
29117    var iStockNumber = 0;
29118    var bUseStock = '';
29119    var bUseSoldOut = '';
29120    var iAddOptionPrice = 0; // 연동형 옵션인 경우 판매가를 제외한 옵션 자체에 붙은 금액을 따로 보관하자
29121
29122    if (Olnk.isLinkageType(sOptionType) === true) {
29123        var sOptionIdTemp = '';
29124        if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
29125            sOptionIdTemp = sOptionId;
29126            if (aStockData.hasOwnProperty(sOptionId) === false) {
29127                sOptionIdTemp = 'default';
29128            }
29129            // 실제로 금액이 중요한게 아니라 0인지 아닌지만 판단하면 되기 때문에 0.00을 int로 캐스팅하여 비교
29130            if (parseInt(aStockData[sOptionIdTemp].stock_price, 10) !== 0) {
29131                iOptionPrice = parseFloat(aStockData[sOptionIdTemp].option_price);
29132                iAddOptionPrice = parseFloat(aStockData[sOptionIdTemp].option_price);
29133            }
29134        } else {
29135            var aOptionTmp = sOptionId.split('||');
29136            var aOptionIdTmp = new Array;
29137            for (i = 0; i < aOptionTmp.length; i++) {
29138                if (aOptionTmp[i] !== '') {
29139                    aOptionIdTmp = aOptionTmp[i].split('_');
29140                    if (/^\*+$/.test(aOptionIdTmp[0]) === false) {
29141                        iOptionPrice = iOptionPrice + parseFloat(aStockData[aOptionIdTmp[0]].option_price);
29142                        iAddOptionPrice = parseFloat(aStockData[aOptionIdTmp[0]].option_price);
29143                        sOptionIdTemp = aOptionIdTmp[0];
29144                    }
29145                }
29146            }
29147        }
29148
29149        if ((Olnk.bAllSelectedOption === true || Olnk.getOptionPushbutton(EC$('#option_push_button')) === true) && sOptionIdTemp === '') {
29150            sOptionIdTemp = sProductCode;
29151        }
29152
29153        iOptionPrice = parseFloat(product_price) + iOptionPrice;
29154
29155        iStockNumber = parseInt(aStockData[sOptionIdTemp].stock_number);
29156        bUseStock = aStockData[sOptionIdTemp].use_stock;
29157        bUseSoldOut = aStockData[sOptionIdTemp].use_soldout;
29158
29159
29160        if (typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type') && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation') {
29161            // 예약형은 현재 선택된 옵션과의 비교만 필요
29162            iTotalQuantity = iQuantity;
29163        } else {
29164            // iTotalQuantity 연동형 옵션의 경우 현재 옵션박스에 되어 있는 모든 품목의 재고를 더해야 한다.(추가 구성상품의 경우 따로 체크함)
29165            var sAddOptionBoxNum = '';
29166            EC$('[name="quantity_opt[]"]').each(function() {
29167                sAddOptionBoxNum = EC$(this).attr('id').replace('quantity','');
29168                if (EC$(this).attr('id').indexOf('add_') < 0 && EC$(oObj).attr('id').indexOf(sAddOptionBoxNum) < 0) {
29169                    iTotalQuantity += parseInt(EC$(this).val());
29170                }
29171            });
29172        }
29173
29174        // 최대 재고 수량 체크
29175        if (bUseSoldOut === 'T' && bUseStock === true && iTotalQuantity > iStockNumber) {
29176            alert(sprintf(__('재고 수량이 %s개 존재합니다. 재고수량 이하로 입력해주세요.'), iStockNumber));
29177            EC$(oObj).val(iStockNumber);
29178            return;
29179        }
29180    } else {
29181        iStockNumber = parseInt(aStockData[sOptionId].stock_number);
29182        iOptionPrice = parseFloat(aStockData[sOptionId].option_price);
29183    }
29184
29185    if (oSingleSelection.isItemSelectionTypeS() === true) {
29186        var iProductNum = iProductNo;
29187        var iOptionSequence = 1;
29188        if (option_type === 'F') {
29189            if (CAFE24.checkChannelUI() === true) {
29190                iOptionSequence = EC$(oObj).parents('div.option_product').attr('target-key').split('|')[1];
29191            } else {
29192                iOptionSequence = EC$(oObj).parents('tr.option_product').attr('target-key').split('|')[1];
29193            }
29194        }
29195        EC$('input.single-quantity-input[product-no='+iProductNum+'][option-sequence='+iOptionSequence+']').val(iQuantity);
29196    }
29197
29198    iProductPrice = getProductPrice(iQuantity, iOptionPrice, sOptionId, null, function(iProductPrice)
29199    {
29200        var bIsValidBundleObject = typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE === 'object';
29201        var iProductNum = (has_option === 'T') ? EC$(sOptionBoxId + '_quantity').attr('product-no') : iProductNo;
29202        //1+N 상품일 경우 품목별 가격은 변경되지 않음
29203        var iTotalPrice = (bIsValidBundleObject === true && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNum) === true) ? iOptionPrice : iOptionPrice * iQuantity;
29204        sProductPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
29205
29206        // ECHOSTING-58174
29207        if (sIsDisplayNonmemberPrice == 'T') {
29208            sProductPrice = sNonmemberPrice;
29209            iProductPrice = 0;
29210        }
29211
29212        EC$(sOptionBoxId + '_quantity').val(iQuantity);
29213        EC$(sOptionBoxId + '_price').find('span').html(sProductPrice);
29214        EC$(sOptionBoxId + '_price').find('input').val(iProductPrice);
29215
29216        // 적립금 계산
29217        if (typeof (mileage_val) !== 'undefined') {
29218
29219            var iStockPrice = 0;
29220            if (Olnk.isLinkageType(sOptionType) === true) {
29221                iStockPrice = iAddOptionPrice;
29222            } else if (typeof (aStockData[sOptionId].stock_price) !== 'undefined') {
29223                iStockPrice = aStockData[sOptionId].stock_price;
29224            }
29225            var mileage_price = TotalAddSale.getMileageGenerateCalc(sOptionId, iQuantity);
29226
29227            if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
29228                EC$(sOptionBoxId + '_mileage').html(CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(mileage_price));
29229            } else {
29230                if (mileage_price > 0) {
29231                    EC$(sOptionBoxId + '_mileage').html(CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(mileage_price));
29232                }
29233            }
29234            if (sIsDisplayNonmemberPrice == 'T') {
29235                EC$(sOptionBoxId + '_mileage').html(sNonmemberPrice);
29236            }
29237        }
29238
29239        // 구매레이어
29240        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
29241            parent.EC$(sOptionBoxId + '_quantity').val(iQuantity);
29242            parent.EC$(sOptionBoxId + '_price').find('span').html(sProductPrice);
29243            parent.EC$(sOptionBoxId + '_price').find('input').val(iProductPrice);
29244            if (typeof (mileage_val) !== 'undefined') {
29245                parent.EC$(sOptionBoxId + '_mileage').html(CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(mileage_price));
29246                if (sIsDisplayNonmemberPrice == 'T') {
29247                    parent.EC$(sOptionBoxId + '_mileage').html(sNonmemberPrice);
29248                }
29249            }
29250        }
29251        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
29252            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
29253                EC$("#productOptionIframe").contents().find(sOptionBoxId + '_quantity').val(iQuantity);
29254                EC$("#productOptionIframe").contents().find(sOptionBoxId + '_price').find('span').html(sProductPrice);
29255                EC$("#productOptionIframe").contents().find(sOptionBoxId + '_price').find('input').val(iProductPrice);
29256            }
29257            if (typeof (mileage_val) !== 'undefined') {
29258                EC$("#productOptionIframe").contents().find(sOptionBoxId + '_mileage').html(CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(mileage_price));
29259                if (sIsDisplayNonmemberPrice == 'T') {
29260                    EC$("#productOptionIframe").contents().find(sOptionBoxId + '_mileage').html(sNonmemberPrice);
29261                }
29262            }
29263        }
29264        // 총 주문금액/수량 처리
29265        setTotalData();
29266
29267        // 적립금 / 품목금액 갱신 (현재 품목 제외)
29268        TotalAddSale.updatePrice(sOptionBoxId, sOptionId);
29269    });
29270}
29271
29272// 자바스크립트 number_format jsyoon
29273function number_format(str)
29274{
29275    str += '';
29276
29277    var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
29278
29279    while (objRegExp.test(str)) {
29280        str = str.replace(objRegExp,'$1,$2');
29281    }
29282
29283    return str;
29284}
29285
29286/**
29287 * 가격계산 후 판매가에 반영
29288 * @param bInit 초기값여부
29289 * @param bOption 옵션선택여부
29290 * @param sOptionId 단독구성형일때는 SelectBox가 여러개이므로 선택한 OptionId 필요
29291 */
29292function setPrice(bInit, bOption, sOptionId)
29293{
29294    EC_SHOP_FRONT_DEBUG.log("fn - setPrice");
29295
29296    var sQuantityString = '(' + sprintf(__('%s개'),0) + ')';
29297
29298    // 판매가 대체 문구시 가격 계산 안함
29299    if (product_price_content == true) {
29300        if (sIsDisplayNonmemberPrice == 'T') {
29301            EC$('#totalProducts .total').html('<strong><em>'+sNonmemberPrice+'</em></strong> ' + sQuantityString + '</span>');
29302        }
29303        return false;
29304    }
29305
29306    // 옵션이 없는 경우 수량 초기화
29307    if (has_option == 'F' && (isNaN(EC$(quantity_id).val()) === true || EC$(quantity_id).val() == '' || EC$(quantity_id).val().indexOf('.') > 0)) {
29308        EC$(quantity_id).val(product_min);
29309    }
29310
29311    if (bInit === true) {
29312        setProductPriceText();
29313    }
29314    // 옵션이 없을 경우
29315    if (has_option == 'F') {
29316        setPriceHasOptionF();
29317    } else if (has_option == 'T') {
29318        if (typeof sOptionType !== 'undefined' && Olnk.isLinkageType(sOptionType) === false) {
29319            setPriceHasOptionT(bOption, sOptionId);
29320        } else {
29321            if (Olnk.getOptionPushbutton(EC$('#option_push_button')) === false) {
29322                iQuantity = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
29323                if (oSingleSelection.isItemSelectionTypeS() === true) {
29324                    iQuantity = PRODUCTSUBMIT.getQuantity();
29325                    Olnk.bAllSelectedOption = true;
29326                }
29327                if (EC$('.EC-funding-checkbox').length > 0) {
29328                    var sCompositionCode = EC$(CAFE24.SHOP_FRONT_NEW_OPTION_BIND.oOptionObject).attr('composition-code');
29329                    if (CAFE24.SHOP_FRONT_NEW_OPTION_BIND.oOptionObject === null) {
29330                        sCompositionCode = CAFE24.SHOP_FRONT_PRODUCT_FUNDING.sCurrentCompositionCode;
29331                    }
29332                    sSelector = EC$('#quantity_'+sCompositionCode);
29333                    iQuantity = PRODUCTSUBMIT.getQuantity(sSelector);
29334                    //Olnk.bAllSelectedOption = true;
29335                }
29336                Olnk.handleTotalPrice(option_stock_data, product_price, sIsDisplayNonmemberPrice,false, iQuantity);
29337
29338                // 적립금 / 품목금액 갱신
29339                TotalAddSale.updatePrice();
29340            }
29341        }
29342    }
29343
29344    // 적립금 처리
29345    setMileage(bInit);
29346}
29347
29348/**
29349 *  모바일 할인가 계산 후 리턴
29350*/
29351function getMobileDcPrice(iPrice) {
29352
29353    var iReturnMobileDcPrice = 0;
29354    var iTmpBasePrice = 0;
29355    var iPer = 0;
29356
29357    // 정율 할인일 경우
29358    if (sc_mobile_dc_value_flag == 'P') {
29359        iPer = sc_mobile_dc_value * 0.01;
29360        iTmpBasePrice = iPrice * iPer;
29361        iTmpBasePrice = getMobileDcLimitPrice(iTmpBasePrice);
29362        iReturnMobileDcPrice = Math.ceil(iPrice - iTmpBasePrice);
29363    }
29364    // 금액 할인일 경우
29365    else {
29366        iReturnMobileDcPrice = iPrice - sc_mobile_dc_value;
29367    }
29368
29369    return iReturnMobileDcPrice;
29370}
29371
29372/**
29373 *  모바일 할인가 금액 절사 후 리턴
29374 *
29375*/
29376function getMobileDcLimitPrice(MobileDcPrice) {
29377
29378    var iFloat = 0;
29379    var iOpp = 0;
29380
29381    switch (sc_mobile_dc_limit_value) {
29382
29383        // 절사 안함
29384        case "F" : return MobileDcPrice; break;
29385
29386        // 원단위 절사
29387        case "O" :
29388            iFloat = 0.1;
29389            iOpp = 10;
29390        break;
29391
29392        // 십원단위 절사
29393        case "T" :
29394            iFloat = 0.01;
29395            iOpp = 100;
29396        break;
29397
29398        // 백원단위 절사
29399        case "M" :
29400            iFloat = 0.001;
29401            iOpp = 1000;
29402        break;
29403    }
29404
29405    MobileDcPrice = MobileDcPrice * iFloat;
29406
29407    // 반올림인지 내림인지
29408    if (sc_mobile_dc_limit_flag == 'L') { MobileDcPrice = Math.floor(MobileDcPrice) * iOpp; }
29409    else if (sc_mobile_dc_limit_flag == 'U') { MobileDcPrice = Math.round(MobileDcPrice) * iOpp; }
29410
29411    return MobileDcPrice;
29412}
29413/**
29414 * 적립금 계산 후 반영
29415 */
29416function setMileage(bInit)
29417{
29418    if (bInit === true && (EC_MOBILE === true || EC_MOBILE_DEVICE === true)) {
29419        if (sIsDisplayNonmemberPrice == 'T') {
29420            EC$('#span_mileage_text').html(sNonmemberPrice);
29421        }
29422    }
29423
29424}
29425
29426/**
29427 * 싸이월드 스크랩 하기
29428 * @param sMallId 몰아이디
29429 * @param iPrdNo 상품번호
29430 * @param iCateNo 카테번호
29431 * @param iSid 승인번호
29432 * @author 김성주 <[email protected]>
29433 */
29434function cyConnect(sMallId, iPrdNo, iCateNo, iSid)
29435{
29436    return;
29437}
29438
29439/**
29440 * 싸이월드 스크랩 설명 보여주기
29441 * @author 김성주 <[email protected]>
29442 */
29443function openNateInfo(num)
29444{
29445    if (num == "1") {
29446        document.getElementById('divNate').style.display="none";
29447    } else {
29448        document.getElementById('divNate').style.display="";
29449    }
29450}
29451
29452/**
29453 * 판매가 표시설정
29454 */
29455function setProductPriceText()
29456{
29457    var sString = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(product_price);
29458    if (typeof product_price_ref !== 'undefined' && product_price_ref > 0) {
29459        // 화폐 노출 순서 설정 ECHOSTING-56540
29460        if (currency_disp_type == 'P') {
29461            sString += ' ' + txt_product_price_ref;
29462        } else {
29463            sString = txt_product_price_ref + ' ' + sString;
29464        }
29465    }
29466    // ECHOSTING-58174
29467    if (sIsDisplayNonmemberPrice == 'T') {
29468        sString = sNonmemberPrice;
29469    }
29470
29471    // ECHOSTING-67418 구상품일때도 판매가 영역이 바뀌게 처리 (초기화시 최소 구매수량 개수에 맞게 노출)
29472    if (isNewProductSkin() === false && sIsDisplayNonmemberPrice !== 'T') {
29473        iPrice = getProductPrice(product_min, product_price, null, null, function(iPrice) {
29474            sString = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iPrice);
29475            EC$('#span_product_price_text').html(sString);
29476        });
29477    } else {
29478        EC$('#span_product_price_text').html(sString);
29479    }
29480    var sMobileClass = '';
29481    if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
29482        sMobileClass = ' class = "price"';
29483    }
29484    var sTotalPriceSelector = oSingleSelection.getTotalPriceSelector();
29485    var sQuantityString = '('+sprintf(__('%s개'),0)+')';
29486    if (CAFE24.checkChannelUI() === true) {
29487        sQuantityString = '';
29488    }
29489    if (oSingleSelection.isItemSelectionTypeS() === true) {
29490        var sStrPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(0);
29491
29492        EC$(sTotalPriceSelector).html('<strong'+sMobileClass+'><em>'+sStrPrice+'</em></strong> '+sQuantityString+'</span>');
29493        setTotalPriceRef(0, sQuantityString);
29494    }
29495
29496    // ECHOSTING-58174
29497    if (sIsDisplayNonmemberPrice == 'T') {
29498        if (sNonmemberPrice === "") {
29499            sNonmemberPrice = "-";
29500        }
29501        EC$(sTotalPriceSelector).html('<strong'+sMobileClass+'><em>'+sNonmemberPrice+'</em></strong> ' + sQuantityString + '</span>');
29502    }
29503    ReferenceCurrencyPrice.init();
29504
29505}
29506
29507/**
29508 * 전체 금액 리턴
29509 * @returns {Number}
29510 */
29511function getTotalPrice()
29512{
29513    var iTotalPrice = 0;
29514    EC$('.option_box_price').each(function() {
29515        iTotalPrice += parseInt(EC$(this).val());
29516    });
29517
29518    return iTotalPrice;
29519}
29520
29521/**
29522 * 금액설정(옵션이 없는 경우)
29523 */
29524function setPriceHasOptionF()
29525{
29526    if (EC$('#totalProducts').length === 0) {
29527        return;
29528    }
29529    try {
29530        iQuantity = parseInt(EC$(quantity_id).val().replace(/^[\s]+|[\s]+$/g,'').match(/[\d\-]+/),10);
29531    } catch (e) {}
29532    var iMaxCnt = 2147483647;
29533    if (iQuantity > iMaxCnt) {
29534        EC$(quantity_id).val(iMaxCnt);
29535        iQuantity = iMaxCnt;
29536    }
29537    // 모바일 할인가 추가.
29538    if (typeof (EC$('#span_product_price_mobile_text')) !== 'undefined') {
29539        try {
29540            var iPriceMobile = parseFloat(product_price_mobile,10);
29541        }
29542        catch (e) { var iPriceMobile = product_price; }
29543    }
29544    TotalAddSale.setParam('ch_ref', CAFE24.getChRefData());
29545    var iTotalPrice = getProductPrice(iQuantity, product_price, item_code, null, function(iTotalPrice) {
29546        var sTotalOriginPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
29547        var iTotalOriginPrice = iTotalPrice;
29548
29549        var sItemCode = EC$('.option_box_price').attr('item_code');
29550        sItemCode = (typeof(sItemCode) === 'undefined') ? item_code : sItemCode;
29551        iVatSubTotalPrice = TotalAddSale.getVatSubTotalPrice(sItemCode);
29552
29553        if (iVatSubTotalPrice != iTotalPrice && iVatSubTotalPrice != 0 && iTotalPrice != 0) {
29554            iTotalPrice = iVatSubTotalPrice;
29555        }
29556
29557        var sTotalPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
29558        var sTotalSalePrice = sTotalPrice;
29559        iTotalAddSalePrice = TotalAddSale.getTotalAddSalePrice();
29560        if (typeof(iTotalAddSalePrice) !== 'undefined' && iTotalAddSalePrice != 0) {
29561            iTotalSalePrice = iTotalPrice - parseFloat(iTotalAddSalePrice, 
2956110);
29562            sTotalSalePrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalSalePrice);
29563        } else {
29564            iTotalSalePrice = iTotalPrice;
29565        }
29566
29567        if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
29568            if (CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING.sCurrentCompositionCode === null) {
29569                return true;
29570            }
29571        }
29572        //옵션이 없는 상품이고 추가구성상품 추가시 수량처리 및 상품금액 처리
29573        var iAddQuantity = 0;
29574        if (EC$('.add_product_option_box_price').length > 0) {
29575            EC$('.quantity_opt').each(function() {
29576                iAddQuantity += parseFloat(EC$(this).val());
29577            });
29578
29579            sTotalSalePrice = getAddProductExistTotalSalePrice(iTotalSalePrice);
29580        }
29581        var iTotalQuantity = iQuantity + iAddQuantity;
29582
29583        var sQuantityString = '('+sprintf(__('%s개'), iTotalQuantity) + ')';
29584        // ECHOSTING-58174
29585        if (sIsDisplayNonmemberPrice == 'T') {
29586            sTotalOriginPrice = sNonmemberPrice;
29587            sTotalPrice = sNonmemberPrice;
29588            sTotalSalePrice = sNonmemberPrice;
29589        }
29590
29591        if (EC_MOBILE === true || EC_MOBILE_DEVICE === true || (typeof(isOrderForm) !== 'undefined' && isOrderForm === 'T')) {
29592            EC$(oSingleSelection.getTotalPriceSelector()).html('<strong class="price">'+sTotalSalePrice+' '+sQuantityString+'</strong>');
29593            EC$('#quantity').html('<input type="hidden" name="option_box_price" class="option_box_price" value="'+iTotalOriginPrice+'" item_code="'+item_code+'">');
29594        } else {
29595            EC$('#totalProducts .total').html('<strong><em>' + sTotalSalePrice + '</em></strong> ' + sQuantityString + '</span>');
29596
29597            //품목 할인가 보여주는 설정일 경우 할인가 노출
29598            var sDisplayPrice = sTotalOriginPrice;
29599            if (TotalAddSale.getIsUseSalePrice() === true) {
29600                //1+N상품은 할인가 보여주지 않음
29601                sDisplayPrice = (TotalAddSale.getIsBundleProduct() === true) ? '' : sTotalSalePrice;
29602                sDisplayPrice = '<span class="ec-front-product-item-price" code="' + item_code + '" product-no="' + iProductNo + '">' + sDisplayPrice + '</span>';
29603            }
29604
29605            EC$('#totalProducts').find('.quantity_price').addClass('notranslate').html(sDisplayPrice + '<input type="hidden" name="option_box_price" class="option_box_price" value="'+iTotalOriginPrice+'" item_code="'+item_code+'">');
29606            if (typeof(mileage_val) !== 'undefined' && TotalAddSale.checkVaildMileageValue(mileage_val) === true) {
29607                var mileage_price = TotalAddSale.getMileageGenerateCalc(item_code, iQuantity);
29608
29609                if (sIsDisplayNonmemberPrice == 'T') {
29610                    EC$('#totalProducts').find('.mileage_price').html(sNonmemberPrice);
29611                } else {
29612                    EC$('#totalProducts').find('.mileage_price').html(CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(mileage_price));
29613                }
29614            } else {
29615                EC$('#totalProducts').find('.mileage').hide();
29616            }
29617        }
29618
29619        if (typeof(iTotalAddSalePrice) !== 'undefined' && iTotalAddSalePrice != 0) {
29620            setTotalPriceRef(iTotalSalePrice, sQuantityString);
29621        } else {
29622            setTotalPriceRef(iTotalPrice, sQuantityString);
29623        }
29624
29625        if ((EC_MOBILE === true || EC_MOBILE_DEVICE === true) && EC$('.quantity_price').length > 0) {
29626            EC$('.quantity_price').html(sTotalSalePrice);
29627        }
29628
29629        // 총 주문금액/수량 처리
29630        setTotalData();
29631        // 적립금 / 품목금액 갱신
29632        TotalAddSale.updatePrice();
29633    });
29634}
29635
29636/**
29637 * 금액설정(옵션이 있는 경우)
29638 * 복합/조합 - 단독/일체 구분없이 item_code만으로 처리하도록 변경
29639 */
29640function setPriceHasOptionT(bOption, sOptionId)
29641{
29642    if (typeof(option_stock_data) === 'undefined') {
29643        return;
29644    }
29645
29646    if (sIsDisplayNonmemberPrice === 'T') {
29647        return;
29648    }
29649
29650    if (bOption !== true) {
29651        return;
29652    }
29653
29654    var sSelectElementId = sOptionId;
29655    var temp_product_option_id = product_option_id;
29656
29657    //뉴상품+구스킨 : 옵션추가버튼을 이용해 추가된 옵션 select box id 예외처리
29658    if (sOptionId.split('_')[0] == 'add') {
29659        temp_product_option_id = sOptionId.split('_')[0]+'_'+sOptionId.split('_')[1]+'_'+temp_product_option_id;
29660    }
29661    if (typeof(EC$('#'+sSelectElementId).attr('composition-code')) !== 'undefined') {
29662        temp_product_option_id = temp_product_option_id+'_'+EC$('#'+sOptionId).attr('composition-code');
29663    }
29664
29665    var sSoldoutDisplayText = CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_SOLDOUT.getSoldoutDiplayText(iProductNo);
29666    var aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
29667    // bItemSelected : 모든 셀렉트 박스가 선택됐는지 여부
29668    var bItemSelected, bSoldOut = false;
29669    var sOptionId, sOptionText, sOptionPriceText = '';
29670    var iPrice = 0;
29671
29672    var iBuyUnit = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getBuyUnitQuantity('base');
29673    var iProductMin = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
29674    var aOptionTitle = [];
29675
29676    var iQuantity = (iBuyUnit >= iProductMin ? iBuyUnit : iProductMin);
29677    // 조합구성 & 분리선택형
29678    if (option_type == 'T' && item_listing_type == 'S') {
29679        var aOption = [];
29680        EC$('select[id^="' + temp_product_option_id + '"]').each(function() {
29681            var cVal = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(this);
29682            aOption.push(cVal);
29683
29684            var sTmp = EC$(this).attr('option_title');
29685            aOptionTitle.push({ key: sTmp, value: cVal });
29686        });
29687
29688        // 아직 totalProduct에 Element추가가 안되서 getItemCode를 사용할 수 없다.
29689        sOptionId = ITEM.getOldProductItemCode('[id^="'+temp_product_option_id+'"]');
29690        sOptionValue = aOption.join('/');
29691        sOptionText = aOption.join('#$%');
29692        if (ITEM.isOptionSelected(aOption) === true) {
29693            bItemSelected = true;
29694        }
29695
29696        if (typeof(aStockData[sOptionId]) !== 'undefined' && aStockData[sOptionId].stock_price != 0) {
29697            if (typeof(product_option_price_display) === 'undefined' || product_option_price_display === 'T') {
29698                // 분리선택형은 추가금액을 sOptionText에 포함. sOptionPriceText는 비워둔다(둘 다 채우면 이중 표시).
29699                sOptionText += '(' + getOptionPrice(aStockData[sOptionId].stock_price) + ')';
29700            }
29701        }
29702
29703        var sWmsStockStatus = CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_WMS.getStockStatus(iProductNo, sOptionId);
29704        sOptionText += sWmsStockStatus;
29705
29706        if (bItemSelected === true && sOptionId === false) {
29707            alert(sprintf(__("선택하신 '%s' 옵션은 판매하지 않은 옵션입니다.\n다른 옵션을 선택해 주세요."),sOptionValue));
29708            return false;
29709        }
29710    } else {
29711        var sElementId = sOptionId;
29712        var oSelect = EC$('#'+sElementId);
29713
29714        if (oSelect.attr('is_selected') !== 'T') {
29715            sOptionText = EC$('#' + sOptionId + ' option:selected').text();
29716            sOptionId = EC$('#' + sOptionId + ' option:selected').val();
29717            bItemSelected = true;
29718        } else {
29719            if (isNewProductSkin() === true && NEWPRD_OPTION.isOptionSelectTitleOrDivider(CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(oSelect)) !== true) {
29720                alert(__('PLEASE.DELETE.THE.OPTION', 'SHOP.JS.FRONT.NEW.PRODUCT.INFO'));
29721                NEWPRD_OPTION.resetSelectElement(oSelect);
29722                return false;
29723            }
29724            sOptionId = '*';
29725        }
29726
29727        // 독립선택형 옵션별로 한개씩 선택시
29728        if (oSingleSelection.isItemSelectionTypeM() === true && typeof(is_onlyone) === 'string' && is_onlyone === 'T' && isNewProductSkin() === true) {
29729
29730            if (NEWPRD_OPTION.isOptionSelectTitleOrDivider(oSelect.val()) !== true) {
29731                EC$('#'+sElementId).attr('is_selected','T');
29732            }
29733        }
29734
29735        if (ITEM.isOptionSelected(sOptionId) === false) {
29736            bItemSelected = false;
29737        }
29738    }
29739
29740
29741    if (checkOptionBox(sOptionId) === true) {
29742        NEWPRD_OPTION.resetSelectElement(oSelect);
29743        return false;
29744    }
29745
29746    // get_stock_info
29747    if (aStockData[sOptionId] == undefined) {
29748        iStockNumber = -1;
29749        iOptionPrice = 0;
29750        bStock = false;
29751        sIsDisplay = 'T';
29752        sIsSelling = 'T';
29753        sIsReserveStat = 'N';
29754    } else {
29755        iStockNumber = aStockData[sOptionId].stock_number;
29756        iOptionPrice = aStockData[sOptionId].option_price;
29757        bStock = aStockData[sOptionId].use_stock;
29758        sIsDisplay = aStockData[sOptionId].is_display;
29759        sIsSelling = aStockData[sOptionId].is_selling;
29760        sIsReserveStat = aStockData[sOptionId].is_reserve_stat; //이건 어디서
29761    }
29762
29763    if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isItemCode(sOptionId) === true && typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig[iProductNo] === 'object') {
29764        iOptionPrice = aStockData[sOptionId].option_price - aStockData[sOptionId].stock_price;
29765    }
29766    if (sIsSelling == 'F' || ((iStockNumber < iBuyUnit || iStockNumber <= 0) && (bStock === true || sIsDisplay == 'F'))) {
29767        //뉴상품+구스디 스킨 (옵션추가 버튼나오는 디자인 - 옵션선택시 재고체크)
29768        if (EC$('#totalProducts').length <= 0) {
29769            var aOptionName = new Array();
29770            var aOptionText = new Array();
29771
29772            aOptionName = option_name_mapper.split('#$%');
29773            aOptionText = sOptionText.split('#$%');
29774            for (var i = 0; i < aOptionName.length; i++) {
29775                aOptionText[i] = aOptionName[i]+':'+aOptionText[i];
29776            }
29777            option_text = aOptionText.join('\n');
29778            alert(__('이 상품은 현재 재고가 부족하여 판매가 잠시 중단되고 있습니다.') + '\n\n' + __('제품명') + ' : ' + product_name + '\n\n' + __('재고없는 제품옵션') + ' : \n' + option_text);
29779            CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(EC$('#' + sSelectElementId), '*');
29780        }
29781        bSoldOut = true;
29782        sOptionText = sOptionText.split('#$%').join('/').replace('['+sSoldoutDisplayText+']', '') + ' <span class="soldOut">['+sSoldoutDisplayText+']</span>';
29783    } else {
29784        sOptionText = sOptionText.split('#$%').join('/');
29785    }
29786
29787    if (typeof(EC$('#'+sSelectElementId).attr('composition-code')) !== 'undefined') {
29788        iQuantity = PRODUCTSUBMIT.getQuantity(EC$('.xans-product-funding').find('#quantity_'+EC$('#'+sSelectElementId).attr('composition-code')));
29789    }
29790    //예약주문|당일발송
29791    if (aStockData[sOptionId] !== undefined) {
29792        if (aReserveStockMessage['show_stock_message'] === 'T' && sIsReserveStat !== 'N') {
29793            var sReserveStockMessage = '';
29794            bSoldOut = false; //품절 사용 안함
29795
29796            sReserveStockMessage = aReserveStockMessage[sIsReserveStat];
29797            sReserveStockMessage = sReserveStockMessage.replace(aReserveStockMessage['stock_message_replace_name'], iStockNumber);
29798            sReserveStockMessage = sReserveStockMessage.replace('[:PRODUCT_STOCK:]', iStockNumber);
29799
29800            sOptionText = sOptionText.replace(sReserveStockMessage, '') + ' <span class="soldOut">'+sReserveStockMessage+'</span>';
29801        }
29802    }
29803
29804    if (oSingleSelection.isItemSelectionTypeS() === true) {
29805        iQuantity = PRODUCTSUBMIT.getQuantity();
29806        if (option_type === 'F') {
29807            var iOptionSequence = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSortNum(oSelect);
29808            iQuantity = PRODUCTSUBMIT.getQuantity(EC$('[product-no='+iProductNo+'][option-sequence='+iOptionSequence+']'));
29809        }
29810    }
29811
29812    iPrice = getProductPrice(iQuantity, iOptionPrice, sOptionId, bSoldOut, function(iPrice) {
29813        // 옵션박스 호출
29814        if (bItemSelected === true) {
29815            // 구상품스킨일때는 옵션박스 호출안함
29816            if (isNewProductSkin() === false) {
29817                if (sIsDisplayNonmemberPrice == 'T') {
29818                    EC$('#span_product_price_text').html(sNonmemberPrice);
29819                } else {
29820                    EC$('#span_product_price_text').html(CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iPrice));
29821                }
29822            } else {
29823                setOptionBox(sOptionId, sOptionText, iPrice, bSoldOut, sSelectElementId, sIsReserveStat, iQuantity, aOptionTitle, sSoldoutDisplayText, sOptionPriceText);
29824            }
29825
29826            if (typeof CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET !== 'undefined') {
29827                CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET.bIsLoadedPriceAjax = true;
29828            }
29829        }
29830    });
29831}
29832
29833/**
29834 * 옵션 사용가능 체크
29835 */
29836function checkOptionBox(sOptionId)
29837{
29838    if (oSingleSelection.isItemSelectionTypeS() === true) {
29839        return false;
29840    }
29841    if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
29842        return false;
29843    }
29844
29845    var bSelected = false;
29846    // 이미 선택된 옵션은 아무 처리도 하지 않도록 처리한다.
29847    EC$('.option_box_id').each(function(i) {
29848        if (EC$(this).val() == sOptionId) {
29849            bSelected = true;
29850        }
29851    });
29852
29853    EC$('.soldout_option_box_id').each(function(i) {
29854        if (EC$(this).val() == sOptionId) {
29855            bSelected = true;
29856        }
29857    });
29858    if (bSelected === true) {
29859        alert(__('PLEASE.DELETE.THE.OPTION', 'SHOP.JS.FRONT.NEW.PRODUCT.INFO'));
29860    }
29861    return bSelected;
29862}
29863
29864/*
29865 * 옵션선택 박스 설정
29866 * @todo totalproduct id를 컨트롤러로 밀어야함
29867 */
29868function setOptionBox(sItemCode, sOptionText, iPrice, bSoldOut, sSelectElementId, sIsReserveStat, iManualQuantity, aOptionTitle, sSoldoutDisplayText, sOptionPriceText)
29869{
29870    EC_SHOP_FRONT_DEBUG.log("fn - setOptionBox");
29871
29872    if (CAFE24.checkChannelUI() === true) {
29873        setOptionBoxDiv(sItemCode, sOptionText, iPrice, bSoldOut, sSelectElementId, sIsReserveStat, iManualQuantity, aOptionTitle, sSoldoutDisplayText, sOptionPriceText);
29874        return;
29875    }
29876
29877    const oBoxBuilder = CAFE24.SHOP_FRONT_NEW_OPTION_BOX;
29878
29879    // Pipeline stages 1-3
29880    const optionBoxState = oBoxBuilder.validateAndPrepare({
29881        sItemCode, sOptionText, iPrice, bSoldOut, sSelectElementId,
29882        sIsReserveStat, iManualQuantity, aOptionTitle, sSoldoutDisplayText, sOptionPriceText
29883    });
29884    if (optionBoxState === null) return false;
29885    oBoxBuilder.computePricing(optionBoxState);
29886    oBoxBuilder.computeMeta(optionBoxState);
29887
29888    optionBoxState.sTableRow = `<tr class="option_product ${optionBoxState.sDisplayOption}" data-option-index="${optionBoxState.iIndex}" target-key="${optionBoxState.iTargetKey}">`;
29889
29890    // REFACTOR_BRANCH_START
29891    // Pipeline stage 4: device-specific row builder (Strategy 패턴)
29892    optionBoxState.sTableRow = optionBoxState.bIsMobile
29893        ? oBoxBuilder.rowBuilders.mobile(optionBoxState)
29894        : oBoxBuilder.rowBuilders.pc(optionBoxState);
29895    // REFACTOR_BRANCH_END
29896
29897    // Pipeline stages 5-6
29898    oBoxBuilder.appendToTable(optionBoxState);
29899    oBoxBuilder.finalizeUpdates(optionBoxState);
29900}
29901
29902// REFACTOR_HELPERS_BEGIN
29903/**
29904 * 옵션 박스 빌더 — setOptionBox 모바일/PC 분기 공통 로직 모듈.
29905 * 옵션 텍스트는 buildOptionTextLine이 isMobile/isReservation 두 플래그로 4 케이스를 통합 처리한다.
29906 */
29907CAFE24.SHOP_FRONT_NEW_OPTION_BOX = {
29908
29909    /**
29910     * NaverChk_Button 숨김 처리 (품절 분기 공통)
29911     */
29912    hideNaverChkButton() {
29913        try {
29914            if (EC$('#NaverChk_Button').length > 0 && EC$('#NaverChk_Button').children().length > 0) {
29915                EC$('#NaverChk_Button').css('display', 'none');
29916            }
29917        } catch (e) {}
29918    },
29919
29920    /**
29921     * 품절 옵션 박스 hidden input
29922     */
29923    buildSoldoutHiddenInput(sOptionBoxId, sItemCode) {
29924        return `<input type="hidden" class="soldout_option_box_id" id="${sOptionBoxId}_id" value="${sItemCode}">`;
29925    },
29926
29927    /**
29928     * 옵션 박스 가격 hidden input (정상 분기 공통)
29929     */
29930    buildOptionPriceHiddenInput(iPrice, iProductNo, sItemCode) {
29931        return `<input type="hidden" class="option_box_price" value="${iPrice}" product-no="${iProductNo}" item_code="${sItemCode}">`;
29932    },
29933
29934    /**
29935     * 마일리지 배지 (정상 분기 공통)
29936     */
29937    buildMileageBadge(sOptionBoxId, sItemCode, sMileageIcon, sMileageAlt, sMileageVal) {
29938        return `<span class="mileage">(<img src="${sMileageIcon}" alt="${sMileageAlt}" /> <span id="${sOptionBoxId}_mileage" class="mileage_price" code="${sItemCode}">${sMileageVal}</span>)</span>`;
29939    },
29940
29941    /**
29942     * 삭제 아이콘 — mobile/pc 4개 cell에서 동일 마크업으로 공유 (sold-out/sold-in 양쪽).
29943     * 외부 마크업(`<a href="#none">` 또는 `<a href="#none" class="delete">`, `<td>` 래핑 여부)은 호출 측 책임.
29944     */
29945    buildDeleteIcon(sOptionBoxId) {
29946        return `<img src="//img.echosting.cafe24.com/design/skin/default/product/btn_price_delete.gif" alt="삭제" id="${sOptionBoxId}_del" class="option_box_del" />`;
29947    },
29948
29949    /**
29950     * 마일리지 섹션 — bShowMileage가 true일 때만 mileage badge 마크업 반환, 아니면 빈 문자열.
29951     * mobile sold-in / pc 분기 양쪽에서 동일한 conditional 마크업을 캡슐화하는 wrapper.
29952     */
29953    buildMileageSection(optionBoxState) {
29954        if (!optionBoxState.bShowMileage) return '';
29955        return this.buildMileageBadge(optionBoxState.sOptionBoxId, optionBoxState.sItemCode, optionBoxState.sMileageIcon, optionBoxState.sMileageAlt, optionBoxState.sMileageVal);
29956    },
29957
29958    /**
29959     * 옵션 박스 hidden input — 속성 순서/공백 보존 필수.
29960     * 사이 공백: data-item-add-option↔reserved=0칸, reserved↔option-id=2칸, option-id↔option-index=2칸.
29961     * sIsReserveStat: 예약주문 상태값, 내부에서 data-item-reserved 속성 마크업으로 변환.
29962     */
29963    buildOptionBoxHiddenInput(sOptionBoxId, sItemCode, aAddOption, sIsReserveStat, sOptionId, iIndex) {
29964        // escape() 인코딩 포맷 호환 유지 (encodeURIComponent와 결과가 다름)
29965        const sEscapedAddOption = escape(aAddOption.join(NEWPRD_OPTION.DELIMITER_SEMICOLON)); // NOSONAR
29966        const sInputHiddenReserved = `data-item-reserved="${sIsReserveStat}" `;
29967        return `<input type="hidden" class="option_box_id" id="${sOptionBoxId}_id" value="${sItemCode}" name="item_code[]" data-item-add-option="${sEscapedAddOption}"${sInputHiddenReserved} data-option-id="${sOptionId}"  data-option-index="${iIndex}">`;
29968    },
29969
29970    /**
29971     * 옵션 텍스트 라인. 모바일/PC × 예약/비예약 4 케이스를 isMobile/isReservation 플래그로 통합.
29972     */
29973    buildOptionTextLine(sProductName, sAddOptionTitle, sOptionLabel, sOptionPriceText, isReservation, isMobile) {
29974        const sCombinedLabel = isReservation ? `${sOptionLabel}${sOptionPriceText}` : sOptionLabel;
29975        const sNamePart = isMobile ? `<strong>${sProductName}</strong>` : sProductName;
29976        const sSeparator = isReservation ? '&nbsp;' : ' - ';
29977        return `<p class="product">${sNamePart}<br />${sSeparator}<span>${sAddOptionTitle}${sCombinedLabel}</span> [#RESTOCK_BUTTON] </p>`;
29978    },
29979
29980    /**
29981     * 추가옵션 테이블 wrapper 헤더 (sHtml 분기). 모바일/PC 차이: colgroup width, 헤더 라벨, 모바일 caption.
29982     */
29983    buildAddOptionTableHeader(isMobile) {
29984        if (isMobile) {
29985            return '<td colspan="3">' +
29986                '<table summary="" border="1">' +
29987                '<caption>상품 목록</caption>' +
29988                '<colgroup>' +
29989                '<col style="width:auto;">' +
29990                '<col style="width:100px;">' +
29991                '<col style="width:35px;">' +
29992                '</colgroup>' +
29993                '<thead>' +
29994                '<tr>' +
29995                `<th scope="col">${__('상품 정보')}</th>` +
29996                `<th scope="col">${__('가격')}</th>` +
29997                `<th scope="col">${__('삭제')}</th>` +
29998                '</tr>' +
29999                '</thead>' +
30000                '<tbody><tr>';
30001        }
30002        return '<td colspan="3">' +
30003            '<table>' +
30004            '<colgroup>' +
30005            '<col style="width:284px;">' +
30006            '<col style="width:80px;">' +
30007            '<col style="width:110px;">' +
30008            '</colgroup>' +
30009            '<thead>' +
30010            '<tr>' +
30011            `<th scope="col">${__('상품명')}</th>` +
30012            `<th scope="col">${__('상품수')}</th>` +
30013            `<th scope="col">${__('가격')}</th>` +
30014            '</tr>' +
30015            '</thead>' +
30016            '<tbody><tr>';
30017    },
30018
30019    /**
30020     * 추가옵션 테이블 wrapper 푸터 (sHtml 분기). inner tr 닫음 + sHtml + outer wrapper 닫음.
30021     */
30022    buildAddOptionTableFooter(sHtml) {
30023        return `</tr>${sHtml}</tbody></table></td>`;
30024    },
30025
30026    /**
30027     * 추가옵션 테이블 wrapper — sHtml 비어있으면 빈 문자열, 아니면 header 호출.
30028     * mobile/pc rowBuilder의 `if (sHtml) sTableRow += ...` 분기 제거용.
30029     */
30030    buildOptionalHeader(sHtml, isMobile) {
30031        return sHtml ? this.buildAddOptionTableHeader(isMobile) : '';
30032    },
30033
30034    /**
30035     * 추가옵션 테이블 wrapper — sHtml 비어있으면 빈 문자열, 아니면 footer 호출.
30036     */
30037    buildOptionalFooter(sHtml) {
30038        return sHtml ? this.buildAddOptionTableFooter(sHtml) : '';
30039    },
30040
30041    // ============================================================
30042    // Cell builders — rowBuilders.{mobile|pc}의 sold-out/sold-in 분기 본문을
30043    // 별도 메서드로 분리하여 rowBuilders 진입점의 인지적 복잡도를 낮춤.
30044    // 각 메서드는 optionBoxState를 받아 해당 분기의 셀 마크업 (sTableRow 일부) 문자열만 반환.
30045    // 부수효과(hideNaverChkButton)는 sold-out cells에서 호출, iframe append는 호출 측 mobile에서 인라인.
30046    // ============================================================
30047
30048    /**
30049     * 모바일 sold-out cells — option text td + quantity readonly + price + delete (3 cells).
30050     * 부수효과: hideNaverChkButton 호출.
30051     */
30052    buildMobileSoldOutCells(optionBoxState) {
30053        this.hideNaverChkButton();
30054        const { sOptionBoxId, sItemCode, sOptionText, sStrPrice } = optionBoxState;
30055        let s = '<td>';
30056        s += this.buildSoldoutHiddenInput(sOptionBoxId, sItemCode) + sOptionText;
30057        s += '<p><input type="number" readonly value="0"/> ';
30058        s += '<a href="#none" class="up"><img width="30" height="27" src="//img.echosting.cafe24.com/mobileWeb/common/btn_quantity_up.png"/></a> &nbsp;';
30059        s += '<a href="#none" class="down"><img width="30" height="27" src="//img.echosting.cafe24.com/mobileWeb/common/btn_quantity_down.png"/></a></span></p></td>';
30060        s += `<td class="right"><strong class="price">${sStrPrice}</strong></td>`;
30061        s += `<td class="center"><a href="#none">${this.buildDeleteIcon(sOptionBoxId)}</a></td>`;
30062        return s;
30063    },
30064
30065    /**
30066     * 모바일 sold-in cells — option text + quantity (id/value/data-target) + price (mileage 포함) + delete (3 cells).
30067     * iProductNo 글로벌 사용.
30068     */
30069    buildMobileSoldInCells(optionBoxState) {
30070        const {
30071            sOptionBoxId, sItemCode, aAddOption, sIsReserveStat, sOptionId, iIndex,
30072            sOptionText, sReadonly, iQuantity, iPrice, sStrPrice
30073        } = optionBoxState;
30074        let s = '<td>';
30075        s += this.buildOptionBoxHiddenInput(sOptionBoxId, sItemCode, aAddOption, sIsReserveStat, sOptionId, iIndex) + sOptionText;
30076        s += `<p><input type="number" id="${sOptionBoxId}_quantity" name="quantity_opt[]" autocomplete="off" class="quantity_opt eProductQuantityClass" ${sReadonly} value="${iQuantity}" product-no="${iProductNo}"/> `;
30077        s += `<a href="#none" class="up eProductQuantityUpClass" data-target="${sOptionBoxId}_up"><img width="30" height="27" src="//img.echosting.cafe24.com/mobileWeb/common/btn_quantity_up.png" id="${sOptionBoxId}_up" class="option_box_up" alt="up" /></a> &nbsp;`;
30078        s += `<a href="#none" class="down eProductQuantityDownClass" data-target="${sOptionBoxId}_down"><img width="30" height="27" src="//img.echosting.cafe24.com/mobileWeb/common/btn_quantity_down.png" id="${sOptionBoxId}_down" class="option_box_down" alt="down" /></a></p></td>`;
30079        s += `<td class="right"><strong id="${sOptionBoxId}_price" class="price">${this.buildOptionPriceHiddenInput(iPrice, iProductNo, sItemCode)}<span class="ec-front-product-item-price" code="${sItemCode}" product-no="${iProductNo}">${sStrPrice}</span></strong>`;
30080        s += this.buildMileageSection(optionBoxState);
30081        s += '</td>';
30082        s += `<td class="center"><a href="#none" class="delete">${this.buildDeleteIcon(sOptionBoxId)}</a></td>`;
30083        return s;
30084    },
30085
30086    /**
30087     * PC sold-out cells — option text td + quantity wrapper td + price td-open.
30088     * 부수효과: hideNaverChkButton 호출.
30089     * optionBoxState.sNoTranslateClass 사용 (rowBuilder.pc에서 사전 설정).
30090     * 비대칭: price `<td>` 닫기는 호출 측 후단(`</td></tr>`)에서 수행.
30091     */
30092    buildPcSoldOutCells(optionBoxState) {
30093        this.hideNaverChkButton();
30094        const { sOptionBoxId, sItemCode, sOptionText, sReadonly, sStrPrice, sNoTranslateClass } = optionBoxState;
30095        let s = `<td>${this.buildSoldoutHiddenInput(sOptionBoxId, sItemCode)}${sOptionText}</td>`;
30096        s += '<td><span class="quantity" style="width:65px;">';
30097        s += `<input type="text" ${sReadonly} value="0"/>`;
30098        s += '<a href="#none" class="up"><img src="//img.echosting.cafe24.com/design/skin/default/product/btn_count_up.gif" alt="수량증가" /></a>';
30099        s += '<a href="#none" class="down"><img src="//img.echosting.cafe24.com/design/skin/default/product/btn_count_down.gif" alt="수량감소" /></a>';
30100        s += '</span>';
30101        s += `<a href="#none" class="delete">${this.buildDeleteIcon(sOptionBoxId)}</a></td>`;
30102        s += `<td class="right"><span id="${sOptionBoxId}_price"><span class="${sNoTranslateClass}">${sStrPrice}</span></span>`;
30103        return s;
30104    },
30105
30106    /**
30107     * PC sold-in cells — option text td + quantity wrapper td + price td-open with hidden input.
30108     * iProductNo 글로벌 사용. optionBoxState.sNoTranslateClass 사용.
30109     * 수량 up 버튼 마크업의 이중 따옴표(`class="up eProductQuantityUpClass""`)는 기존 출력 호환을 위해 그대로 둔다.
30110     * 비대칭: price `<td>` 닫기는 호출 측 후단(`</td></tr>`)에서 수행.
30111     */
30112    buildPcSoldInCells(optionBoxState) {
30113        const {
30114            sOptionBoxId, sItemCode, aAddOption, sIsReserveStat, sOptionId, iIndex,
30115            sOptionText, sReadonly, iQuantity, iPrice, sStrPrice, sNoTranslateClass
30116        } = optionBoxState;
30117        let s = `<td>${this.buildOptionBoxHiddenInput(sOptionBoxId, sItemCode, aAddOption, sIsReserveStat, sOptionId, iIndex)}${sOptionText}</td>`;
30118        s += '<td>
30118<span class="quantity" style="width:65px;">';
30119        s += `<input type="text" id="${sOptionBoxId}_quantity" name="quantity_opt[]" class="quantity_opt eProductQuantityClass" ${sReadonly} value="${iQuantity}" product-no="${iProductNo}"/>`;
30120        s += `<a href="#none" class="up eProductQuantityUpClass"" data-target="${sOptionBoxId}_up" ><img src="//img.echosting.cafe24.com/design/skin/default/product/btn_count_up.gif" id="${sOptionBoxId}_up" class="option_box_up" alt="수량증가" /></a>`;
30121        s += `<a href="#none" class="down eProductQuantityDownClass" data-target="${sOptionBoxId}_down"><img src="//img.echosting.cafe24.com/design/skin/default/product/btn_count_down.gif" id="${sOptionBoxId}_down" class="option_box_down" alt="수량감소" /></a>`;
30122        s += '</span>';
30123        s += `<a href="#none" class="delete">${this.buildDeleteIcon(sOptionBoxId)}</a></td>`;
30124        s += `<td class="right"><span id="${sOptionBoxId}_price">`;
30125        s += this.buildOptionPriceHiddenInput(iPrice, iProductNo, sItemCode);
30126        s += `<span class="ec-front-product-item-price ${sNoTranslateClass}" code="${sItemCode}" product-no="${iProductNo}">${sStrPrice}</span></span>`;
30127        return s;
30128    },
30129
30130    // ============================================================
30131    // Pipeline stages — setOptionBox 책임 영역을 단일 책임 메서드로 분리.
30132    // 디자인 패턴: Pipeline (단계별 sequence) + Object as Context (DTO)
30133    // 각 stage는 optionBoxState 객체에 결과를 누적하여 다음 stage로 전달.
30134    // ============================================================
30135
30136    /**
30137     * Pipeline stage 1: 입력 검증 + 사전 준비
30138     * - bIsAsyncOptionBox 결정 (parent iframe, option_type='F')
30139     * - checkAddOption / checkOptionBox 검증
30140     * - sReadonly, iQuantity, sStrPrice 결정
30141     *
30142     * @param {Object} oArgs setOptionBox 진입 인자를 묶은 DTO (sItemCode, sOptionText, iPrice,
30143     *   bSoldOut, sSelectElementId, sIsReserveStat, iManualQuantity, aOptionTitle,
30144     *   sSoldoutDisplayText, sOptionPriceText)
30145     * @returns {Object|null} optionBoxState (검증 통과) 또는 null (검증 실패)
30146     */
30147    validateAndPrepare(oArgs) {
30148        const { sItemCode, iPrice, sSelectElementId, iManualQuantity } = oArgs;
30149        const oSelect = EC$(`#${sSelectElementId}`);
30150        const bIsAsyncOptionBox = this.determineAsyncOptionBox(sSelectElementId, sItemCode);
30151
30152        // 필수 추가옵션 작성여부 검증
30153        if (checkAddOption() !== true) {
30154            delete oProductList[sItemCode];
30155            NEWPRD_ADD_OPTION.resetSelectElement(oSelect);
30156            // 독립선택형 옵션별로 한개씩 선택시
30157            if (typeof(is_onlyone) === 'string' && is_onlyone === 'T' && isNewProductSkin() === true) {
30158                oSelect.removeAttr('is_selected');
30159            }
30160            return null;
30161        }
30162
30163        if (checkOptionBox(sItemCode) === true) {
30164            NEWPRD_OPTION.resetSelectElement(oSelect);
30165            return null;
30166        }
30167
30168        const { sReadonly, iBuyUnit, iProductMin, iQuantity } = this.computeInitialQuantity(iManualQuantity);
30169        const sStrPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iPrice);
30170
30171        return {
30172            // 진입 인자 (oArgs spread)
30173            ...oArgs,
30174            // Stage 1 ê²°ê³¼
30175            sReadonly,
30176            oSelect,
30177            bIsAsyncOptionBox,
30178            iBuyUnit,
30179            iProductMin,
30180            sStrPrice,
30181            iQuantity
30182        };
30183    },
30184
30185    /**
30186     * Pipeline stage 1 helper — bIsAsyncOptionBox 결정.
30187     * 모바일 옵션선택레이어 / 미리보기 cors 예외 처리 + option_type='F' 분기.
30188     * 부수효과: parent iframe의 none_create_option_box 속성 제거 (cors 예ì
30188™¸ 케이스).
30189     */
30190    determineAsyncOptionBox(sSelectElementId, sItemCode) {
30191        let bIsAsyncOptionBox = true;
30192        try {
30193            if (parent && parent !== globalThis && parent.EC$(`#${sSelectElementId}`).attr('none_create_option_box') === 'true') {
30194                bIsAsyncOptionBox = false;
30195                parent.EC$(`#${sSelectElementId}`).removeAttr('none_create_option_box');
30196            }
30197        } catch (e) {}
30198
30199        if (option_type === 'F' && parent.EC$(`input.option_box_id[value="${sItemCode}"]`).length > 0) {
30200            bIsAsyncOptionBox = false;
30201        }
30202        return bIsAsyncOptionBox;
30203    },
30204
30205    /**
30206     * Pipeline stage 1 helper — 초기 수량/readonly 결정.
30207     * iBuyUnit/iProductMin 결정 후 buy_unit > 1 → readonly, iManualQuantity 우선 적용.
30208     * @returns {{ sReadonly: string, iBuyUnit: number, iProductMin: number, iQuantity: number }}
30209     */
30210    computeInitialQuantity(iManualQuantity) {
30211        const iBuyUnit = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getBuyUnitQuantity('base');
30212        const iProductMin = CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID.getProductMinQuantity();
30213        const sReadonly = Number.parseInt(buy_unit, 10) > 1 ? 'readonly' : '';
30214        const iQuantity = iManualQuantity === undefined
30215            ? Math.max(iBuyUnit, iProductMin)
30216            : iManualQuantity;
30217        return { sReadonly, iBuyUnit, iProductMin, iQuantity };
30218    },
30219
30220    /**
30221     * Pipeline stage 2: 가격/마일리지 계산
30222     * - aStockData 파싱
30223     * - Olnk linkage type x reservation 분기 마일리지 계산
30224     * - 비회원가 노출 처리
30225     */
30226    computePricing(optionBoxState) {
30227        optionBoxState.iMileageVal = 0;
30228        optionBoxState.sMileageIcon = typeof mileage_icon === 'undefined' ? '//img.echosting.cafe24.com/design/common/icon_sett04.gif' : mileage_icon;
30229        optionBoxState.sMileageAlt = typeof mileage_icon_alt === 'undefined' ? '' : mileage_icon_alt;
30230
30231        if (typeof option_stock_data !== 'undefined') {
30232            optionBoxState.aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
30233        }
30234
30235        if (typeof mileage_val !== 'undefined') {
30236            optionBoxState.iStockPrice = this.computeStockPriceFromOptions(optionBoxState);
30237            optionBoxState.iMileageVal = TotalAddSale.getMileageGenerateCalc(optionBoxState.sItemCode, optionBoxState.iQuantity);
30238        }
30239        optionBoxState.sMileageVal = CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(optionBoxState.iMileageVal);
30240
30241        // 비회원가 노출 시 가격/마일리지 덮어쓰기
30242        if (sIsDisplayNonmemberPrice == 'T') {
30243            optionBoxState.sStrPrice = sNonmemberPrice;
30244            optionBoxState.sMileageVal = sNonmemberPrice;
30245        }
30246    },
30247
30248    /**
30249     * Pipeline stage 2 helper — Olnk linkage type 분기 + reservation 분기 + non-linkage 분기.
30250     * 부수효과: linkage type + reservation 케이스에서 optionBoxState.sLinkageOptionId 설정.
30251     * @returns {number} 계산된 iStockPrice (0이 기본)
30252     */
30253    computeStockPriceFromOptions(optionBoxState) {
30254        if (Olnk.isLinkageType(option_type) === true) {
30255            const aOptionTmp = optionBoxState.sItemCode.split('||');
30256            if (this.isReservationLinkage()) {
30257                return this.computeReservationLinkageStockPrice(optionBoxState, aOptionTmp);
30258            }
30259            return this.computeOptionLinkageStockPrice(optionBoxState, aOptionTmp);
30260        }
30261        return optionBoxState.aStockData[optionBoxState.sItemCode].stock_price !== undefined
30262            ? optionBoxState.aStockData[optionBoxState.sItemCode].stock_price
30263            : 0;
30264    },
30265
30266    /**
30267     * Pipeline stage 2 helper — reservation 몰 + linkage 옵션 케이스 조건 판정.
30268     * @returns {boolean}
30269     */
30270    isReservationLinkage() {
30271        return typeof CAFE24.FRONT_JS_CONFIG_SHOP === 'object'
30272            && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('product_service_type')
30273            && CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation';
30274    },
30275
30276    /**
30277     * Pipeline stage 2 helper — reservation + linkage type 분기 stock price 계산.
30278     * 부수효과: optionBoxState.sLinkageOptionId 설정.
30279     */
30280    computeReservationLinkageStockPrice(optionBoxState, aOptionTmp) {
30281        const aValueNum = this.collectValidOptionIdHeads(aOptionTmp);
30282        optionBoxState.sLinkageOptionId = aValueNum.join('-');
30283        return optionBoxState.aStockData.hasOwnProperty(optionBoxState.sLinkageOptionId)
30284            ? optionBoxState.aStockData[optionBoxState.sLinkageOptionId].stock_price
30285            : 0;
30286    },
30287
30288    /**
30289     * Pipeline stage 2 helper — linkage type 일반 분기 stock price 계산.
30290     */
30291    computeOptionLinkageStockPrice(optionBoxState, aOptionTmp) {
30292        const aValueNum = this.collectValidOptionIdHeads(aOptionTmp);
30293        if (aValueNum.length === 0) {
30294            return 0;
30295        }
30296        const sLastValidId = aValueNum.at(-1);
30297        return Number.parseFloat(optionBoxState.aStockData[sLastValidId].option_price);
30298    },
30299
30300    /**
30301     * Pipeline stage 2 helper — itemCode 분해 후 옵션 ID head 중 유효한 것만 수집.
30302     * head는 `*+` (별표만으로 구성)이면 invalid로 간주.
30303     * @returns {string[]}
30304     */
30305    collectValidOptionIdHeads(aOptionTmp) {
30306        const aValueNum = [];
30307        for (const sOptionEntry of aOptionTmp) {
30308            if (sOptionEntry === '') {
30309                continue;
30310            }
30311            const aOptionIdTmp = sOptionEntry.split('_');
30312            if (/^\*+$/.test(aOptionIdTmp[0]) === false) {
30313                aValueNum.push(aOptionIdTmp[0]);
30314            }
30315        }
30316        return aValueNum;
30317    },
30318
30319    /**
30320     * Pipeline stage 3: 메타데이터 결정 (iIndex, sOptionBoxId, sHtml, ...)
30321     */
30322    computeMeta(optionBoxState) {
30323        let sProductName = product_name;
30324        if (sProductName != null) {
30325            sProductName = product_name.replaceAll(String.raw`\"`, '"');
30326        }
30327        optionBoxState.sProductName = sProductName;
30328
30329        optionBoxState.aAddOption = NEWPRD_ADD_OPTION.getCurrentAddOption();
30330
30331        optionBoxState.iIndex = 1;
30332        if (Number.parseInt(EC$('#totalProducts > table > tbody').find('tr.option_product').length, 10) > 0) {
30333            optionBoxState.iIndex = Number.parseInt(EC$('#totalProducts > table > tbody').find('tr.option_product').last().data('option-index'), 10) + 1;
30334        }
30335
30336        optionBoxState.iTargetKey = iProductNo;
30337        if (option_type === 'F') {
30338            optionBoxState.iTargetKey = `${iProductNo}|${CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSortNum(optionBoxState.oSelect)}`;
30339        }
30340
30341        optionBoxState.sDisplayOption = '';
30342        // 옵션선택시 바로 장바구니 담기 상태라면 hide처리
30343        if (CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET !== undefined && CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_DIRECT_BASKET.isAvailableDirectBasket(optionBoxState.oSelect) === true) {
30344            optionBoxState.sDisplayOption = 'displaynone';
30345        }
30346
30347        optionBoxState.sOptionBoxId = `option_box${optionBoxState.iIndex}`;
30348        const oStockItem = optionBoxState.aStockData[optionBoxState.sItemCode];
30349        optionBoxState.sOptionId = (oStockItem !== undefined && oStockItem.option_id !== undefined) ? oStockItem.option_id : '';
30350
30351        // 품목 구분을 위한 코드
30352        optionBoxState._sItemCode = NEWPRD_ADD_OPTION.getPerItemCode(optionBoxState.iIndex, optionBoxState.sItemCode);
30353        optionBoxState.sHtml = NEWPRD_ADD_OPTION.getPerAddOptionTemplate(optionBoxState._sItemCode);
30354
30355        optionBoxState.sAddOptionTitle = '';
30356        if (NEWPRD_ADD_OPTION.isUsePerAddOption() === false) {
30357            optionBoxState.sAddOptionTitle = NEWPRD_ADD_OPTION.getCurrentAddOptionTitle(optionBoxState.aAddOption);
30358            optionBoxState.sAddOptionTitle = optionBoxState.sAddOptionTitle.replaceAll('<', '&lt;').replaceAll('>', '&gt;');
30359        }
30360
30361        optionBoxState.bIsReservation = CAFE24.FRONT_JS_CONFIG_SHOP.product_service_type === 'reservation';
30362        optionBoxState.bIsMobile = (EC_MOBILE === true || EC_MOBILE_DEVICE === true);
30363        optionBoxState.bShowMileage = TotalAddSale.checkVaildMileageValue(optionBoxState.iMileageVal) === true && sIsMileageDisplay === 'T';
30364    },
30365
30366    /**
30367     * Pipeline stage 5: tbody append + 펀딩 분기 + FileOptionManager 등록 + G2G 재번역
30368     */
30369    appendToTable(optionBoxState) {
30370        if (0 == EC$('#totalProducts > table > tbody.option_products').length) {
30371            EC$('#totalProducts > table > tbody').last().addClass("option_products").after(EC$('<tbody class="add_products"/>'));
30372        }
30373
30374        if (EC$('.EC-funding-checkbox').length === 0) {
30375            EC$('#totalProducts > table > tbody.option_products').append(optionBoxState.sTableRow);
30376            if (typeof add_option_file_input !== 'undefined') {
30377                // FileOptionManager에서 관리 될 수 있도록 등록
30378                const sId = `file_option_${optionBoxState._sItemCode}`;
30379                if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
30380                    parent.FileOptionManager.put(sId, add_option_file_input.option);
30381                }
30382                FileOptionManager.put(sId, add_option_file_input.option);
30383            }
30384
30385            if (SHOP.isG2G() === true) {
30386                // 옵션 추가 후 재번역 이벤트 발생
30387                document.dispatchEvent(new CustomEvent('jet-retranslate', {
30388                    detail: { element: document.querySelector('#totalProducts') }
30389                }));
30390            }
30391        } else {
30392            if (has_option === 'T') {
30393                const sCompositionCode = CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING.sCurrentCompositionCode;
30394                CAFE24.SHOP_FRONT_PRODUCT_FUNDING.appendSelectedItem(optionBoxState.sItemCode, sCompositionCode);
30395            }
30396        }
30397    },
30398
30399    /**
30400     * Pipeline stage 6: 합계/적립금/품목금액 갱신
30401     */
30402    finalizeUpdates(optionBoxState) {
30403        // 총 주문금액/수량 처리
30404        setTotalData();
30405        // 적립금 / 품목금액 업데이트
30406        TotalAddSale.updatePrice(optionBoxState.sOptionBoxId, optionBoxState.sItemCode);
30407    },
30408
30409    // ============================================================
30410    // 디바이스별 row builder (mobile / pc). 각 builder는 optionBoxState를 받아
30411    // sTableRow 문자열을 반환하며, 모바일은 parent iframe append 부수효과를 포함한다.
30412    // ============================================================
30413
30414    rowBuilders: {
30415
30416        /**
30417         * 모바일 row builder — header/cells/footer 조립 + iframe append 부수효과.
30418         * 인지적 복잡도 감소를 위해 셀 본문은 buildMobileSold{Out|In}Cells로 위임.
30419         * - sOptionText 변환은 immutable 패턴으로 새 optionBoxState 생성하여 sub-method에 전달
30420         * - 부수효과 (iframe append)는 인라인 유지
30421         */
30422        mobile(optionBoxState) {
30423            const oBoxBuilder = CAFE24.SHOP_FRONT_NEW_OPTION_BOX;
30424            const { sItemCode, sProductName, sAddOptionTitle, sOptionPriceText, bIsReservation, bSoldOut, bIsAsyncOptionBox, sSelectElementId, sHtml } = optionBoxState;
30425
30426            const sProcessedOptionText = getReplaceRestockButton(
30427                sItemCode,
30428                oBoxBuilder.buildOptionTextLine(sProductName, sAddOptionTitle, optionBoxState.sOptionText, sOptionPriceText, bIsReservation, true),
30429                bSoldOut
30430            );
30431            const optionBoxStateForCells = { ...optionBoxState, sOptionText: sProcessedOptionText };
30432
30433            let sTableRow = optionBoxState.sTableRow;
30434            sTableRow += oBoxBuilder.buildOptionalHeader(sHtml, true);
30435            sTableRow += bSoldOut === true
30436                ? oBoxBuilder.buildMobileSoldOutCells(optionBoxStateForCells)
30437                : oBoxBuilder.buildMobileSoldInCells(optionBoxStateForCells);
30438            sTableRow += oBoxBuilder.buildOptionalFooter(sHtml);
30439            sTableRow += '</tr>';
30440
30441            // 부수효과: option layer iframe append (인라인 유지, bIsAsyncOptionBox 단일 가드)
30442            if (bIsAsyncOptionBox === true) {
30443                const optionLayer = CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER;
30444                if (optionLayer.isDisplayLayer(true) === true) {
30445                    parent.EC$('#totalProducts > table > tbody').last().append(sTableRow);
30446                }
30447                if (optionLayer.isExistLayer() === true && optionLayer.isDisplayLayer() === false) {
30448                    EC$("#productOptionIframe").contents().find('#totalProducts > table > tbody').last().append(sTableRow);
30449                    parent.EC$("#"+sSelectElementId).removeAttr('none_create_option_box');
30450                }
30451            }
30452
30453            return sTableRow;
30454        },
30455
30456        /**
30457         * PC row builder — header/cells/mileage/footer 조립.
30458         * 인지적 복잡도 감소를 위해 셀 본문은 buildPcSold{Out|In}Cells로 위임.
30459         * - sOptionText 변환과 sNoTranslateClass 결정은 진입점에서 수행 후 새 optionBoxState로 sub-method에 전달
30460         * - <td/tr> 닫음 비대칭: mileage/footer 뒤 `</td></tr>` (의도된 구조)
30461         */
30462        pc(optionBoxState) {
30463            const oBoxBuilder = CAFE24.SHOP_FRONT_NEW_OPTION_BOX;
30464            const { sItemCode, sProductName, sAddOptionTitle, sOptionPriceText, bIsReservation, bSoldOut, sHtml } = optionBoxState;
30465
30466            const sProcessedOptionText = getReplaceRestockButton(
30467                sItemCode,
30468                oBoxBuilder.buildOptionTextLine(sProductName, sAddOptionTitle, optionBoxState.sOptionText, sOptionPriceText, bIsReservation, false),
30469                bSoldOut
30470            );
30471            const sNoTranslateClass = SHOP.isG2G() === true ? 'notranslate' : '';
30472            const optionBoxStateForCells = { ...optionBoxState, sOptionText: sProcessedOptionText, sNoTranslateClass };
30473
30474            let sTableRow = optionBoxState.sTableRow;
30475            sTableRow += oBoxBuilder.buildOptionalHeader(sHtml, false);
30476            sTableRow += bSoldOut === true
30477                ? oBoxBuilder.buildPcSoldOutCells(optionBoxStateForCells)
30478                : oBoxBuilder.buildPcSoldInCells(optionBoxStateForCells);
30479            sTableRow += oBoxBuilder.buildMileageSection(optionBoxStateForCells);
30480            sTableRow += oBoxBuilder.buildOptionalFooter(sHtml);
30481            sTableRow += '</td></tr>';
30482
30483            return sTableRow;
30484        }
30485    }
30486};
30487// REFACTOR_HELPERS_END
30488
30489/**
30490 * 재입고 버튼 반환
30491 * @param sItemCode 품목 코드
30492 * @returns {string}
30493 */
30494function getReplaceRestockButton(sItemCode, sOptionText, bSoldOut)
30495{
30496    var aRestockButton = EC_FRONT_JS_CONFIG_SHOP.aRestockButton;
30497    var sReplaceText = '';
30498    if (typeof aRestockButton !== 'undefined' && typeof sItemCode !== 'undefined' && bSoldOut === true) {
30499        sReplaceText = '<a href="#none"  item_code = "' + sItemCode + '" id="btn_restock" class="btn_restock" onClick="' + aRestockButton.action + '">' + aRestockButton.image + '</a>';
30500    }
30501
30502    return sOptionText.replace(['[#RESTOCK_BUTTON]'], sReplaceText);
30503}
30504
30505/**
30506 * 총 상품금액/수량 적용
30507 */
30508function setTotalData()
30509{
30510    EC_SHOP_FRONT_DEBUG.log("fn - setTotalData");
30511
30512    if (CAFE24.checkChannelUI() === true) {
30513        setTotalDataDiv();
30514        return;
30515    }
30516
30517    // 실제 계산
30518    var iTotalCount = 0;
30519    var iTotalPrice = 0;
30520    var iVatSubTotalPrice = 0;
30521    var aEventQuantity = new Array();
30522    var aEventQuantityCheck = {};
30523    //add_product_option_box_price추가구성상품
30524    var bIsValidBundleObject = typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE === 'object';
30525    var fEventProductPrice = 0;
30526
30527    EC$('.option_box_price, .option_add_box_price, .add_product_option_box_price').each(function(i) {
30528        var iProductNum = (has_option === 'T') ? EC$(this).attr('product-no') : iProductNo;
30529        var sItemCode = EC$(this).attr('item_code');
30530        if (parseInt(iProductNum) === parseInt(iProductNo) && bIsValidBundleObject === true && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNum) === true) {
30531            if (has_option === 'T') {
30532                var iSingleQuantity = parseInt(EC$('.quantity_opt[product-no="'+iProductNum+'"]').eq(i).val(),10);
30533            } else {
30534                var iSingleQuantity = parseInt(EC$('input[name="quantity_opt[]"]').eq(i).val(),10);
30535            }
30536
30537            if (typeof(aEventQuantityCheck[iProductNum]) === 'undefined') {
30538                aEventQuantityCheck[iProductNum] = 0;
30539                aEventQuantity.push({'product_no': iProductNum});
30540            }
30541
30542            aEventQuantityCheck[iProductNum] += iSingleQuantity;
30543        } else if (typeof(EC$(this).attr('composition-code')) !== 'undefined') {
30544            var sCompositionCode = EC$(this).attr('composition-code');
30545            var iQuantity = EC$('#quantity_'+sCompositionCode).val();
30546            iTotalPrice = iTotalPrice + (EC$(this).val() * iQuantity);
30547        } else {
30548            if (typeof EC_FRONT_JS_CONFIG_SHOP.bSoldout === 'undefined') {
30549                iTotalPrice += parseFloat(EC$(this).val());
30550                iVatSubTotalPrice += TotalAddSale.getVatSubTotalPrice(sItemCode);
30551            }
30552        }
30553    });
30554    EC$(aEventQuantity).each(function() {
30555        fEventProductPrice = fEventProductPrice + (product_price * CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.getQuantity(aEventQuantityCheck[this.product_no], this.product_no));
30556    });
30557    iTotalPrice = iTotalPrice + fEventProductPrice;
30558
30559    if (iVatSubTotalPrice != iTotalPrice && iVatSubTotalPrice != 0 && iTotalPrice != 0) {
30560        iTotalPrice = iVatSubTotalPrice;
30561    }
30562    iTotalAddSalePrice = TotalAddSale.getTotalAddSalePrice();
30563    if (typeof(iTotalAddSalePrice) !== 'undefined' && iTotalAddSalePrice != 0) {
30564        iTotalPrice -= parseFloat(iTotalAddSalePrice, 10);
30565    }
30566
30567    iTotalPrice = (iTotalPrice <= 0) ? 0 : iTotalPrice;
30568    var sStrPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
30569
30570    iTotalCount = CAFE24.SHOP_FRONT_PRODUCT_INFO.getTotalQuantity();
30571    var sQuantityString = '('+sprintf(__('%s개'),iTotalCount)+')';
30572
30573    // ECHOSTING-58174
30574    if (sIsDisplayNonmemberPrice == 'T') {
30575        sStrPrice = sNonmemberPrice;
30576    }
30577    var sTotalPriceSelector = oSingleSelection.getTotalPriceSelector();
30578    // 실제 노출
30579    if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
30580        EC$(sTotalPriceSelector).html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
30581
30582        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
30583            parent.EC$(sTotalPriceSelector).html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
30584        }
30585        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
30586            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
30587                EC$("#productOptionIframe").contents().find(sTotalPriceSelector).html('<strong class="price">'+sStrPrice+'</strong> '+sQuantityString);
30588            }
30589        }
30590    } else {
30591        let sNoTranslateClass = '';
30592        if (SHOP.isG2G() === true) {
30593            sNoTranslateClass = 'notranslate';
30594        }
30595        EC$(sTotalPriceSelector).html('<strong><em class="'+sNoTranslateClass+'">'+sStrPrice+'</em></strong> '+sQuantityString+'</span>');
30596    }
30597
30598    setTotalPriceRef(iTotalPrice, sQuantityString);
30599    setProductPriceTaxTypeText(iTotalPrice);
30600    setGlobaleTaxPolicyText();
30601    setActionButtonVisible();
30602    ReferenceCurrencyPrice.init();
30603}
30604
30605
30606/**
30607 * 예약주문, 바로구매 버튼 , 정기 배송 버튼
30608 */
30609var setActionButtonVisible = function ()
30610{
30611    var sActionButtonSelector = '#btnBuy, #actionBuy, #actionBuyClone, #actionBuyCloneFixed';
30612    var sReserveSelector = '#btnReserve, #actionReserve, #actionReserveClone, #actionReserveCloneFixed';
30613    var sActionButtonRegular = '#btnRegularDeliveryCloneFixed, #btnRegularDelivery';
30614
30615    var oOptionBox = EC$('.option_box_id');
30616    var oSoldoutOptionBox = EC$('.soldout_option_box_id');
30617    var bIsReserveStatus = oOptionBox.length === oOptionBox.filter('[data-item-reserved="R"]').length;
30618
30619    if (oOptionBox.length > 0) {
30620        EC$(sActionButtonSelector).show();
30621        EC$(sReserveSelector).hide();
30622    }
30623
30624    // 단품인 경우 재고관련 정보 스크립트
30625    if (typeof single_option_stock_data !== 'undefined') {
30626        var oSingleOptionData = EC$.parseJSON(single_option_stock_data);
30627        bIsReserveStatus = oSingleOptionData.is_reserve_stat === 'R';
30628    }
30629
30630    // 옵션이 있는 상품에 한해서만 옵션박스 체크
30631    if (typeof single_option_stock_data === 'undefined' && (oSoldoutOptionBox.length > 0 || oOptionBox.length < 1)) {
30632        EC$(sActionButtonSelector).show();
30633        EC$(sReserveSelector).hide();
30634        setActionButtonRegular(sActionButtonSelector, sReserveSelector, sActionButtonRegular);
30635        return;
30636    }
30637
30638    if (bIsReserveStatus) {
30639        EC$(sActionButtonSelector).hide();
30640        EC$(sReserveSelector).removeClass("displaynone").show();
30641        EC$(sActionButtonRegular).hide();
30642        return;
30643    }
30644
30645    setActionButtonRegular(sActionButtonSelector, sReserveSelector, sActionButtonRegular);
30646};
30647
30648/**
30649 * 정기 배송 버튼
30650 */
30651var setActionButtonRegular = function (sActionButtonSelector , sReserveSelector, sActionButtonRegular)
30652{
30653    if (EC_FRONT_JS_CONFIG_SHOP.bRegularConfig === true && (EC$('#is_subscriptionT').is(":checked") === true || EC_FRONT_JS_CONFIG_SHOP.bIsUseRegularDelivery === 'T')) {
30654        EC$(sActionButtonSelector).hide();
30655        EC$(sReserveSelector).hide();
30656        EC$(sActionButtonRegular).removeClass("displaynone").show();
30657    } else {
30658        EC$(sActionButtonRegular).hide();
30659    }
30660};
30661
30662/**
30663 * 총 상품금액에 참조화폐 추가
30664 * @param iTotalPrice
30665 * @param sQuantityString
30666 */
30667function setTotalPriceRef(iTotalPrice, sQuantityString)
30668{
30669    var sPrePrice = '';
30670    var sPostPrice = '';
30671    var sTotalPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalPrice);
30672    var sTotalPriceRef = CAFE24.SHOP_PRICE_FORMAT.shopPriceToSubPrice(iTotalPrice);
30673
30674    if (sTotalPriceRef == '') {
30675        return;
30676    }
30677
30678    // ECHOSTING-58174
30679    if (sIsDisplayNonmemberPrice == 'T') {
30680        sTotalPrice = sNonmemberPrice;
30681        sTotalPriceRef = sNonmemberPrice;
30682    }
30683
30684    var sTotalPriceSelector = oSingleSelection.getTotalPriceSelector();
30685    if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
30686        if (currency_disp_type == 'P') {
30687            EC$(sTotalPriceSelector).find('strong').append(' / ' + sTotalPriceRef);
30688        } else {
30689            EC$(sTotalPriceSelector).html('<strong class="price">'+ sTotalPriceRef +' '+sQuantityString + '</strong> / ' + sTotalPrice);
30690        }
30691
30692        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
30693            parent.EC$(sTotalPriceSelector).find('strong').append(' / ' + sTotalPriceRef);
30694        }
30695        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
30696            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
30697                EC$("#productOptionIframe").contents().find(sTotalPriceSelector).find('strong').append(' / ' + sTotalPriceRef);
30698            }
30699        }
30700    } else {
30701        if (currency_disp_type == 'P') {
30702            EC$(sTotalPriceSelector).append(' / ' + sTotalPriceRef);
30703        } else {
30704            EC$(sTotalPriceSelector).html('<strong><em>' + sTotalPriceRef + '</em></strong> ' + sQuantityString + '</span> / ' + sTotalPrice);
30705        }
30706    }
30707}
30708
30709/**
30710 * 부가세 표시 문구 설정 반영
30711 * @param int iTotalPrice 총 상품 금액
30712 */
30713function setProductPriceTaxTypeText(iTotalPrice)
30714{
30715    var oProductTaxTypeText = TotalAddSale.getProductTaxTypeText();
30716    if (typeof(oProductTaxTypeText) === 'undefined') {
30717        return;
30718    }
30719
30720    var iTotalOrderPrice = TotalAddSale.getTotalOrderPrice();
30721    iTotalPrice = CAFE24.SHOP_PRICE.toShopPrice(iTotalPrice);
30722    var iTaxPrice = (oProductTaxTypeText.product_tax_type_per > 0) ? CAFE24.SHOP_PRICE.toShopPrice(iTotalOrderPrice - iTotalPrice) : 0;
30723    if (iTotalPrice == 0) {
30724        return;
30725    }
30726
30727    var iProductPrice = (oProductTaxTypeText.display_prd_vat_separately === 'T') ? iTotalOrderPrice : iTotalPrice;
30728    var iProductVatPrice = iTotalPrice;
30729    // 부가세율 공식
30730    if (oProductTaxTypeText.display_prd_vat_separately === 'F' || oProductTaxTypeText.product_tax_type !== 'A') {
30731        iTaxPrice = (iProductPrice * oProductTaxTypeText.product_tax_type_per) / (100 + oProductTaxTypeText.product_tax_type_per);
30732        var iShopDecimal = (oProductTaxTypeText.shop_decimal_place > 0) ? oProductTaxTypeText.shop_decimal_place : 1;
30733        iTaxPrice = Math.round(iTaxPrice * iShopDecimal) / iShopDecimal;
30734        iProductVatPrice = iProductVatPrice - iTaxPrice;
30735    }
30736
30737    // 부가세가 0원 미만 및 판매가가 0원 이하 이면 부가세 발생 불가
30738    if (iTaxPrice < 0 || iProductPrice <= 0 || iProductVatPrice <= 0) {
30739        return;
30740    }
30741
30742    var sTaxPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTaxPrice);
30743    var sProductPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iProductPrice);
30744    var sProductVatPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iProductVatPrice);
30745
30746    var sProductTypeText = oProductTaxTypeText.product_tax_type_text.replace(/\[:제외금액:\]|\[:VAT_EXCLUDED_PRICE:\]/g, sProductVatPrice);
30747    sProductTypeText = sProductTypeText.replace(/\[:포함금액:\]|\[:VAT_INCLUDED_PRICE:\]/g, sProductPrice);
30748    sProductTypeText = sProductTypeText.replace(/\[:부가세:\]|\[:VAT:\]/g, sTaxPrice);
30749
30750    //Tags
30751    var sTags = 'font-size:' + parseInt(oProductTaxTypeText.product_tax_type_text_font_size, 10) + 'px;';
30752    sTags += 'color:' + oProductTaxTypeText.product_tax_type_text_color + ';';
30753    sTags += oProductTaxTypeText.product_tax_type_text_font_type;
30754
30755    sProductTypeText = ' <span style="' + sTags + '">' + sProductTypeText + '</span>';
30756
30757    if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
30758        EC$('#totalProducts .total').find('strong').append(sProductTypeText);
30759
30760        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
30761            parent.EC$('#totalProducts .total').find('strong').append(sProductTypeText);
30762        }
30763        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
30764            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
30765                EC$("#productOptionIframe").contents().find('#totalProducts .total').find('strong').append(sProductTypeText);
30766            }
30767        }
30768    } else {
30769        EC$('#totalProducts .total').append(sProductTypeText);
30770    }
30771}
30772
30773/**
30774 * Global-e 세금/관세 안내 문구 표시
30775 *
30776 * GE 활성 시 국가/통화 무관 단일 안내 문구를 표시한다.
30777 * 세금/관세 계산 책임이 GE 측에 있으므로 클라이언트에서는 분기하지 않는다.
30778 *
30779 * @see ECHOSTING-601718
30780 */
30781function setGlobaleTaxPolicyText()
30782{
30783    if (!window.GlobalePresentment || window.GlobalePresentment.isEnabled() === false) {
30784        return;
30785    }
30786
30787    var sTaxText = __('GLOBALE.TAX.DUTY.NOTICE', 'SHOP.JS.FRONT.NEW.PRODUCT.INFO');
30788    var sTaxTypeHtml = ' <span class="globale-tax-policy">' + sTaxText + '</span>';
30789    var sTotalPriceSelector = (typeof oSingleSelection === 'object' && oSingleSelection !== null)
30790        ? oSingleSelection.getTotalPriceSelector()
30791        : '#totalProducts .total:visible, #totalPrice .total';
30792
30793    // 모바일·PC 옵션박스 공통: 총상품금액(수량) 문구·하단 구분선과 겹치지 않도록 블록 박스로 분리 + 상하 여백 (ECQAUNIT-74376, ECQAUNIT-74549)
30794    // 고정 height 는 번역/화면폭에 따른 줄수 변동에 깨지므로 margin 방식 사용. 긴 문구는 정해진 폭 안에서 줄바꿈(word-break).
30795    // .total(가격 span) 내부는 폭이 좁아 블록이 찌그러지므로 .total 형제로 부착해 컨테이너 전체 폭 사용.
30796    // 형제 부착 시 가격 색 상속이 끊기므로 스킨의 가격 strong 색을 런타임에 읽어 유지
30797    var sPriceColor = EC$(sTotalPriceSelector).find('strong').first().css('color') || '';
30798    var sBlockTaxTypeHtml = '<span class="globale-tax-policy" style="display:block;margin:8px 0;line-height:1.4;text-align:left;word-break:break-word;'
30799        + (sPriceColor !== '' ? 'color:' + sPriceColor + ';' : '') + '">' + sTaxText + '</span>';
30800
30801    // 중복 부착 방지: 기존 globale-tax-policy 제거 후 재부착
30802    EC$(sTotalPriceSelector).find('.globale-tax-policy').remove();
30803
30804    if (EC_MOBILE === true || EC_MOBILE_DEVICE === true) {
30805        EC$(sTotalPriceSelector).siblings('.globale-tax-policy').remove();
30806        EC$(sTotalPriceSelector).after(sBlockTaxTypeHtml);
30807
30808        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer(true) === true) {
30809            parent.EC$(sTotalPriceSelector).siblings('.globale-tax-policy').remove();
30810            parent.EC$(sTotalPriceSelector).after(sBlockTaxTypeHtml);
30811        }
30812        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer() === true) {
30813            if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isDisplayLayer() === false) {
30814                EC$("#productOptionIframe").contents().find(sTotalPriceSelector).siblings('.globale-tax-policy').remove();
30815                EC$("#productOptionIframe").contents().find(sTotalPriceSelector).after(sBlockTaxTypeHtml);
30816            }
30817        }
30818    } else if (sTotalPriceSelector.indexOf('totalProducts') >= 0) {
30819        // PC 옵션레이어/옵션박스(#totalProducts): 폭이 좁아 .total 내부 inline 부착 시 총금액과
30820        // 한 줄로 이어져 짤린다. 모바일과 동일하게 .total 형제 블록 + 폭 내 줄바꿈으로 분리. (ECQAUNIT-74549)
30821        EC$(sTotalPriceSelector).siblings('.globale-tax-policy').remove();
30822        EC$(sTotalPriceSelector).after(sBlockTaxTypeHtml);
30823    } else {
30824        // PC 상세 기본가격(#totalPrice): 폭이 넓어 기존 옆(inline) 노출 유지
30825        EC$(sTotalPriceSelector).append(sTaxTypeHtml);
30826    }
30827}
30828
30829
30830/**
30831 * 상품금액 계산 (모바일 및 할인판매가 체크)
30832 * @param iQuantity 수량
30833 * @param iQuantity 가격
30834 * @param sItemCode 옵션코드
30835 * @param bSoldout 품절여부
30836 * @param fCallback 콜백함수
30837 */
30838function getProductPrice(iQuantity, iOptionPrice, sItemCode, bSoldOut, fCallback)
30839{
30840    EC_SHOP_FRONT_DEBUG.log("fn - getProductPrice");
30841
30842    var fProductPrice = CAFE24.SHOP_PRICE.toShopPrice(product_price);
30843    if (typeof(iQuantity) === 'undefined' || iQuantity == 0) {
30844        iQuantity = 1;
30845    }
30846    // 1+N이벤트의 경우
30847    iEventQuantity = CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.getQuantity(iQuantity, iProductNo);
30848    fProductPrice = iOptionPrice * parseInt(iEventQuantity, 10);
30849    oProductList = TotalAddSale.getProductList();
30850    TotalAddSale.setSubscriptionParam();
30851    if (CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING.sCurrentCompositionCode !== null) {
30852        TotalAddSale.setParam('composition_code', CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING.sCurrentCompositionCode);
30853        var iFundingNum = EC$('.EC-funding-checkbox[value="'+ CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_FUNDING.sCurrentCompositionCode+'"]').data('funding-no');
30854        TotalAddSale.setParam('funding_no', iFundingNum);
30855    }
30856
30857    if (typeof(CAFE24.SHOP_FRONT_PRODUCT_RENTAL) === 'object') {
30858        CAFE24.SHOP_FRONT_PRODUCT_RENTAL.changeRentalPrice(fProductPrice);
30859    }
30860
30861    // 할인판매가
30862    if (sItemCode != 'undefined' && sItemCode != '' && sItemCode != '*' && sItemCode != '**' && sItemCode !== null) {
30863        // 옵션이 있는 경우에는 iOptionPrice가 판매가로 들어가 있어서
30864        // 할인된 금액이 처리되지 않지만 옵션이 없는 경우 이쪽으로 판매가가 할인 판매가로 설정되어버림
30865        // 상품 상세페이지내에서는 할인 판매가로 컨트롤 없음
30866        //fProductPrice = CAFE24.SHOP_PRICE.toShopPrice(product_sale_price);
30867        // 품절시 ajax호출안함
30868        TotalAddSale.setProductOptionType(sItemCode, sOptionType);
30869        TotalAddSale.setSoldOutFlag(bSoldOut);
30870        TotalAddSale.setQuantity(sItemCode, iQuantity);
30871        TotalAddSale.setParam('product', oProductList);
30872        if (has_option === 'F') {
30873            iQuantity = iEventQuantity;
30874        }
30875        TotalAddSale.getCalculatorSalePrice(fCallback, fProductPrice);
30876    } else {
30877        if (bSoldOut) {
30878            TotalAddSale.setQuantity(sItemCode, 0);
30879            TotalAddSale.setParam('product', oProductList);
30880        }
30881        fCallback(fProductPrice);
30882    }
30883
30884    return fProductPrice;
30885}
30886
30887/**
30888 * 이벤트 리스너 Object를 파라미터로 받아 추가입력옵션 길이 체크
30889 * @param oObj
30890 * @param sVal
30891 * @param iLimit
30892 */
30893function addOptionWordWithObj(oObj, sVal, iLimit)
30894{
30895    var iStrLen = sVal.length;
30896    var sErrorMsg = sprintf(__('메시지는 %s자 이하로 입력해주세요.'), iLimit);
30897
30898    if (iStrLen > iLimit) {
30899        if (CAFE24.checkChannelUI() === true) {
30900            oObj.siblings('.txt_help').remove(); // 기존의 에러 메시지가 있다면 제거
30901            oObj.after('<p class="txt_help">' + sErrorMsg + '</p>');
30902            oObj.parent('.ec-input-count').addClass('error');
30903        } else {
30904            alert(sErrorMsg);
30905        }
30906
30907        oObj.val(sVal.substr(0, sVal.length-1));
30908        return;
30909    }
30910    oObj.parent().parent().find('.length').html(iStrLen);
30911}
30912
30913/**
30914 * 추가입력옵션 길이 체크
30915 * @param oObj
30916 * @param limit
30917 */
30918function addOptionWord(sId, sVal, iLimit)
30919{
30920    // 영문,한글 상관없이 iLimit 글자만큼 제한하도록 수정 (ECHOSTING-78226)
30921    //var iStrLen = stringByteSize(sVal);
30922    addOptionWordWithObj(EC$('#'+sId), sVal, iLimit);
30923}
30924
30925/**
30926 * 문자열을 UTF-8로 변환했을 경우 차지하게 되는 byte 수를 리턴한다.
30927 */
30928function stringByteSize(str)
30929{
30930    if (str == null || str.length == 0) return 0;
30931    var size = 0;
30932    for (var i = 0; i < str.length; i++) {
30933      size += charByteSize(str.charAt(i));
30934    }
30935    return size;
30936}
30937
30938/**
30939 * 글자수 체크
30940 * @param ch
30941 * @returns {Number}
30942 */
30943function charByteSize(ch)
30944{
30945    if (ch == null || ch.length == 0) return 0;
30946    var charCode = ch.charCodeAt(0);
30947    if (escape(charCode).length > 4) {
30948        return 2;
30949    } else {
30950        return 1;
30951    }
30952}
30953
30954/**
30955 * 기존의 CAFE24.SHOP_PRICE_FORMAT.toShopPrice() 의 래핑 함수
30956 * @param fPrice 옵션 추가 금액
30957 * @returns String 옵션 추가 금액(금액이 0보다 클경우 '+' 태그 추가)
30958 */
30959function getOptionPrice(fPrice)
30960{
30961        var sPricePlusTag = '';
30962
30963        if (fPrice > 0) {
30964            sPricePlusTag = '+';
30965        } else {
30966            sPricePlusTag = '-';
30967            fPrice = Math.abs(fPrice);
30968        }
30969
30970        // [ECQAINT-79686] presentment 활성 시 결제화폐 환산+통화기호 (SHOP_PRICE/FORMAT 헬퍼가 비활성 시 기존 포맷 폴백)
30971        if (SHOP.isG2G() === true) {
30972            return sPricePlusTag + CAFE24.SHOP_PRICE.toShopPricePresentment(fPrice, true);
30973        }
30974        var oCurrencyInfoMap79686 = CAFE24.SHOP_CURRENCY_INFO;
30975        if (oCurrencyInfoMap79686) {
30976            var oCurrencyInfo79686 = oCurrencyInfoMap79686[CAFE24.SDE_SHOP_NUM] || oCurrencyInfoMap79686[undefined];
30977            if (oCurrencyInfo79686) {
30978                if (oCurrencyInfo79686.bPresentmentEnabled === true) {
30979                    return sPricePlusTag + CAFE24.SHOP_PRICE_FORMAT.toShopPricePresentment(fPrice);
30980                }
30981            }
30982        }
30983        var sPrice = CAFE24.SHOP_PRICE.toShopPrice(fPrice, true);
30984        var aFormat = CAFE24.SHOP_CURRENCY_FORMAT.getShopCurrencyFormat();
30985        return sPricePlusTag + aFormat.head + sPrice + aFormat.tail;
30986}
30987
30988/**
30989 * 추가구성상품 여부 판단후 최종금액 산출
30990 * @param string sTotalSalePrice 총 상품 금액
30991 * @param int iTotalSalePrice 판매가
30992 * @returns string 추가구성 총 상품금액
30993 */
30994function getAddProductExistTotalSalePrice(iTotalSalePrice)
30995{
30996     EC$('.add_product_option_box_price').each(function() {
30997         iTotalSalePrice += parseFloat(EC$(this).val());
30998     });
30999
31000     return CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iTotalSalePrice);
31001}
31002
31003/**
31004 * 상품상세페이지 기존 모듈 제거하고 신규 모듈로 (ajax)
31005 * coupon_productdetail_new.html 에 쿠폰다운로드 신규모둘을 추가하여 ajax처리
31006 */
31007function getPrdDetailNewAjax()
31008{
31009    var sPath = document.location.pathname;
31010
31011    if (CAFE24.UTIL.trim(parent.EC$('.ec-product-couponAjax').html()) !== "") {
31012        return;
31013    }
31014
31015    EC$.get('/product/coupon_productdetail_new.html',{'product_no': iProductNo,'cate_no': iCategoryNo, 'sPath': sPath} ,function(sHtml) {
31016        parent.EC$('.ec-product-couponAjax').html(sHtml);
31017        parent.EC$('.ec-product-couponAjax').show();
31018
31019        EC$('div.eToggle .title').click(function() {
31020            var toggle = EC$(this).parent('.eToggle');
31021            if (toggle.hasClass('disable') == false) {
31022                EC$(this).parent('.eToggle').toggleClass('selected');
31023            }
31024        });
31025    });
31026}
31027
31028var SELECTEDITEM = {
31029    iSequence: 0,
31030    sElementIdPrefix: 'option_box',
31031    getElementId: function()
31032    {
31033        return this.sElementIdPrefix+this.getSequence();
31034    },
31035    getSequence: function()
31036    {
31037        return this.iSequence++;
31038    }
31039};
31040
31041CAFE24.SHOP_FRONT_PRODUCT_INFO = {
31042    getTotalQuantity: function()
31043    {
31044        var sQuantitySelector = 'input[name="quantity_opt[]"]';
31045        var sQuantityContext = (has_option === 'F' ? '' : '#totalProducts');
31046        if (EC$('.EC-funding-checkbox').length > 0) {
31047            sQuantitySelector = 'input.quantity';
31048            sQuantityContext = '.xans-product-funding';
31049        }
31050        var iTotalCount = 0;
31051        EC$(sQuantitySelector, sQuantityContext).each(function() {
31052            var iQuantity = EC$(this).val();
31053            if (typeof(EC$(this).attr('composition-code')) !== 'undefined') {
31054                iQuantity = 0;
31055                var sCompositionCode = EC$(this).attr('composition-code');
31056                if (EC$('.selected-funding-item.option_box_price[composition-code="'+sCompositionCode+'"]').length > 0) {
31057                    iQuantity = EC$('.selected-funding-item.option_box_price[composition-code="'+sCompositionCode+'"]').attr('quantity');
31058                }
31059            }
31060
31061            iTotalCount = iTotalCount + parseInt(iQuantity, 10);
31062        });
31063        return iTotalCount;
31064    }
31065};
31066
31067var EC_SHOP_FRONT_PRODUCT_INFO = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_INFO');
31068var CAPP_SIZE_GUIDE = function() {
31069    // 사이즈 가이드 데이터
31070    var aSizeGuide = {};
31071
31072    var initialize = function() {
31073        try {
31074            EC$(document).on('click', '.size_guide_info', function() {
31075                var sProductNo = EC$(this).attr('product_no');
31076                getSizeGuide(sProductNo);
31077            });
31078        } catch (e) {}
31079    };
31080
31081    /**
31082     * 사이즈 가이드 팝업
31083     * @param sProductNo 상품번호
31084     */
31085    var getSizeGuide = function(sProductNo) {
31086        EC$('.xans-product-sizeguide').remove();
31087        if (typeof(aSizeGuide[sProductNo]) !== 'undefined') {
31088            layerSizeGuide(sProductNo);
31089            return;
31090        }
31091
31092        EC$.get('/product/sizeguide.html?product_no='+sProductNo, function(sHtml)
31093        {
31094            // optimizer.php 스크립트 제거 - 동적 HTML 삽입 시 이벤트 충돌 방지
31095            sHtml = sHtml.replace(/<script.*?ind-script\/optimizer.php.*?<\/script>/g, '');
31096            setSizeGuide(sProductNo, sHtml);
31097            layerSizeGuide(sProductNo);
31098        });
31099    };
31100
31101    var setSizeGuide = function(sProductNo, sHtml) {
31102        aSizeGuide[sProductNo] = sHtml;
31103    };
31104
31105    var layerSizeGuide = function(sProductNo) {
31106        if (EC_MOBILE_DEVICE) {
31107            window.open("/product/sizeguide.html?product_no=" + sProductNo, "popSizeGuide", "toolbar=no,scrollbars=no,resizable=yes,width=800,height=640,left=0,top=0");
31108        } else {
31109            EC$('body').append(EC$('<div id="sSizeGuideLayer" style="z-index:10003; position:relative;"></div>'));
31110            EC$('#sSizeGuideLayer').html(aSizeGuide[sProductNo]);
31111            EC$('#sSizeGuideLayer').show();
31112        }
31113    };
31114
31115    return {
31116        init: function() {
31117            initialize();
31118        }
31119    };
31120
31121}();
31122
31123EC$(function() {
31124    CAPP_SIZE_GUIDE.init();
31125});
31126
31127EC$(function() {
31128    // 모바일 할인 적용 상품일 경우
31129    if (typeof(isMobileDcStatus) !== 'undefined' && isMobileDcStatus == 'F') {
31130        // 모바일 할인이 적용 되지 않는 상품일 경우 가려준다.
31131        try {
31132            EC$('#span_product_price_mobile_p_line').hide();
31133            EC$('#span_optimum_discount_price_mobile_p_line').hide();
31134            EC$('#span_product_price_mobile_d_line').hide();
31135        } catch (e) {}
31136    }
31137    CAFE24.SHOP_FRONT_QRCODE.init();
31138
31139    CAFE24.SHOP_FRONT_REGULAR_DELIVERY.init();
31140});
31141
31142CAFE24.SHOP_FRONT_QRCODE = {
31143    init: function()
31144    {
31145        if (typeof qrcode_class !== 'string' || qrcode_class.length < 1) {
31146            return;
31147        }
31148        EC$('.'+qrcode_class).click(CAFE24.SHOP_FRONT_QRCODE.bindUrlCopyButton);
31149    },
31150    bindUrlCopyButton: function()
31151    {
31152        var sTargetUrl = EC$('img.EC_QRCODE_URL_BUTTON-'+qrcode_class).attr('target-url');
31153        if (typeof sTargetUrl === 'undefined') {
31154            return;
31155        }
31156        if (typeof(window.clipboardData) === 'object') {
31157            window.clipboardData.setData('text', sTargetUrl);
31158        } else {
31159            EC$('<textarea id="qrcode_dummy">').css({'position': 'absolute','top': '-1000px'}).appendTo('body').text(sTargetUrl).select();
31160            document.execCommand('copy');
31161        }
31162        alert(__('URL.ADDRESS.COPIED.CTRL', 'SHOP.JS.FRONT.NEW.PRODUCT.INFO'));
31163        EC$('textarea#qrcode_dummy').remove();
31164    }
31165};
31166
31167var EC_SHOP_FRONT_QRCODE = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_QRCODE');
31168
31169/**
31170 * SNS 링크 정보
31171 * @param sMedia
31172 * @param iProductNo
31173 */
31174function SnsLinkAction(sMedia, iProductNo)
31175{
31176    CAFE24.PLUSAPP_BRIDGE.shareSocialLink(sMedia, iProductNo);
31177    window.open(sSocialUrl + '?product_no=' + iProductNo + '&type=' + sMedia,sMedia);
31178}
31179
31180/**
31181 * 상품 상세 페이지 이동
31182 * @param iProductNo 상품번호
31183 * @param iCategoryNo 카테고리 번호
31184 * @param iDisplayGroup 진열그룹
31185 * @param sLink URL정보
31186 */
31187function product_detail(iProductNo, iCategoryNo, iDisplayGroup, sLink)
31188{
31189    var sLink = sLink ? sLink : '/product/detail.html';
31190    sLink += '?product_no=' + iProductNo + '&cate_no=' + iCategoryNo + '&display_group=' + iDisplayGroup;
31191
31192    try {
31193        opener.location.href = sLink;
31194    } catch (e) {
31195        location.href = sLink;
31196    }
31197
31198    self.close();
31199}
31200
31201/**
31202 * 추천메일보내기
31203 * @param product_no 상품번호
31204 * @param category_no 카테고리번호
31205 * @param display_group 진열그룹
31206 */
31207function recommend_mail_pop(product_no, category_no, display_group)
31208{
31209    option = "'toolbar=no," + "location=no," + "directories=no," + "status=no," + "menubar=no," + "scrollbars=yes," + "resizable=yes," + "width=576," + "height=568," + "top=300," + "left=200";
31210
31211    filename = "/product/recommend_mail.html?product_no=" + product_no + "&category_no=" + category_no;
31212    filename += "&display_group=" + display_group;
31213
31214    window.open(filename,"recommend_mail_pop",option);
31215}
31216
31217/**
31218 * 상품조르기 팝업 호출
31219 * @param product_no 상품번호
31220 */
31221function request_pop(product_no)
31222{
31223    option = "'toolbar=no," + "location=no," + "directories=no," + "status=no," + "menubar=no," + "scrollbars=yes," + "resizable=yes," + "width=576," + "height=568," + "top=300," + "left=200";
31224    filename = "/product/request.html?product_no[]=" + product_no;
31225
31226    window.open(filename,"request_pop",option);
31227}
31228
31229//모바일 옵션선택레이어(옵션미선택후 구매하기/장바구니/관심상품버튼 클릭시) 후처리 모음...
31230CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER = {
31231    bIsUseOptionLayer: false,
31232    bIsUseRegularDelivery: 'F',
31233    /**
31234     * 설정값 Set
31235     * @param bIsExec 강제실행여부
31236     * @param oCallBack 콜백함수(관심상품에서는 따로 fixedActionButton아이디값을 확인하지않고 실행되기떄문에 디자인확인하지 않고 바로 실행)
31237     */
31238    init: function(oCallBack)
31239    {
31240        //레이어가 사용가능한 상태인지 확인..
31241
31242        //모바일이 아니라면 사용하지 않음
31243        if (EC_MOBILE !== true && EC_MOBILE_DEVICE !== true) {
31244            return;
31245        }
31246
31247        if (CAFE24.checkChannelUI() === true) {
31248            return;
31249        }
31250
31251        //아이프레임 내에서는 레이어를 다시띄우지 않음
31252        if (CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame() === parent) {
31253            return;
31254        }
31255
31256        EC$.ajax({
31257            url: '/exec/front/Product/Moduleexist?section=product&file=layer_option&module=product_detail',
31258            dataType: 'json',
31259            success: function (data) {
31260                if (data.result === true) {
31261                    CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.bIsUseOptionLayer = true;
31262                    if (typeof oCallBack === 'function') {
31263                        oCallBack();
31264                    }
31265                }
31266            }
31267        });
31268    },
31269
31270    /**
31271     * 레이어띄우기(기존 로직때문에 영향이 있어 레이어를 띄우지 못하는 상황이면 false로 리턴하는 로직도 같이..)
31272     * @param iProductNo 상품번호
31273     * @param iCategoryNo 카테고리 번호
31274     * @param sType 각 액션별 정의(일반상품-normal / 세트상품-set / 관심상품에서 호출-wishlist)
31275     */
31276    setLayer: function(iProductNo, iCategoryNo, sType)
31277    {
31278        var iCategoryNo = iCategoryNo || '';
31279        var iProductNo = iProductNo || '';
31280
31281        //상품번호는 필수
31282        if (iProductNo === '') return false;
31283
31284        //레이어 사용가능상태가 아니면 false로 바로 리턴
31285        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.bIsUseOptionLayer === false) {
31286            return false;
31287        }
31288
31289        try {
31290            CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.createLayer(iProductNo, iCategoryNo, sType);
31291        } catch (e) {
31292            return false;
31293        }
31294
31295        return true;
31296    },
31297
31298    /**
31299     * 모듈이 존재하는지 확인후에 레이어 아이프레임 생성
31300     * @param iProductNo 상품번호
31301     * @param iCategoryNo 카테고리 번호
31302     * @param sType 각 액션별 정의(일반상품-normal / 세트상품-set / 관심상품에서 호출-wishlist)
31303     */
31304    createLayer: function(iProductNo, iCategoryNo, sType)
31305    {
31306        try {
31307            EC$('#opt_layer_window').remove();
31308        } catch (e) {}
31309
31310        CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.setHTML(iProductNo, iCategoryNo, sType);
31311
31312        // @see ECHOSTING-354154
31313        // 아이프레임으로 페이지를 로드할 때 스크립트의 실행 시간과 페이지 로드 완료 시점의 시간차가 발생하여
31314        // 옵션 및 금액 계산 관련 스크립트가 정상적으로 동작하지 않기 때문에 (display 속성 등)
31315        // 로드 전에 무조건 해당 페이지를 뿌려주고 opacity만 0으로 변경하여 정상 동작하도록 처리
31316        EC$('#opt_layer_window').show().css('opacity', 0);
31317
31318        // 아이프레임이 로드된후에 parent 상세페이지의 옵션정보와 동기화
31319        EC$('#productOptionIframe').on('load', function() {
31320            setTimeout((function() {
31321                EC$('#opt_layer_window').css('opacity', 100);
31322
31323                // 구매버튼 높이
31324                var iActionHeight = EC$(this).contents().find('.xans-product-action').outerHeight();
31325                // 레이어 전체 높이
31326                var iTotalHeight = EC$(this).contents().find('#product_detail_option_layer').outerHeight();
31327                // 닫기버튼 높이
31328                var iCloseButtonHeight = EC$(this).contents().find('#product_detail_option_layer .btnClose').outerHeight();
31329                // 네이버체크아웃 버튼 높이
31330                var iCheckOuterHeight = EC$(this).contents().find('#product_detail_option_layer #NaverChk_Button').outerHeight() || 0;
31331                // 카카오체크아웃 버튼 높이
31332                var oKakaoButton = EC$(this).contents().find('#product_detail_option_layer #kakao-checkout-button');
31333                if (oKakaoButton.length > 0) {
31334                    var iKakaoHeight = oKakaoButton.outerHeight() < 1 ? 90 : oKakaoButton.outerHeight();
31335                    iCheckOuterHeight += iKakaoHeight;
31336                }
31337
31338                // 구매버튼 + 닫기버튼을 제외한 영역의 높이가 200이 안된다면  최소높이값에 구매버튼 높이를 더해서 지정
31339                if (iTotalHeight - iActionHeight - iCloseButtonHeight < 200 + iCloseButtonHeight) {
31340                    iTotalHeight = 200 + iCloseButtonHeight + iActionHeight;
31341                }
31342
31343                // 체크아웃버튼이 있을경우 해당버튼 높이도 더함
31344                iTotalHeight += iCheckOuterHeight;
31345                EC$(this).css('height', iTotalHeight);
31346
31347                if (sType === 'normal') {
31348                    // 일반상품 상세페이지와 레이어 동기화
31349                    CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.setNormalInit();
31350                } else if (sType === 'set') {
31351                    // 세트상품 상세페이지와 레이어 동기화
31352                    CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.setSetInit();
31353                }
31354
31355                if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.bIsUseRegularDelivery === 'T') {
31356                    EC$(this).contents().find("#product_detail_option_layer #actionBuy").hide();
31357                    EC$(this).contents().find("#product_detail_option_layer #btnRegularDelivery").removeClass('displaynone').show();
31358                    EC$(this).contents().find("#product_detail_option_layer #btnRegularDelivery").append(
31359                        '<input id="is_subscriptionT" style="display: none" checked="checked" class="EC_regular_delivery" name="is_subscription" value="T" type="radio">'
31360                    );
31361                }
31362
31363                CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.showLayer();
31364            }).bind(this));
31365        });
31366    },
31367
31368    /**
31369     * 레이어노출시키기
31370     */
31371    showLayer: function()
31372    {
31373        //기존 고정된 위치에 나오던것을 스크롤에 따라 움직이도록 디자인변경 - setHTML() 참조
31374        var iTop = parseInt((EC$(window).height() - EC$("#productOptionIframe").height()) / 2);
31375        EC$("#opt_layer_iframe_parent").css({"top": iTop, "left": 0});
31376        EC$('#opt_layer_window').show();
31377    },
31378
31379    /**
31380     * 레이어 HTML생성
31381     * @param iProductNo 상품번호
31382     * @param iCategoryNo 카테고리 번호
31383     * @param sType 각 액션별 정의(일반상품-normal / 세트상품-set / 관심상품에서 호출-wishlist)
31384     */
31385    setHTML: function(iProductNo, iCategoryNo, sType)
31386    {
31387        var sPrdOptUrl = "/product/layer_option.html?product_no="+iProductNo+'&cate_no='+iCategoryNo+'&bPrdOptLayer=T&bIsUseRegularDelivery=F';// + this.bIsUseRegularDelivery;
31388        if (sType === 'wishlist') {
31389            sPrdOptUrl += '&sActionType=' + sType;
31390        }
31391        if (CAFE24.getChRefData() !== undefined) {
31392            sPrdOptUrl += "&ch_ref=" + CAFE24.getChRefData();
31393        }
31394        var aPrdOptLayerHtml = [];
31395
31396        aPrdOptLayerHtml.push('<div id="opt_layer_window">');
31397        aPrdOptLayerHtml.push('<div id="opt_layer_background" style="position:fixed; top:0; left:0; width:100%; height:100%; background:#000; opacity:0.3; filter:alpha(opacity=30); z-index:9994;"></div>');
31398        aPrdOptLayerHtml.push('<div id="opt_layer_iframe_parent" style="position:fixed; top:0; left:0; width:100%; z-index:9995;">');
31399        aPrdOptLayerHtml.push('<iframe src="'+sPrdOptUrl+'" id="productOptionIframe" style="width:100%; height:100%; border:0;"></iframe>');
31400        aPrdOptLayerHtml.push('</div>');
31401        aPrdOptLayerHtml.push('</div>');
31402
31403        EC$('body').append(aPrdOptLayerHtml.join(''));
31404    },
31405
31406    /**
31407     * 일반상품 담기시 레이어 동기화
31408     * 옵션선택레이어가 뜬후에 상세페이지에있던 옵션선택정보와 동기화하는듯
31409     */
31410    setNormalInit: function()
31411    {
31412        var sValue = '*';
31413        var oTarget = null;
31414        var oOptionIframe = EC$("#productOptionIframe")[0].contentWindow.CAFE24.SHOP_FRONT_NEW_OPTION_COMMON;
31415
31416        if (Olnk.isLinkageType(option_type) === true) {
31417            EC$('select[id^="' + product_option_id + '"]').each(function() {
31418                sValue = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(this);
31419                if (Olnk.getCheckValue(sValue,'') === true) {
31420                    oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #'+ EC$(this).attr('id')+'').val(EC$(this).val()).trigger('change');
31421                    oOptionIframe.setValue(oTarget, sValue);
31422                }
31423            })
31424        // 독립형 옵션에서 같은 옵션에서 여러 품목 선택할 경우 품목만큼 복사 되어야 함
31425        } else if (option_type === 'F') {
31426            var eOptionBox = EC$('input[class^="option_box_id"]');
31427            if (eOptionBox.length > 0) {
31428                eOptionBox.each(function () {
31429                    var sOptionId = CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.getOptionSelectId('product_option_id', EC$(this).val());
31430                    if (sOptionId !== '') {
31431                        EC$('#' + sOptionId).attr('none_create_option_box', true);
31432                        oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #' + sOptionId + '');
31433                        oOptionIframe.setValue(oTarget, EC$(this).val(), true, true);
31434                    }
31435                });
31436            }
31437        } else {
31438            EC$('select[id^="' + product_option_id + '"]').each(function() {
31439                var sSelectOptionId = EC$(this).attr('id');
31440                sValue = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(this);
31441                oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #'+sSelectOptionId+'');
31442
31443                if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isSeparateOption(oTarget) === true || option_type === 'F') {
31444                    // 독립형 옵션인 경우 옵션이 선택된 상태이면 attribute를 추가해서 본페이지의 옵션박스는 생성하지 않도록 함 (setOptionBox())
31445                    if (option_type === 'F' && CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isOptionSelected(EC$(this)) === true) {
31446                        EC$(this).attr('none_create_option_box', true);
31447                    }
31448                    oOptionIframe.setValue(oTarget, sValue, true, true);
31449                } else {
31450                    oOptionIframe.setValue(oTarget, sValue);
31451                }
31452            });
31453        }
31454
31455        // 파일첨부 리스트 복사
31456        var eFileOption = EC$('[name^="file_option"]');
31457        if (eFileOption.length > 0) {
31458            var sId = eFileOption.attr('id');
31459            FileOptionManager.sync(sId, EC$("#productOptionIframe")[0].contentWindow.EC$('ul#ul_' + sId));
31460        }
31461
31462        // 추가구성상품 리스트 복사
31463        var eAddOptionBox = EC$('input[class^="option_add_box_"]');
31464        if (eAddOptionBox.length > 0) {
31465            eAddOptionBox.each(function () {
31466                var aAddOptionBoxValue = EC$(this).val().split('||');
31467                var sAddoptionId = CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.getOptionSelectId('addproduct_option_id_', aAddOptionBoxValue[0]);
31468                if (sAddoptionId !== '') {
31469                    oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #' + sAddoptionId + '');
31470                    oOptionIframe.setValue(oTarget, aAddOptionBoxValue[0], true, true);
31471                }
31472            });
31473        }
31474
31475    },
31476    /**
31477     * 품목코드로 옵션selectbox id 조회
31478     */
31479    getOptionSelectId: function(sOptionId, sItemCode)
31480    {
31481        var eAddOption = EC$('select[id^="' + sOptionId + '"]');
31482        var sAddOptionId = '';
31483        eAddOption.each(function () {
31484            if (EC$(this).find('option[value="' + sItemCode + '"]').length > 0) {
31485                sAddOptionId =  EC$(this).attr('id');
31486            }
31487        });
31488        return sAddOptionId;
31489
31490    },
31491    /**
31492     * 세트상품 담기시 레이어 동기화
31493     * 옵션선택레이어가 뜬후에 상세페이지에있던 옵션선택정보와 동기화하는듯
31494     */
31495    setSetInit: function()
31496    {
31497        var oOptionIframe = EC$("#productOptionIframe")[0].contentWindow.CAFE24.SHOP_FRONT_NEW_OPTION_COMMON;
31498        var iTotalOptCnt = EC$('[class*='+set_option.setproduct_require+']').length;
31499        var iOptionSeq = 0;
31500        EC$('[class*='+set_option.setproduct_require+']').each(function(i) {
31501            if (EC$(this)[0].tagName == 'INPUT') {
31502                return;
31503            }
31504            var sSelectOptionId = EC$(this).attr('id');
31505            var sParentVal = CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionSelectedValue(this);
31506
31507            if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isOptionSelected(this) === true) {
31508                iOptionSeq = i + 2;
31509            }
31510            if (iTotalOptCnt >= iOptionSeq) {
31511                EC$("#productOptionIframe").contents().find('.'+set_option.setproduct_require+'_'+iOptionSeq).prop('disabled', false);
31512            }
31513
31514            var oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #'+sSelectOptionId+'');//.val(sParentVal).trigger('change');
31515            if (CAFE24.SHOP_FRONT_NEW_OPTION_VALIDATION.isSeparateOption(oTarget) === true) {
31516                EC$("#productOptionIframe")[0].contentWindow.CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oTarget, sParentVal, true, true);
31517            } else {
31518                EC$("#productOptionIframe")[0].contentWindow.CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oTarget, sParentVal);
31519            }
31520
31521        });
31522
31523        // 추가구성상품 리스트 복사
31524        var eAddOptionBox = EC$('input[class^="option_add_box_"]');
31525        if (eAddOptionBox.length > 0) {
31526            eAddOptionBox.each(function () {
31527                var aAddOptionBoxValue = EC$(this).val().split('||');
31528                var sAddoptionId = CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.getOptionSelectId('addproduct_option_id_', aAddOptionBoxValue[0]);
31529                if (sAddoptionId !== '') {
31530                    oTarget = EC$("#productOptionIframe")[0].contentWindow.EC$('#product_detail_option_layer #' + sAddoptionId + '');
31531                    oOptionIframe.setValue(oTarget, aAddOptionBoxValue[0], true, true);
31532                }
31533            });
31534        }
31535    },
31536
31537    /**
31538     * 옵션선택레이어가 존재하는지 여부(기존 비교 그대로)
31539     * @param bIsParent 부모Element에서 옵션레이어를 찾을 경우
31540     */
31541    isExistLayer: function(bIsParent)
31542    {
31543        if (EC_MOBILE !== true && EC_MOBILE_DEVICE !== true) {
31544            return false;
31545        }
31546
31547        if (bIsParent === true) {
31548            return typeof(window.parent) === 'object' && parseInt(parent.EC$('#opt_layer_window').length) > 0;
31549        } else {
31550            return typeof(EC$('#opt_layer_window')) === 'object' && parseInt(EC$('#opt_layer_window').length) > 0;
31551        }
31552    },
31553
31554    /**
31555     * 옵션선택 레이어가 display상태인지 여부
31556     * @param bIsParent 부모Element에서 옵션레이어를 찾을 경우
31557     */
31558    isDisplayLayer: function(bIsParent)
31559    {
31560        if (EC_MOBILE !== true && EC_MOBILE_DEVICE !== true) {
31561            return false;
31562        }
31563
31564        if (bIsParent === true) {
31565            return typeof(bPrdOptLayer) !== 'undefined' && bPrdOptLayer === 'T' && parent.EC$('#opt_layer_window').css('display') === 'block';
31566        } else {
31567            return (EC$('#opt_layer_window').css('display') === 'none') ? false : true;
31568        }
31569    }
31570};
31571
31572var EC_SHOP_FRONT_PRODUCT_OPTIONLAYER = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_OPTIONLAYER');
31573
31574/**
31575 * 프론트 옵션 정보 관리
31576 */
31577CAFE24.SHOP_FRONT_PRODUCT_OPTION_INFO = {
31578    /**
31579     * 옵션 타입 리턴
31580     * @param int iProductNo 상품 번호
31581     * @return string 옵션 타입
31582     */
31583    getOptionType: function (oOptionChoose) {
31584        return CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionType(oOptionChoose);
31585    },
31586
31587    /**
31588     * 옵션 리스팅 타입 리턴
31589     * @param int iProductNo 상품 번호
31590     * @return string 옵션 리스팅 타입
31591     */
31592    getItemListingType: function (oOptionChoose) {
31593        return CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getOptionListingType(oOptionChoose);
31594    },
31595
31596    /**
31597     * 전체 품목 재고 정보
31598     * @param int iProductNo 상품 번호
31599     * @return object 품목별 재고 정보 리스트
31600     */
31601    getAllItemStorkInfo: function (iProductNo) {
31602        return CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.getProductStockData(iProductNo);
31603    },
31604
31605    /**
31606     * 옵션값으로 품목코드 구하여 리턴
31607     * @param int iProductNo 상품 번호
31608     * @param array aOptionValue 옵션값
31609     * @return string 품목코드
31610     */
31611    getItemCodeByOptionValue: function (iProductNo, aOptionValue) {
31612        var sOptionValue = aOptionValue.join("#$%");
31613
31614        return CAFE24.SHOP_FRONT_NEW_OPTION_DATA.getItemCode(iProductNo, sOptionValue);
31615    }
31616};
31617
31618var EC_SHOP_FRONT_PRODUCT_OPTION_INFO = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_OPTION_INFO');
31619
31620CAFE24.FRONT_NEW_PRODUCT_QUANTITY_VALID = {
31621    setBuyUnitQuantity: function(iBuyUnit, iProductMin, sBuyUnitType, sOrderLimitType, iItemCount, sType)
31622    {
31623        // 구매주문단위가 상품별의 경우 1씩 증가
31624        if (sBuyUnitType === 'P') {
31625            iBuyUnit = (iItemCount > 1) ? 1 : iBuyUnit;
31626            // 최초 셋팅되는 수량은 "상품"기준 구매단위 에서 "품목"기준 최소/최대 수량 =? 최소수량이 기본수량
31627            if (sType === 'base' && sOrderLimitType === 'O') {
31628                iBuyUnit = iProductMin;
31629            }
31630        }
31631        return iBuyUnit;
31632    },
31633    getBuyUnitQuantity: function(sType)
31634    {
31635        return this.setBuyUnitQuantity(parseInt(buy_unit,10), parseInt(product_min,10), buy_unit_type, order_limit_type, item_count, sType);
31636    },
31637    getSetBuyUnitQuantity: function(aProductInfo, sType) {
31638
31639        return this.setBuyUnitQuantity(parseInt(aProductInfo.buy_unit,10), parseInt(aProductInfo.product_min,10), aProductInfo.buy_unit_type, aProductInfo.order_limit_type, aProductInfo.item_count, sType);
31640    },
31641    setProductMinQuantity: function(iBuyUnit, iProductMin, sBuyUnitType, sOrderLimitType, iItemCount)
31642    {
31643        if (isNewProductSkin() === true) {
31644            var iItemCount = typeof(iItemCount) === "undefined" ? 1: parseInt(iItemCount, 10);
31645            // 단품 or 품목이 1개인경우 품목-품목 기준으로 동작
31646            if (iItemCount > 1) {
31647                // 상품기준 단위 증차감 단위는 1
31648                if (sBuyUnitType === 'P' && sOrderLimitType === 'P') {
31649                    iProductMin = 1;
31650                    // "품목"기준 단위 이면서 최소/최대 "상품"기준의 경우 "품목"구매단위가 최소수량
31651                } else if (sOrderLimitType === 'P') {
31652                    iProductMin = iBuyUnit;
31653                }
31654            }
31655        } else {
31656            var iBuyUnit = parseInt(buy_unit, 10);
31657            iBuyUnit = iBuyUnit < 1 ? 1 : iBuyUnit;
31658            var iFactor = Math.ceil(iProductMin / iBuyUnit);
31659            iProductMin = iBuyUnit * iFactor;
31660        }
31661
31662        return iProductMin;
31663    },
31664    getProductMinQuantity: function()
31665    {
31666        this.initProductOptionModule();
31667        return this.setProductMinQuantity(parseInt(buy_unit,10), parseInt(product_min,10), buy_unit_type, order_limit_type, item_count);
31668    },
31669    getSetProductMinQuantity: function(aProductInfo)
31670    {
31671        return this.setProductMinQuantity(parseInt(aProductInfo.buy_unit,10), parseInt(aProductInfo.product_min,10), aProductInfo.buy_unit_type, aProductInfo.order_limit_type, aProductInfo.item_count);
31672    },
31673    getNumberValidate: function(e)
31674    {
31675        var keyCode = e.which;
31676        // Tab, Enter, Delete키 포함
31677        var isNumberPress = ((keyCode >= 48 && keyCode <= 57 && !e.shiftKey) // 숫자키
31678        || (keyCode >= 96 && keyCode <= 105) // 키패드
31679        || keyCode == 8 // BackSpace
31680        || keyCode == 9 // Tab
31681        || keyCode == 46); // Delete
31682
31683        if (!isNumberPress) {
31684            e.preventDefault();
31685        }
31686    },
31687    initProductOptionModule : function() {
31688        // product_option모듈 미사용시 스크립트 오류 방어
31689        if (typeof(item_count) === 'undefined') {
31690            item_count = 1;
31691        }
31692        if (typeof isNewProductSkin !== 'function') {
31693            window.isNewProductSkin = function() { return false; }
31694        }
31695    }
31696};
31697
31698var EC_FRONT_NEW_PRODUCT_QUANTITY_VALID = CAFE24.getDeprecatedNamespace('EC_FRONT_NEW_PRODUCT_QUANTITY_VALID');
31699
31700CAFE24.SHOP_FRONT_REGULAR_DELIVERY = {
31701    init: function()
31702    {
31703        EC$('#EC_cycle_count option').eq(0).prop('disabled', true);
31704        EC$('#EC_regular_count option').eq(0).prop('disabled', true);
31705
31706        EC$('.EC_regular_delivery').on('click', function() {
31707            CAFE24.SHOP_FRONT_REGULAR_DELIVERY.changeBuyButton(EC$(this).val());
31708            if (typeof ProductSet !== 'undefined') {
31709                ProductSet.setOptionBoxQuantity(EC$('#option_box1_quantity'), 'change');
31710            } else if (has_option === 'F') {
31711                setPrice(false, false, '');
31712            } else {
31713                if (EC$('#option_box1_quantity').length > 0) {
31714                    // 옵션선택 이후에는 option_id를 특정할 수 없음 수량선택박스 있으면 재계산
31715                    setOptionBoxQuantity('change', EC$('#option_box1_quantity'));
31716                }
31717            }
31718        });
31719
31720        this.changeBuyButton(EC$('.EC_regular_delivery:checked').val());
31721
31722    },
31723    changeBuyButton: function(sUsedRegularDelivery)
31724    {
31725
31726        if (typeof(EC_FRONT_JS_CONFIG_SHOP) === 'undefined') {
31727            return;
31728        }
31729
31730        if (typeof(sUsedRegularDelivery) === 'undefined') {
31731            return;
31732        }
31733
31734        if (EC_FRONT_JS_CONFIG_SHOP.bRegularConfig === false) {
31735            return;
31736        }
31737
31738        if (EC$('#btnReserve').is(':visible') === true || EC$('#actionReserve').is(':visible') === true) {
31739            if (sUsedRegularDelivery === 'T') {
31740                EC$('#regular_cycle_period').removeClass('displaynone').show();
31741                EC$('#regular_count').show();
31742            } else {
31743                EC$('#regular_cycle_period').hide();
31744                EC$('#regular_count').hide();
31745            }
31746            return;
31747        }
31748
31749        var sActionButtonSelector = '#btnBuy, #actionBuy, #actionBuyClone, #actionBuyCloneFixed';
31750        var sActionButtonRegular = '#btnRegularDeliveryCloneFixed, #btnRegularDelivery, #regular_cycle_period, #regular_info';
31751
31752        if (sUsedRegularDelivery === 'T') {
31753            EC$(sActionButtonSelector).hide();
31754            EC$(sActionButtonRegular).removeClass('displaynone').show();
31755            EC$('#regular_count').show();
31756            CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.bIsUseRegularDelivery = 'T';
31757        } else {
31758            EC$(sActionButtonSelector).show();
31759            EC$(sActionButtonRegular).hide();
31760            EC$('#regular_count').hide();
31761            CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.bIsUseRegularDelivery = 'F';
31762        }
31763    }
31764};
31765
31766var EC_SHOP_FRONT_REGULAR_DELIVERY = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_REGULAR_DELIVERY');
31767
31768if (!Object.size) {
31769    Object.size = function(obj) {
31770        var size = 0, key;
31771        for (key in obj) {
31772            if (obj.hasOwnProperty(key)) size++;
31773        }
31774        return size;
31775    };
31776}
31777var SHOP_FRONT_NEW_PRODUCT_COMMON = CAFE24.getDeprecatedNamespace('SHOP_FRONT_NEW_PRODUCT_COMMON');
31778CAFE24.SHOP_FRONT_NEW_PRODUCT_COMMON = {
31779    /**
31780     * 바로구매 클릭시 장바구니에 같은 상품이 있을 경우 같이 구매 여부를 묻는 메세지
31781     * @param iCount
31782     * @returns {string}
31783     */
31784    getOverridePurchaseMessage: function(iCount)
31785    {
31786        let sReturnMessage = __('동일상품이 장바구니에 있습니다. 함께 구매하시겠습니까?');
31787        if (typeof iCount !== 'undefined') {
31788            sReturnMessage = sprintf(__('동일상품이 장바구니에 %s개 있습니다.'), iCount) + ' ' + __('함께 구매하시겠습니까?');
31789        }
31790        return sReturnMessage + '\n' + __('IF.PRESS.CANCEL.BUY.SELECTED', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION');
31791    }
31792};
31793/**
31794 * 기존에 product_submit함수에 있던 내용들을 메소드 단위로 리펙토링한 객체
31795 */
31796var PRODUCTSUBMIT = {
31797    oConfig: {
31798        'sFormSelector': '#frm_image_zoom'
31799    },
31800    /**
31801     * 1 : 바로 구매, 2 : 장바구니 넣기
31802     */
31803    sType: null,
31804    sAction: null,
31805    oObject: null,
31806    oValidate: null,
31807    oForm: null,
31808    oDebug: null,
31809    bIsDebugConsoleOut: false,
31810    sPaymethod: null,
31811    aInfo: null,
31812
31813    /**
31814     * 초기화
31815     */
31816    initialize: function(sType, sAction, oObject, aInfo)
31817    {
31818        this.oDebug = this.DEBUG.initialize(this);
31819        this.oDebug.setInfo('PRODUCTSUBMIT.initialize 시작');
31820        this.oDebug.setInfo('sType : ', sType);
31821        this.oDebug.setInfo('sAction : ', sAction);
31822        this.oDebug.setInfo('oObject : ', oObject);
31823        this.oDebug.setInfo('aInfo : ', aInfo);
31824
31825        if (typeof(sType) === 'undefined' || ((sType !== 'sms_restock' && sType !== 'email_restock') && typeof(sAction) === 'undefined')) {
31826            this.oDebug.setMessage('PRODUCTSUBMIT.initialize fail');
31827            return false;
31828        }
31829        this.sType = sType;
31830        this.sAction = sAction;
31831        this.oObject = oObject;
31832        this.sPaymethod = $(oObject).data('paymethod');
31833        this.oValidate = this.VALIDATION.initialize(this);
31834        this.UTIL.initialize(this);
31835        this.oForm = EC$(this.oConfig.sFormSelector);
31836        this.oForm.find(':hidden').remove();
31837        this.aInfo = aInfo;
31838        NEWPRD_ADD_OPTION.initCustomData();
31839    },
31840    /**
31841     * 데이터 검증
31842     */
31843    isValidRequest: function()
31844    {
31845        try {
31846            this.oDebug.setInfo('PRODUCTSUBMIT.isValidRequest 시작');
31847
31848            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidFunding');
31849            if (this.oValidate.isValidFunding() === false) {
31850                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidFunding fail');
31851            }
31852
31853            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isRequireLogin');
31854            if (this.oValidate.isRequireLogin() === false) {
31855                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isRequireLogin fail');
31856            }
31857
31858            // ECHOSTING-370710: 적립금 전용 상품 비회원 구매 차단
31859            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isMileageOnlyForNonmember');
31860            if (this.oValidate.isMileageOnlyForNonmember() === false) {
31861                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isMileageOnlyForNonmember fail');
31862            }
31863
31864            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isPriceContent');
31865            if (this.oValidate.isPriceContent() === false) {
31866                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isPriceContent fail');
31867            }
31868
31869            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isOptionDisplay');
31870            if (this.oValidate.isOptionDisplay() === false) {
31871                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isOptionDisplay fail');
31872            }
31873
31874            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isItemInStock');
31875            if (this.oValidate.isItemInStock() === false) {
31876                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isItemInStock fail');
31877            }
31878
31879            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidRegularDelivery');
31880            if (this.oValidate.isValidRegularDelivery() === false) {
31881                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidRegularDelivery fail');
31882            }
31883
31884            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidOption');
31885            if (this.oValidate.isValidOption() === false) {
31886                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidOption fail');
31887            }
31888
31889            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidAddproduct');
31890            if (this.oValidate.isValidAddproduct() === false) {
31891                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidAddproduct fail');
31892            }
31893
31894            this.oDebug.setInfo('PRODUCTSUBMIT.setDynamicCheckoutAppData');
31895            if (this.setDynamicCheckoutAppData() === false) {
31896                this.oDebug.setMessage('PRODUCTSUBMIT.setDynamicCheckoutAppDatafail');
31897            }
31898
31899            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isExclusivePurchaseOnly');
31900            if (this.oValidate.isExclusivePurchaseOnly() === false) {
31901                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isExclusivePurchaseOnly fail');
31902            }
31903
31904            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidReservationItemData');
31905            if (this.oValidate.isValidReservationItemData() === false) {
31906                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidReservationItemData fail');
31907            }
31908
31909            this.oDebug.setInfo('PRODUCTSUBMIT.oValidate.isValidCulturalTax');
31910            if (this.oValidate.isValidCulturalTax() === false) {
31911                this.oDebug.setMessage('PRODUCTSUBMIT.oValidate.isValidCulturalTax fail');
31912            }
31913
31914        } catch (mError) {
31915            return this.DEBUG.messageOut(mError, 'PRODUCT_ACTION.isValidRequest');
31916        }
31917        return true;
31918    },
31919    /**
31920     * 전송폼 생성
31921     */
31922    setBasketForm: function()
31923    {
31924        try {
31925            this.oDebug.setInfo('PRODUCTSUBMIT.setBasketForm 시작');
31926            // 예약 주문 체크
31927            STOCKTAKINGCHECKRESERVE.checkReserve();
31928
31929            this.oForm.attr('method', 'POST');
31930            this.oForm.attr('action', '/' + this.sAction);
31931
31932            this.oDebug.setInfo('PRODUCTSUBMIT.setCommonInput');
31933            if (this.setCommonInput() === false) {
31934                this.oDebug.setMessage('PRODUCTSUBMIT.setCommonInput fail');
31935            }
31936
31937            this.oDebug.setInfo('PRODUCTSUBMIT.setOptionId');
31938            if (this.setOptionId() === false) {
31939                this.oDebug.setMessage('PRODUCTSUBMIT.setOptionId fail');
31940            }
31941
31942            this.oDebug.setInfo('PRODUCTSUBMIT.setAddOption');
31943            if (this.setAddOption() === false) {
31944                this.oDebug.setMessage('PRODUCTSUBMIT.setAddOption fail');
31945            }
31946
31947            this.oDebug.setInfo('PRODUCTSUBMIT.setQuantityOveride');
31948            if (this.setQuantityOveride() === false) {
31949                this.oDebug.setMessage('PRODUCTSUBMIT.setQuantityOveride fail');
31950            }
31951
31952            this.oDebug.setInfo('PRODUCTSUBMIT.setSelectedItem');
31953            if (this.setSelectedItemHasOptionT() === false || this.setSelectedItemHasOptionF() === false) {
31954//                if (this.setSelectedItemHasOptionT() === false || this.setSelectedItemHasOptionF() === false || this.setSingleSelectedItem() === false) {
31955                this.oDebug.setMessage('PRODUCTSUBMIT.setSelectedItem fail');
31956            }
31957
31958            this.oDebug.setInfo('PRODUCTSUBMIT.setFundingData');
31959            if (this.setFundingData() === false) {
31960                this.oDebug.setMessage('PRODUCTSUBMIT.setFundingData fail');
31961            }
31962            this.oDebug.setInfo('PRODUCTSUBMIT.setRegularDelivery');
31963            if (this.setRegularDelivery() === false) {
31964                this.oDebug.setMessage('PRODUCTSUBMIT.setRegularDelivery fail');
31965            }
31966
31967            this.oDebug.setInfo('PRODUCTSUBMIT.setReservationData');
31968            if (this.setReservationData() === false) {
31969                this.oDebug.setMessage('PRODUCTSUBMIT.setReservationData fail');
31970            }
31971
31972            this.oDebug.setInfo('PRODUCTSUBMIT.setCulturalTax');
31973            if (this.setCulturalTax() === false) {
31974                this.oDebug.setMessage('PRODUCTSUBMIT.setCulturalTax fail');
31975            }
31976
31977        } catch (mError) {
31978            return this.DEBUG.messageOut(mError, 'PRODUCT_ACTION.setBasketForm');
31979        }
31980
31981        return true;
31982    },
31983    setBasketAjax : function(defer)
31984    {
31985        this.oDebug.setInfo('PRODUCTSUBMIT.setBasketAjax 시작');
31986        if (typeof(ACEWrap) !== 'undefined') {
31987            // 에이스카운터
31988            ACEWrap.addBasket();
31989        }
31990
31991        if (typeof(PRODUCTSUBMIT.sPaymethod) !== 'undefined') {
31992            this.oForm.prepend(getInputHidden('paymethod', this.sPaymethod));
31993        }
31994
31995        // 파일첨부 옵션의 파일업로드가 없을 경우 바로 장바구니에 넣기
31996        if (FileOptionManager.existsFileUpload() === false) {
31997            NEWPRD_ADD_OPTION.setItemPerAddOptionForm(this.oForm);
31998            action_basket(this.sType, 'detail', this.sAction, this.oForm.serialize(), this.UTIL.getData('sBasketType'), null, defer);
31999        } else {
32000            // 파일첨부 옵션의 파일업로드가 있으면
32001            FileOptionManager.upload(function(mResult) {
32002                // 파일업로드 실패
32003                if (mResult === false) {
32004                    PRODUCTSUBMIT.DEBUG.setMessage('PRODUCTSUBMIT.setBasketAjax fail - 파일업로드 실패');
32005                    return false;
32006                }
32007
32008                // 파일업로드 성공
32009                for (var sId in mResult) {
32010                    // 해당 품목에 파일 첨부 옵션 항목 추가
32011                    NEWPRD_ADD_OPTION.pushFileList(sId, mResult);
32012                    PRODUCTSUBMIT.UTIL.appendHidden(sId, FileOptionManager.encode(mResult[sId]));
32013                }
32014
32015                NEWPRD_ADD_OPTION.setItemPerAddOptionForm(PRODUCTSUBMIT.oForm);
32016                action_basket(PRODUCTSUBMIT.sType, 'detail', PRODUCTSUBMIT.sAction, PRODUCTSUBMIT.oForm.serialize(), PRODUCTSUBMIT.UTIL.getData('sBasketType'), null, defer);
32017            });
32018        }
32019    },
32020    setSelectedItem: function(sItemCode, iQuantity, sParameterName, sAdditionalData)
32021    {
32022        iQuantity = parseInt(iQuantity, 10);
32023        if (isNaN(iQuantity) === true || iQuantity < 1) {
32024            this.oDebug.setMessage('PRODUCTSUBMIT.setSelectedItem fail - iQuantity Fault');
32025            return false;
32026        }
32027
32028        if (typeof(sItemCode) !== 'string') {
32029            this.oDebug.setMessage('PRODUCTSUBMIT.setSelectedItem fail - sItemCode Fault');
32030            return false;
32031        }
32032
32033        if (typeof(sParameterName) === 'undefined') {
32034            sParameterName = 'selected_item[]';
32035        }
32036
32037        if (typeof(sAdditionalData) === 'undefined') {
32038            sAdditionalData = '';
32039        } else {
32040            sAdditionalData = '||' + sAdditionalData;
32041        }
32042
32043        this.UTIL.prependHidden(sParameterName, iQuantity+'||'+sItemCode+sAdditionalData);
32044        return true;
32045    },
32046    getQuantity: function(oQuantityElement)
32047    {
32048        if (typeof(quantity_id) === 'undefined') {
32049            var quantity_id = '#quantity';
32050        }
32051        var $oQuantityElement = EC$(quantity_id);
32052        if (typeof(oQuantityElement) === 'object') {
32053            $oQuantityElement = oQuantityElement;
32054        }
32055        return parseInt($oQuantityElement.val(),10);
32056    },
32057    setSelectedItemHasOptionF: function()
32058    {
32059        if (has_option !== 'F') {
32060            return true;
32061        }
32062
32063        if (item_code === undefined) {
32064            var sItemCode = product_code+'000A';
32065        } else {
32066            var sItemCode = item_code;
32067        }
32068        if (this.sType === 'funding') {
32069            CAFE24.SHOP_FRONT_PRODUCT_FUNDING.setStandaloneProductItem(sItemCode);
32070        } else {
32071            if (NEWPRD_ADD_OPTION.checkSoldOutProductValid(this.oObject) === false && CAFE24.SHOP_FRONT_PRODUCT_RESTOCK.isRestock(this.sType) === false) {
32072                this.setSelectedItem(sItemCode, this.getQuantity());
32073            }
32074        }
32075
32076        return true;
32077    },
32078    setEtypeSelectedItem: function(bFormAppend)
32079    {
32080        var _sItemCode = sProductCode + '000A';
32081        if (this.sType === 'reservation') {
32082            _sItemCode = '';
32083
32084        }
32085        var iQuantity = 0;
32086        var sSelectedItemByEtype = '';
32087        var _aItemValueNo = '';
32088        if (isNewProductSkin() === false) {
32089            iQuantity = this.getQuantity();
32090
32091            // 수량이 없는 경우에는 최소 구매 수량으로 던진다!!
32092            if (iQuantity === undefined) {
32093                iQuantity = product_min;
32094            }
32095            var _aItemValueNo = Olnk.getSelectedItemForBasketOldSkin(sProductCode, EC$('[id^="product_option_id"]'), iQuantity);
32096
32097            if (_aItemValueNo.bCheckNum === false) {
32098                _aItemValueNo = Olnk.getProductAllSelected(sProductCode , EC$('[id^="product_option_id"]') , iQuantity);
32099                if (_aItemValueNo === false) {
32100                    this.oDebug.setMessage('etype error');
32101                }
32102            }
32103            sSelectedItemByEtype = 'selected_item_by_etype[]='+EC$.toJSON(_aItemValueNo) + '&';
32104            if (bFormAppend === true) {
32105                this.setSelectedItem(_sItemCode, iQuantity);
32106                this.UTIL.appendHidden('selected_item_by_etype[]', EC$.toJSON(_aItemValueNo));
32107            }
32108        } else {
32109            var bIsProductEmptyOption = this.UTIL.getData('bIsProductEmptyOption');
32110            // 메인상품 선택여부 확인 false : 선택함 || true : 선택안함
32111            if (bIsProductEmptyOption === false && NEWPRD_ADD_OPTION.checkSoldOutProductValid(this.oObject) === false) {
32112                var iOptionBoxLength = EC$('.option_box_id').length - 1;
32113                EC$('.option_box_id').each(function (i) {
32114                    var sQuantityElement = EC$('#' + EC$(this).attr('id').replace('id', 'quantity'));
32115                    if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
32116                        sQuantityElement = EC$('#quantity_'+EC$(this).attr('composition-code'));
32117                    }
32118                    iQuantity = PRODUCTSUBMIT.getQuantity(sQuantityElement);
32119                    _aItemValueNo = Olnk.getSelectedItemForBasket(sProductCode, EC$(this), iQuantity);
32120
32121                    if (_aItemValueNo.bCheckNum === false) { // 옵션박스는 있지만 값이 선택이 안된경우
32122                        _aItemValueNo = Olnk.getProductAllSelected(sProductCode, EC$(this), iQuantity);
32123                    }
32124                    if (bFormAppend === true) {
32125                        PRODUCTSUBMIT.setSelectedItem(_sItemCode, iQuantity);
32126                        PRODUCTSUBMIT.UTIL.prependHidden('selected_item_by_etype[]', EC$.toJSON(_aItemValueNo));
32127                    }
32128                    sSelectedItemByEtype += 'selected_item_by_etype[]='+EC$.toJSON(_aItemValueNo) + '&';
32129                    var oItem = EC$('[name="item_code[]"]').eq(i);
32130                    var sItemCode = _sItemCode + '_' + i;
32131
32132                    //품목별 추가옵션 셋팅
32133                    if (bFormAppend === true) {
32134                        var ePerAddOption = EC$('.option_products .option').eq(i).find(".input_addoption:visible");
32135                        if (ePerAddOption.length > 0) { // 옵션 박스안에서 개별 입력시
32136                            sItemCode = Olnk.getCustomOptionItemCode(sProductCode, iOptionBoxLength, i);
32137                            NEWPRD_ADD_OPTION.setItemPerAddOptionData(sItemCode, ePerAddOption, PRODUCTSUBMIT.oForm);
32138                        } else {
32139                            //품목별 추가옵션 셋팅
32140                            var sItemAddOption = NEWPRD_ADD_OPTION.getAddOptionValue(oItem.attr('data-item-add-option'));
32141                            NEWPRD_ADD_OPTION.setItemAddOption(sItemCode, sItemAddOption, PRODUCTSUBMIT.oForm);
32142                        }
32143                    }
32144                });
32145
32146                // 전부 선택인 경우 필요값 생성한다.
32147                if (_aItemValueNo === '') {
32148                    iQuantity = this.getQuantity();
32149                    _aItemValueNo = Olnk.getProductAllSelected(sProductCode, EC$('[id^="product_option_id"]'), iQuantity);
32150                    if (_aItemValueNo !== false) {
32151                        if (bFormAppend === true) {
32152                            this.setSelectedItem(_sItemCode, iQuantity);
32153                            this.UTIL.prependHidden('selected_item_by_etype[]', EC$.toJSON(_aItemValueNo));
32154                        }
32155                        sSelectedItemByEtype += 'selected_item_by_etype[]='+EC$.toJSON(_aItemValueNo) + '&';
32156                    }
32157                }
32158            }
32159        }
32160        this.UTIL.setData('sSelectedItemByEtype', sSelectedItemByEtype);
32161    },
32162    setSelectedItemHasOptionT: function()
32163    {
32164        if (has_option !== 'T') {
32165            return true;
32166        }
32167
32168        if (Olnk.isLinkageType(sOptionType) === true) {
32169            this.setEtypeSelectedItem(true);
32170        } else {
32171            if (isNewProductSkin() === true && NEWPRD_ADD_OPTION.checkSoldOutProductValid(this.oObject) === false) {
32172                if (this.sType === 'funding') {
32173                    EC$('.xans-product-funding').each(function(i) {
32174                        if (EC$(this).find('.EC-funding-checkbox:checked').length !== 1) {
32175                            return;
32176                        }
32177                        var iQuantity = EC$(this).find('input.quantity').val();
32178                        var sItemCode = EC$(this).find('input.selected-funding-item').val();
32179                        PRODUCTSUBMIT.setSelectedItem(sItemCode, iQuantity);
32180                    });
32181
32182                } else {
32183                    if (EC$('[name="quantity_opt[]"][id^="option_box"]').length > 0 && EC$('[name="quantity_opt[]"][id^="option_box"]').length == EC$('[name="item_code[]"]').length) {
32184
32185                        EC$('[name="quantity_opt[]"][id^="option_box"]').each(function(i) {
32186
32187                            var oItem = EC$('[name="item_code[]"]').eq(i);
32188                            var sItemCode = oItem.val();
32189                            PRODUCTSUBMIT.setSelectedItem(sItemCode, PRODUCTSUBMIT.getQuantity(EC$(this)));
32190
32191                            //품목별 추가옵션 셋팅
32192                            var eProductBox = EC$('.option_products .option');
32193                            if (CAFE24.checkChannelUI() === true) {
32194                                eProductBox = EC$('.option_product[data-option-index]');
32195                            }
32196                            var ePerAddOption = eProductBox.eq(i).find(".input_addoption:visible");
32197                            if (ePerAddOption.length > 0) { // 옵션 박스안에서 개별 입력시
32198                                NEWPRD_ADD_OPTION.setItemPerAddOptionData(sItemCode, ePerAddOption, PRODUCTSUBMIT.oForm);
32199                            } else {
32200                                var sItemAddOption = NEWPRD_ADD_OPTION.getAddOptionValue(oItem.attr('data-item-add-option'));
32201                                NEWPRD_ADD_OPTION.setItemAddOption(sItemCode, sItemAddOption, PRODUCTSUBMIT.oForm);
32202                            }
32203                        });
32204                    }
32205                }
32206
32207            } else {
32208                // 뉴 상품 + 구스디 스킨
32209                var aItemCode = ITEM.getItemCode();
32210                for (var i = 0; i < aItemCode.length; i++) {
32211                    var sItemCode = aItemCode[i];
32212                    this.setSelectedItem(sItemCode, this.getQuantity(i));
32213                }
32214            }
32215        }
32216
32217        if (this.sType === 'sms_restock' || this.sType === 'email_restock') {
32218            this.UTIL.appendHidden('item_code', EC$(this.oObject).attr('item_code'));
32219        }
32220
32221        // 예약상품인 경우 selected_item 처리
32222
32223        return true;
32224    },
32225    setQuantityOveride: function()
32226    {
32227        if (this.sType !== 1 && this.sType !== 'naver_checkout' && this.sType !== 'direct_buy' && this.sType !== 'simple_pay' && this.sType !== 'app' && this.sType !== 'checkout') {
32228            return true;
32229        }
32230
32231        // 전역변수임
32232        sIsPrdOverride = 'F';
32233        if (this.sType === 1 || this.sType == 'simple_pay') {
32234            var aItemParams = [];
32235            var aItemCode = ITEM.getItemCode();
32236            for (var i = 0, length = aItemCode.length; i < length; i++) {
32237                aItemParams.push("item_code[]=" + aItemCode[i]);
32238            }
32239            var sOptionParam = this.UTIL.getData('sOptionParam');
32240            sOptionParam = sOptionParam + '&delvtype=' + delvtype + '&' + aItemParams.join("&");
32241            if (Olnk.isLinkageType(sOptionType) === true) {
32242                this.setEtypeSelectedItem();
32243                var sSelectedItemByEtype = this.UTIL.getData('sSelectedItemByEtype', sSelectedItemByEtype);
32244            }
32245            selectbuy_action(sOptionParam, iProductNo, sSelectedItemByEtype);
32246        }
32247
32248        if (this.sType === 'naver_checkout' || this.sType === 'direct_buy' || this.sType === 'app' || this.sType === 'checkout') {
32249            sIsPrdOverride = 'T';
32250        }
32251        this.UTIL.appendHidden('quantity_override_flag', sIsPrdOverride);
32252    },
32253    /**
32254     * 실제 옵션에 대한 검증이 아니라 구상품과의 호환을 위해 존재하는 파라미터들을 세팅해주는 메소드
32255     */
32256    setOptionId: function()
32257    {
32258        var count = 1;
32259        var sOptionParam = '';
32260        EC$('select[id^="' + product_option_id + '"]').each(function()
32261        {
32262            PRODUCTSUBMIT.UTIL.appendHidden('optionids[]', EC$(this).attr('name'));
32263            if (EC$(this).prop('required') === true || EC$(this).attr('required') === 'required') {
32264                PRODUCTSUBMIT.UTIL.appendHidden('needed[]', EC$(this).attr('name'));
32265            }
32266            var iSelectedIndex = EC$(this).get(0).selectedIndex;
32267            if (EC$(this).prop('required') && iSelectedIndex > 0) iSelectedIndex -= 1;
32268
32269            if (iSelectedIndex > 0) {
32270                sOptionParam += '&option' + count + '=' + iSelectedIndex;
32271                var sValue = EC$(this).val();
32272                var aValue = sValue.split("|");
32273                PRODUCTSUBMIT.UTIL.appendHidden(EC$(this).attr('name'), aValue[0]);
32274                ++count;
32275            }
32276        });
32277        this.UTIL.setData('sOptionParam', sOptionParam);
32278    },
32279    setAddOption: function()
32280    {
32281        if (add_option_name.length === 0) {
32282            return;
32283        }
32284        if (this.sType === 'funding') {
32285            // CAFE24.SHOP_FRONT_PRODUCT_FUNDING.getFundingBasketData를 참조하세요.
32286            return;
32287        }
32288
32289        var iAddOptionNo = 0;
32290        var aAddOptionName = [];
32291        if (has_option === 'F') {
32292            NEWPRD_ADD_OPTION.addItem(item_code);
32293            var iAddOptionIndex = NEWPRD_ADD_OPTION.getLastIndex();
32294        }
32295        for (var i = 0, iAddOptionNameLength = add_option_name.length; i < iAddOptionNameLength; i++) {
32296            var sValue = EC$('#' + add_option_id + i).val();
32297            if (typeof sValue === 'undefined') {
32298                continue;
32299            }
32300            if (has_option === 'F') {
32301                NEWPRD_ADD_OPTION.addCustomOption(iAddOptionIndex, {
32302                    type: 'text',
32303                    value: sValue,
32304                    info: add_option_name[i]
32305                }, 'input');
32306            }
32307            if (sValue === '') {
32308                continue;
32309            }
32310            this.UTIL.appendHidden('option_add[]', sValue);
32311            aAddOptionName[iAddOptionNo++] = add_option_name[i];
32312        }
32313        this.UTIL.appendHidden('add_option_name', aAddOptionName.join(';'));
32314        NEWPRD_ADD_OPTION.setItemAddOptionName(this.oForm); // 품목별 추가옵션명인데 왜 상품단위로 도는지 확인이 필요함
32315    },
32316    setFundingData: function()
32317    {
32318        if (this.sType !== 'funding') {
32319            return true;
32320        }
32321        if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING.getFundingBasketData !== 'function') {
32322            this.oDebug.setMessage('CAFE24.SHOP_FRONT_PRODUCT_FUNDING.getFundingBasketData error');
32323            return false;
32324        }
32325
32326        var oFundingBasketData = CAFE24.SHOP_FRONT_PRODUCT_FUNDING.getFundingBasketData();
32327        if (typeof(oFundingBasketData) !== 'object') {
32328            this.oDebug.setMessage(oFundingBasketData.sMessage);
32329            return false;
32330        }
32331
32332        delete oFundingBasketData.sMessage;
32333        delete oFundingBasketData.bIsResult;
32334        this.UTIL.appendHidden(oFundingBasketData);
32335
32336
32337    },
32338    setRegularDelivery : function()
32339    {
32340        if (PRODUCTSUBMIT.isRegularDelivery() === false) {
32341            return true;
32342        }
32343
32344        var sSubscriptionCycleValue = PRODUCTSUBMIT.getRegularSelectedValue();
32345
32346        // 디자인상에서 별도 처리 된 정기배송
32347        if (typeof(sSubscriptionCycleValue) === 'undefined') {
32348            return true;
32349        }
32350
32351        // 기존 하드코딩용
32352        var regex = /[W|M|Y]$/g;
32353        if (regex.test(sSubscriptionCycleValue) === false) {
32354            sSubscriptionCycleValue = sSubscriptionCycleValue + 'W';
32355        }
32356
32357        var sSubscriptionCycleCount = sSubscriptionCycleValue.substring(sSubscriptionCycleValue.length-1, -1);
32358        var sSubscriptionCycle = sSubscriptionCycleValue.slice(-1);
32359
32360        this.UTIL.appendHidden('is_subscription', EC$('.EC_regular_delivery:checked').val());
32361        this.UTIL.appendHidden('subscription_cycle', sSubscriptionCycle); // 주단위 현재는 고정
32362        this.UTIL.appendHidden('subscription_cycle_count', sSubscriptionCycleCount);
32363
32364        var sSubscriptionCountValue = PRODUCTSUBMIT.getRegularCountSelectedValue();
32365
32366        // 디자인상에서 별도 처리 된 정기배송
32367        if (typeof(sSubscriptionCountValue) === 'undefined') {
32368            return true;
32369        }
32370        this.UTIL.appendHidden('max_expected_pay_seq', sSubscriptionCountValue);
32371    },
32372    setReservationData : function()
32373    {
32374        // 예약상품이 아니므로 다른 작업은 하지 않고 패스
32375        if (this.sType !== 'reservation') {
32376            return true;
32377        }
32378        this.UTIL.appendHidden('product_service_type', 'reservation');
32379        this.UTIL.appendHidden('reservation_type', (EC$('input#reservation_type').val() ?? ''));
32380        this.UTIL.appendHidden('service_start_date', (EC$('input#service_start_date').val() ?? ''));
32381        this.UTIL.appendHidden('service_end_date', (EC$('input#service_end_date').val() ?? ''));
32382        this.UTIL.appendHidden('quantity_override_flag', 'T');
32383    },
32384    setCulturalTax : function()
32385    {
32386        this.UTIL.appendHidden('is_cultural_tax', SHOP_FRONT_PRODUCT_CULTURAL_TAX.getIsCulturalTax());
32387        return true;
32388    },
32389    setDynamicCheckoutAppData : function()
32390    {
32391        if (this.sType !== 'app') {
32392            return true;
32393        }
32394
32395        this.UTIL.appendHidden(this.aInfo);
32396    },
32397
32398    setCommonInput : function()
32399    {
32400        var sBasketType = (typeof(basket_type) === 'undefined') ? 'A0000' : basket_type;
32401        this.UTIL.setData('sBasketType', sBasketType);
32402
32403        var oCommon = {
32404            'product_no': iProductNo,
32405            'product_name': product_name,
32406            'main_cate_no': iCategoryNo,
32407            'display_group': iDisplayGroup,
32408            'option_type': option_type,
32409            'product_min': product_min,
32410            'command': 'add',
32411            'has_option': has_option,
32412            'product_price': product_price,
32413            'multi_option_schema': EC$('#multi_option').html(),
32414            'multi_option_data': '',
32415            'delvType': delvtype,
32416            'redirect': this.sType,
32417            'product_max_type': product_max_type,
32418            'product_max': product_max,
32419            'basket_type': sBasketType,
32420            'ch_ref': CAFE24.getChRefData()
32421        };
32422        // 상품명에 특수문자가 들어가면 인코딩/디코딩 관계로 레이어가 부모창을 검증하지 못하는 이슈가 발생하고, 쓰이지 않는 변수로 판단되어 제거
32423        if (this.sType === 'sms_restock') {
32424            delete oCommon.product_name;
32425        }
32426        this.UTIL.appendHidden(oCommon);
32427
32428        if (typeof(CAPP_FRONT_OPTION_SELECT_BASKETACTION) !== 'undefined' && CAPP_FRONT_OPTION_SELECT_BASKETACTION === true) {
32429            this.UTIL.appendHidden('basket_page_flag', 'T');
32430        } else {
32431            var oDlvChannelElement = EC$('#delivery_cost_prepaid_channel > li.selected');
32432            if (oDlvChannelElement.length > 0) {
32433                this.UTIL.appendHidden('prd_detail_ship_type', oDlvChannelElement.attr('data-value'));
32434            } else {
32435                this.UTIL.appendHidden('prd_detail_ship_type', EC$('#delivery_cost_prepaid').val());
32436            }
32437        }
32438        if (this.sType !== 'funding') {
32439            // 수량 체크
32440            var iQuantity = 1;
32441            if (CAFE24.SHOP_FRONT_PRODUCT_RESTOCK.isRestock(this.sType) === false) {
32442                iQuantity = checkQuantity();
32443                if (iQuantity == false) {
32444                    // 현재 관련상품 선택 했는지 여부 확인
32445                    // 관련 상품 자체가 없을때는 뒤에 저 로직을 탈 필요가 없음(basket_info 관련상품 체크박스)
32446                    if (EC$('input[name="basket_info[]"]').length <= 0 || NEWPRD_ADD_OPTION.checkRelationProduct(this.oObject, this.sType) === false) {
32447                        return false;
32448                    }
32449                }
32450            }
32451
32452            // 폼 세팅
32453            if (iQuantity == undefined || isNaN(iQuantity) === true || iQuantity < 1) {
32454                iQuantity = 1;
32455            }
32456            this.UTIL.appendHidden('quantity', iQuantity);
32457        }
32458
32459        // 바로구매 주문서 여부
32460        if (this.sType == 'direct_buy') {
32461            this.UTIL.appendHidden('is_direct_buy', 'T');
32462        } else {
32463            this.UTIL.appendHidden('is_direct_buy', 'F');
32464        }
32465    },
32466    VALIDATION: {
32467        initialize: function(oParent)
32468        {
32469            this.parent = oParent;
32470            return this;
32471        },
32472        isRequireLogin: function()
32473        {
32474            // ECHOSTING-58174
32475            if (sIsDisplayNonmemberPrice !== 'T') {
32476                return true;
32477            }
32478            switch (this.parent.sType) {
32479                case 1 :
32480                case 'simple_pay' : // 간편결제
32481                    alert(__('로그인후 상품을 구매해주세요.'));
32482                    break;
32483                case 2 :
32484                    alert(__('로그인후 장바구니 담기를 해주세요.'));
32485                     break;
32486                case 'direct_buy' :
32487                    alert(__('회원만 구매 가능합니다. 비회원인 경우 회원가입 후 이용하여 주세요.'));
32488                    break;
32489                default :
32490                    break;
32491            }
32492            btn_action_move_url('/member/login.html');
32493            return false;
32494        },
32495        // ECHOSTING-370710: 적립금 전용 상품은 비회원 구매 불가 - 상품상세에서 로그인 유도
32496        isMileageOnlyForNonmember: function()
32497        {
32498            if (typeof EC_FRONT_JS_CONFIG_SHOP === 'undefined' || EC_FRONT_JS_CONFIG_SHOP.sIsMileageOnlyProduct !== 'T') {
32499                return true;
32500            }
32501            if (EC_FRONT_JS_CONFIG_SHOP.sIsLoginMember === 'T') {
32502                return true;
32503            }
32504            alert(__('회원만 주문 가능한 상품이 있습니다. 로그인 후 이용해 주세요.'));
32505            btn_action_move_url('/member/login.html');
32506            return false;
32507        },
32508        isPriceContent: function()
32509        {
32510            if (typeof(product_price_content) === 'undefined') {
32511                return true;
32512            }
32513
32514            var sProductcontent = product_price_content.replace(/\s/g, '').toString();
32515            if (sProductcontent === '1') {
32516                alert(sprintf(__('%s 상품은 구매할 수 있는 상품이 아닙니다.'), product_name));
32517                return false;
32518            }
32519
32520            return true;
32521        },
32522        isOptionDisplay: function()
32523        {
32524            if (typeof CAFE24.SHOP_FRONT_NEW_OPTION_COMMON !== 'undefined'
32525                && has_option === 'T'
32526                && Olnk.isLinkageType(sOptionType) === false
32527                && CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.isValidOptionDisplay(product_option_id) === false) {
32528
32529                alert(sprintf(__('%s 상품은 구매할 수 있는 상품이 아닙니다.'), product_name));
32530                return false;
32531            }
32532            return true;
32533        },
32534        isItemInStock: function()
32535        {
32536            if (CAFE24.SHOP_FRONT_PRODUCT_RESTOCK.isRestock(this.parent.sType) === false && (EC$('.option_box_id').length == 0 && EC$('.soldout_option_box_id').length > 0) === true) {
32537                alert(__('품절된 상품은 구매가 불가능합니다.'));
32538                return false;
32539            }
32540
32541            return true;
32542        },
32543        isValidOption: function()
32544        {
32545            // 필수옵션 체크
32546            var bIsProductEmptyOption = CAFE24.SHOP_FRONT_PRODUCT_RESTOCK.isRestock(this.parent.sType) === false && checkOptionRequired() == false;
32547            this.parent.UTIL.setData('bIsProductEmptyOption', bIsProductEmptyOption);
32548
32549            //추가구성상품 옵션 체크
32550            var oValidAddProductCount = NEWPRD_ADD_OPTION.isValidAddOptionSelect(this.parent.oForm);
32551
32552            //관련상품 옵션 체크
32553            var oValidRelationProductCount = NEWPRD_ADD_OPTION.isValidRelationProductSelect(this.parent.oForm, this.parent.oObject, bIsProductEmptyOption);
32554
32555            // 개별 구매 관련 검증된 데이터
32556            var oIndividualValidData = NEWPRD_ADD_OPTION.getIndividualValidCheckData(oValidRelationProductCount, oValidAddProductCount, bIsProductEmptyOption, this.parent.oForm);
32557
32558            // 옵션 체크
32559            if (bIsProductEmptyOption === true) {
32560                // 실패 타입 존재 할 경우
32561                if (oIndividualValidData.sFailType !== '') {
32562                    return false;
32563                }
32564                //관련상품 및 추가구성상품 단독구매시 유효성 메시지 노출여부 결정(순차 검증진행 추가 or 관련 + 본상품)
32565                if (NEWPRD_ADD_OPTION.checkIndividualValidAction(oValidRelationProductCount, oValidAddProductCount) === false) {
32566                    return false;
32567                }
32568                // 독립형 일때
32569                var oExistRequiredSelect = (option_type === 'F') ? EC$('select[id^="' + product_option_id + '"][required="true"]') : false;
32570                var sMsg = __('필수 옵션을 선택해주세요.');
32571                try {
32572                    // 관련상품 체크 확인 유무
32573                    if (NEWPRD_ADD_OPTION.checkRelationProduct(this.parent.oObject, this.parent.sType) === false) {
32574                        return false;
32575                    }
32576
32577                    if (oIndividualValidData.isValidInidual === false && CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.setLayer(iProductNo, iCategoryNo, 'normal') === true) {
32578                        return false;
32579                    }
32580
32581                    if (Olnk.getOptionPushbutton(EC$('#option_push_button')) === true) {
32582                        var bCheckOption = false;
32583                        EC$('select[id^="' + product_option_id + '"]').each(function() {
32584                            if (EC$(this).prop('required') === true && Olnk.getCheckValue(EC$(this).val(),'') === false) {
32585                                bCheckOption = true;
32586                                return false;
32587                            }
32588                        });
32589                        if (bCheckOption === false) {
32590                            sMsg = __('품목을 선택해 주세요.');
32591                        }
32592                    }
32593                } catch (e) {
32594                    PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.isValidOption');
32595                }
32596
32597                // 메인상품 품목데이터 확인
32598                var isEmptyItemData = ITEM.getItemCode().length == false || ITEM.getItemCode() === false;
32599                // 추가구성상품 및 관련상품의 개별적 구매
32600                if (isEmptyItemData === true && oIndividualValidData.isValidInidual === true) {
32601                    if (NEWPRD_ADD_OPTION.checkVaildIndividualMsg(
32601oIndividualValidData, this.parent.sType, this.parent.oObject) === false) {
32602                        return false;
32603                    }
32604
32605                } else {
32606                    if (option_type === 'F') {
32607                        var aRequiredFalseOption = [];
32608                        var aItemCodeList = ITEM.getItemCode();
32609                        // 필수 옵션정보와 선택한 옵션 정보 비교
32610                        for (var i = 0; i < aItemCodeList.length; i++) {
32611                            var sTargetItemCode = aItemCodeList[i];
32612                            // 선택되지않은 필수옵션정보
32613                            EC$('select[id^="' + product_option_id + '"][required="true"]').each(function () {
32614                                var bResult = false;
32615                                var sProductOptionId =  EC$(this).attr('id');
32616
32617                                EC$(this).find('option').each(function () {
32618                                    if (EC$(this).val() == sTargetItemCode) {
32619                                        bResult = true;
32620                                    }
32621                                });
32622                                if (bResult === false) {
32623                                    aRequiredFalseOption.push(sProductOptionId);
32624                                }
32625                            });
32626                        }
32627                        // 실제 첫번째 필수누락 옵션 selector
32628                        oExistRequiredSelect = EC$('select[id="' + aRequiredFalseOption[0] + '"][required="true"]');
32629
32630                        // 품절품목과 비교
32631                        EC$('.soldout_option_box_id').each(function () {
32632                            var sTargetItemCode = EC$(this).val();
32633                            for (var i = 0; i < aRequiredFalseOption.length; i++) {
32634                                EC$('select[id="' + aRequiredFalseOption[i] + '"][required="true"] option').each(function () {
32635                                    if (EC$(this).val() == sTargetItemCode) {
32636                                        // 품절 옵션 selector
32637                                        oExistRequiredSelect = EC$(this).parent();
32638                                        sMsg = __('품절된 상품은 구매가 불가능합니다.');
32639                                    }
32640                                });
32641                            }
32642                        });
32643                    }
32644                    // 기존 유효성 검증 메세지
32645                    var sOrginalValidMsg = NEWPRD_ADD_OPTION.checkExistingValidMessage(this.parent.oObject, oValidAddProductCount);
32646                    //추가구성상품의 선택되어있으면서 본상품의 옵션이 선택 안되었을때
32647                    sMsg = (sOrginalValidMsg === false) ? sMsg : sOrginalValidMsg;
32648
32649                    alert(sMsg);
32650                    if (oExistRequiredSelect !== false) {
32651                        oExistRequiredSelect.focus();
32652                    }
32653                    return false;
32654                }
32655            } else {
32656                // 관련상품 체크 확인
32657                if (NEWPRD_ADD_OPTION.checkRelationProduct(this.parent.oObject, this.parent.sType) === false) {
32658                    return false;
32659                }
32660
32661                // 단독구매시 메인상품 품절된 상품일때 메시지 처리
32662                if (NEWPRD_ADD_OPTION.checkSoldOutProductValid(this.parent.oObject) === true) {
32663                    this.parent.UTIL.appendHidden('is_product_sold_out', 'T');
32664                    if (NEWPRD_ADD_OPTION.checkVaildIndividualMsg(
32664oIndividualValidData, this.parent.sType, this.parent.oObject) === false) {
32665                        return false;
32666                    }
32667                }
32668                if (FileOptionManager.checkValidation() === false) {
32669                    return false;
32670                }
32671            }
32672            if (oValidAddProductCount.result === false) {
32673                if (oValidAddProductCount.message !== '') {
32674                    alert(oValidAddProductCount.message);
32675                    oValidAddProductCount.object.focus();
32676                }
32677                return false;
32678            }
32679            if (oValidRelationProductCount.result === false) {
32680                if (oValidRelationProductCount.message !== '') {
32681                    alert(oValidRelationProductCount.message);
32682                    oValidRelationProductCount.object.focus();
32683                }
32684                return false;
32685            }
32686            if (oIndividualValidData.isValidInidual === false) {
32687                // 추가 옵션 체크 (품목기반 추가옵션일때는 폼제출때 검증 불필요)
32688                var oParent = (this.parent.sType === 'funding') ? EC$('.EC-funding-checkbox:checked').parents('.xans-product-funding') : null;
32689                if (NEWPRD_ADD_OPTION.isItemBasedAddOptionType() !== true && checkAddOption(null, oParent) === false) {
32690                    this.parent.oDebug.setMessage('checkAddOption Fail');
32691                    return false;
32692                }
32693            }
32694
32695            if (NEWPRD_ADD_OPTION.checkPerAddInputOption() === false) {
32696                // 품목별 추가 옵션 입력시 체크
32697                return false;
32698            }
32699            return true;
32700        },
32701        isValidAddproduct: function()
32702        {
32703            if (EC$('.add-product-checked:checked').length === 0) {
32704                return true;
32705            }
32706
32707            var aAddProduct = CAFE24.UTIL.parseJSON(add_option_data);
32708            var aItemCode = new Array();
32709            var bCheckValidate = true;
32710            EC$('.add-product-checked:checked').each(function() {
32711                if (bCheckValidate === false) {
32712                    return false;
32713                }
32714                var iProductNum = EC$(this).attr('product-no');
32715                var iQuantity = EC$('#add-product-quantity-'+iProductNum).val();
32716                var aData = aAddProduct[iProductNum];
32717                if (aData.item_code === undefined) {
32718                    if (aData.option_type === 'T') {
32719                        if (aData.item_listing_type === 'S') {
32720                            var aOptionValue = new Array();
32721                            EC$('[id^="addproduct_option_id_'+iProductNum+'"]').each(function() {
32722                                aOptionValue.push(EC$(this).val());
32723                            });
32724                            if (ITEM.isOptionSelected(aOptionValue) === true) {
32725                                sOptionValue = aOptionValue.join('#$%');
32726                                aItemCode.push([CAFE24.UTIL.parseJSON(aData.option_value_mapper)[sOptionValue],iQuantity]);
32727                            } else {
32728                                bCheckValidate = false;
32729                                alert(__('필수 옵션을 선택해주세요.'));
32730                                return false;
32731                            }
32732                        } else {
32733                            var $eItemSelectbox = EC$('[name="addproduct_option_name_'+iProductNum+'"]');
32734
32735                            if (ITEM.isOptionSelected($eItemSelectbox.val()) === true) {
32736                                aItemCode.push([$eItemSelectbox.val(),iQuantity]);
32737                            } else {
32738                                bCheckValidate = false;
32739                                $eItemSelectbox.focus();
32740                                alert(__('필수 옵션을 선택해주세요.'));
32741                                return false;
32742                            }
32743                        }
32744                    } else if (Olnk.isLinkageType(sOptionType) === true) {
32745                        EC$('[id^="addproduct_option_id_'+iProductNum+'"]').each(function() {
32746                            alert(EC$(this).val());
32747                            if (EC$(this).prop('required') === true && ITEM.isOptionSelected(EC$(this).val()) === false) {
32748                                bCheckValidate = false;
32749                                EC$(this).focus();
32750                                alert(__('필수 옵션을 선택해주세요.'));
32751                                return false;
32752                            }
32753
32754                            if (ITEM.isOptionSelected(EC$(this).val()) === true) {
32755                                aItemCode.push([EC$(this).val(),iQuantity]);
32756                            }
32757                        });
32758                    } else {
32759                        EC$('[id^="addproduct_option_id_'+iProductNum+'"]').each(function() {
32760                            if (EC$(this).prop('required') === true && ITEM.isOptionSelected(EC$(this).val()) === false) {
32761                                bCheckValidate = false;
32762                                EC$(this).focus();
32763                                alert(__('필수 옵션을 선택해주세요.'));
32764                                return false;
32765                            }
32766                            if (ITEM.isOptionSelected(EC$(this).val()) === true) {
32767                                aItemCode.push([EC$(this).val(),iQuantity]);
32768                            }
32769                        });
32770                    }
32771                } else {
32772                    aItemCode.push([aData.item_code,iQuantity]);
32773                }
32774            });
32775            if (bCheckValidate === false) {
32776                return false;
32777            }
32778            for (var x = 0; x < aItemCode.length; x++) {
32779                this.UTIL.appendHidden('relation_item[]', aItemCode[x][1]+'||'+aItemCode[x][0]);
32780            }
32781        },
32782        isValidRegularDelivery: function() // 정기 배송
32783        {
32784            if (PRODUCTSUBMIT.isRegularDelivery() === false) {
32785                return true;
32786            }
32787            if (EC_FRONT_JS_CONFIG_SHOP.bIsLogin === false) {
32788                alert(__('AVAILABLE.AFTER.LOGIN', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32789                btn_action_move_url('/member/login.html');
32790                return false;
32791            }
32792
32793            var sSubscriptionCycleValue = PRODUCTSUBMIT.getRegularSelectedValue();
32794
32795            if (sSubscriptionCycleValue === '') {
32796                alert(__('REGULAR.SHIPPING.CYCLE', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32797                return false;
32798            }
32799
32800            if (EC$('#EC_regular_count option:selected').val() === '') {
32801                alert(__('REGULAR.SHIPPING.COUNT', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32802                return false;
32803            }
32804
32805            return true;
32806        },
32807        isValidFunding: function()
32808        {
32809            if (PRODUCTSUBMIT.sType !== 'funding') {
32810                return true;
32811            }
32812
32813            if (CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isSelectComposition() === false) {
32814                alert(__('PRODUCT.CONFIGURATION', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32815                return false;
32816            }
32817
32818            if (CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isItemSelected() === false) {
32819                alert(__('SELECT.REQUIRED.OPTION.001', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32820                return false;
32821            }
32822
32823            // 최소 주문 수량
32824            if (CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isValidQuantity() === false) {
32825                alert(__('APPLY.RESERVATION', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32826                return false;
32827            }
32828
32829            return true;
32830        },
32831        isExclusivePurchaseOnly: function()
32832        {
32833            if (PRODUCTSUBMIT.isExclusivePurchaseOnly() === false) {
32834                return true;
32835            }
32836            if (this.parent.sType === 2) {
32837                alert(__('EXCLUSIVE.PURCHASE.ONLY.CANNOT', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32838                return false;
32839            }
32840
32841            if (this.parent.sType === 1 && EC$('input[class^="option_add_box_"][name="basket_add_product[]"]').length > 0) {
32842                alert(__('EXCLUSIVE.PURCHASE.ONLY.BUY', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32843                return false;
32844            }
32845            return true;
32846        },
32847        /**
32848         * 예약상품 데이터 검증
32849         * @returns bool 예약상품 검증 통과할경우 true
32850         */
32851        isValidReservationItemData: function()
32852        {
32853            return true;
32854        },
32855        isValidCulturalTax: function()
32856        {
32857            // 본상품 : 문화비와 정기배송 둘다 대상이면 차단
32858            if (PRODUCTSUBMIT.isValidCulturalTax() === true && PRODUCTSUBMIT.isRegularDelivery() === true) {
32859                alert(__('THROUGH.REGULAR.DELIVERY', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32860                return false;
32861            }
32862
32863            // 추가구성상품 : 본품과 추가구성상품이 문화비와 일반이 섞여 있으면 차단
32864            if (EC$('input[class^="option_add_box_"][name="basket_add_product[]"]').length > 0) {
32865                const sCulturalTaxType = SHOP_FRONT_PRODUCT_CULTURAL_TAX.getIsCulturalTax();
32866                const isConsistent = EC$('input[class^="option_add_box_"][name="basket_add_product[]"]').toArray().every(input => {
32867                    const addProductValue = $(input).val();
32868                    const addProductArray = addProductValue.split('||');
32869                    const sAddCulturalTaxType = addProductArray.length > 12 ? addProductArray[12] : '';
32870                    if (sAddCulturalTaxType === 'T' || sAddCulturalTaxType === 'F') {
32871                        return sCulturalTaxType === sAddCulturalTaxType;
32872                    }
32873                    return true; // 'T' 또는 'F'가 아닐 경우 검증하지 않음
32874                });
32875
32876                if (!isConsistent) {
32877                    alert(__('CANNOT.PURCHASED.TOGETHER', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
32878                    return false;
32879                }
32880            }
32881
32882            return true;
32883        }
32884    },
32885    getRegularSelectedValue : function()
32886    {
32887        var sSubscriptionCycleAttrName = '.EC_regular_cycle_count';
32888        if (EC$('.EC_regular_cycle_count').prop('type') === 'select-one') {
32889            sSubscriptionCycleAttrName = '.EC_regular_cycle_count > option:selected';
32890        } else if (EC$('.EC_regular_cycle_count:checked').length > 0) {
32891            sSubscriptionCycleAttrName = '.EC_regular_cycle_count:checked';
32892        }
32893
32894        var sSubscriptionCycleValue = '';
32895        if (EC$('.EC_regular_cycle_count').length === 0) {
32896            sSubscriptionCycleValue = parent.EC$(sSubscriptionCycleAttrName).val();
32897        } else {
32898            sSubscriptionCycleValue = EC$(sSubscriptionCycleAttrName).val();
32899        }
32900
32901        return sSubscriptionCycleValue;
32902    },
32903    getRegularCountSelectedValue : function()
32904    {
32905        var sSubscriptionCountAttrName = '.EC_regular_count';
32906        if (EC$('.EC_regular_count').prop('type') === 'select-one') {
32907            sSubscriptionCountAttrName = '.EC_regular_count > option:selected';
32908        } else if (EC$('.EC_regular_count:checked').length > 0) {
32909            sSubscriptionCountAttrName = '.EC_regular_count:checked';
32910        }
32911
32912        var sSubscriptionCountValue = '';
32913        if (EC$('.EC_regular_count').length === 0) {
32914            sSubscriptionCountValue = parent.EC$(sSubscriptionCountAttrName).val();
32915        } else {
32916            sSubscriptionCountValue = EC$(sSubscriptionCountAttrName).val();
32917        }
32918
32919        return sSubscriptionCountValue;
32920    },
32921    UTIL: {
32922        oData: {},
32923        initialize: function(oParent)
32924        {
32925            this.parent = oParent;
32926            return this;
32927        },
32928        appendHidden: function(mParam)
32929        {
32930            if (typeof(mParam) === 'string' && arguments.length === 2) {
32931                this.setHidden(arguments[0], arguments[1]);
32932            }
32933            if (typeof(mParam) === 'object') {
32934                for (var sName in mParam) {
32935                    if (Array.isArray(mParam[sName]) === true) {
32936                        EC$.each(mParam[sName], function(iIndex, mValue) {
32937                            PRODUCTSUBMIT.UTIL.setHidden(sName+'[]', mValue);
32938                        });
32939                        continue;
32940                    }
32941                    this.setHidden(sName, mParam[sName]);
32942                }
32943            }
32944        },
32945        prependHidden: function(mParam)
32946        {
32947            if (typeof(mParam) === 'string' && arguments.length === 2) {
32948                this.setHidden(arguments[0], arguments[1], 'prepend');
32949            }
32950            if (typeof(mParam) === 'object') {
32951                for (var sName in mParam) {
32952                    if (Array.isArray(mParam[sName]) === true) {
32953                        EC$.each(mParam[sName], function(iIndex, mValue) {
32954                            PRODUCTSUBMIT.UTIL.setHidden(sName+'[]', mValue, 'prepend');
32955                        });
32956                        continue;
32957                    }
32958                    this.setHidden(sName, mParam[sName], 'prepend');
32959                }
32960            }
32961        },
32962        setHidden: function(sName, sValue, sAppendType)
32963        {
32964            //ECHOSTING-9736
32965            if (typeof(sValue) === "string" && (sName == "option_add[]" || sName.indexOf("item_option_add") === 0)) {
32966                 sValue = sValue.replace(/'/g, '\\&#039;');
32967            }
32968
32969            // 타입이 string 일때 연산시 단일 따움표 " ' " 문자를 " ` " 액센트 문자로 치환하여 깨짐을 방지
32970            var oAttribute = {
32971                'name': sName,
32972                'type': 'hidden',
32973                'class': 'basket-hidden'
32974            };
32975            if (sAppendType === 'prepend') {
32976                this.parent.oForm.prepend(EC$('<input>').attr(oAttribute).val(sValue));
32977
32978            } else {
32979                this.parent.oForm.append(EC$('<input>').attr(oAttribute).val(sValue));
32980
32981            }
32982        },
32983        setData: function(sKey, mValue)
32984        {
32985            this.oData[sKey] = mValue;
32986            return true;
32987        },
32988        getData: function(sKey)
32989        {
32990            return this.oData[sKey];
32991        }
32992    },
32993    DEBUG: {
32994        aMessage: [],
32995        initialize: function(oParent)
32996        {
32997            this.aMessage = [];
32998            this.parent = oParent;
32999            this.bIsDebugConsoleOut = this.parent.bIsDebugConsoleOut;
33000            return this;
33001        },
33002        setInfo: function()
33003        {
33004            if (this.bIsDebugConsoleOut === false) {
33005                return;
33006            }
33007            if (window.console) {
33008                var aMessage = [];
33009                for (var i = 0; i < arguments.length; i++) {
33010                    aMessage.push(arguments[i]);
33011                }
33012                console.info(aMessage.join(''));
33013            }
33014        },
33015        setMessage: function(sMessage)
33016        {
33017            this.aMessage.push(sMessage);
33018            this.setConsoleDebug();
33019            throw 'USER_DEFINED_ERROR';
33020        },
33021        setConsoleDebug: function()
33022        {
33023            if (this.bIsDebugConsoleOut === false) {
33024                return;
33025            }
33026            if (window.console) {
33027                console.warn(this.aMessage.join('\n'));
33028            }
33029        },
33030        messageOut: function(mError, sLabel)
33031        {
33032            if (this.bIsDebugConsoleOut === true && mError !== 'USER_DEFINED_ERROR') {
33033                console.error(mError);
33034            }
33035
33036            if (typeof EC_JET === 'object' && EC_JET.hasOwnProperty('message') === true) {
33037                var oErrorMessage = mError === 'USER_DEFINED_ERROR' ? this.aMessage : mError;
33038                EC_JET.message(oErrorMessage, sLabel);
33039            }
33040
33041            return false;
33042        }
33043    },
33044    setLoginMovePage: function(sUrl , sMessage)
33045    {
33046        if (sMessage !== '') {
33047            alert(sMessage);
33048        }
33049        if (typeof(sUrl) === 'undefined') {
33050            sUrl = '/member/login.html';
33051        }
33052        var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
33053        sUrl += '?returnUrl=' + encodeURIComponent(oTarget.location.pathname + oTarget.location.search);
33054        oTarget.location.href = sUrl;
33055    },
33056    isRegularDelivery : function()
33057    {
33058        if (EC_FRONT_JS_CONFIG_SHOP.bRegularConfig === false) {
33059            return false;
33060        }
33061        if (EC$('.EC_regular_delivery:checked').length === 0 || EC$('.EC_regular_delivery:checked').val() === 'F') {
33062            return false;
33063        }
33064
33065        return true;
33066    },
33067
33068    sendLoginPage : function(iPrdNo, sBuyLimitType) {
33069        var sLoginPage = '/member/login.html?returnUrl=' + encodeURIComponent(location.pathname + location.search);
33070        var oTarget = document;
33071        // 분류페이지에서 옵션선택레이어에서 선택시에는 부모페이지를 로그인페이지로 이동
33072        if (parent.$('#capp-shop-new-product-optionselect-layer').length > 0 || parent.$('#modalContent').length > 0) {
33073            oTarget = parent.top.document;
33074        }
33075
33076        if (typeof iPrdNo !== 'undefined') {
33077            EC$.ajax({
33078                url: '/exec/front/Shop/ApiProductPurchase',
33079                type: 'get',
33080                async: false,
33081                data: {
33082                    'product_no': iPrdNo
33083                },
33084                dataType: 'json',
33085                success: function(oReturn) {
33086                    if (oReturn.bIsSuccess === true) {
33087                        //상품정보가 변경되어 구매할 수 없습니다.
33088                        alert(sprintf(__('INFORMATION.CHANGED', 'SHOP.JS.FRONT.NEW.PRODUCT.SET'), ''));
33089                        return;
33090                    }
33091
33092                    alert(oReturn.sMessage);
33093                    if (oReturn.bReplaceLoginPage === true) {
33094                        oTarget.location.href = sLoginPage;
33095                    }
33096                }
33097            });
33098            return;
33099        } else if (typeof iProductNo !== 'undefined') {
33100            if (typeof CAFE24.FRONT_JS_CONFIG_SHOP  !== 'undefined' && CAFE24.FRONT_JS_CONFIG_SHOP.hasOwnProperty('aProductPurchaseInfo_' + iProductNo) === true) {
33101                var oPurchaseInfo = CAFE24.FRONT_JS_CONFIG_SHOP['aProductPurchaseInfo_' + iProductNo];
33102                alert(oPurchaseInfo.sMessage);
33103                if (oPurchaseInfo.bReplaceLoginPage === true) {
33104                    oTarget.location.href = sLoginPage;
33105                }
33106                return;
33107            }
33108        }
33109
33110        sMsg = __('CAN.PURCHASE.GROUP', 'GLOBAL.BUY.LIMIT');
33111        if (sBuyLimitType == 'O' || sBuyLimitType == 'D') {
33112            sMsg = __('CAN.PURCHASE.MEMBER.USE', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION');
33113        }
33114        alert(sMsg);
33115    },
33116    isExclusivePurchaseOnly: function()
33117    {
33118        if (EC_FRONT_JS_CONFIG_SHOP.bIsExclusivePurchaseOnly === false) {
33119            return false;
33120        }
33121        return true;
33122    },
33123    isValidCulturalTax: function()
33124    {
33125        return SHOP_FRONT_PRODUCT_CULTURAL_TAX.getIsCulturalTax() === 'T';
33126    }
33127};
33128
33129// 상품 옵션 id
33130var product_option_id = 'product_option_id';
33131
33132// 추가옵션 id
33133var add_option_id = 'add_option_';
33134
33135// 선택된 상품만 주문하기
33136var sIsPrdOverride = 'F';
33137
33138//모바일로 접속했는지
33139var bIsMobile = false;
33140
33141//분리형 세트상품의 구성상품(품절)에서 SMS 재입고 알림 팝업 호출
33142function set_sms_restock(iProductNo) {
33143    if (typeof(iProductNo) === 'undefined') {
33144        return;
33145    }
33146
33147    // 모바일 접속 및 레이어 팝업 여부 확인
33148    if (typeof(EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER) !== 'undefined') {
33149        var sParam = 'product_no=' + iProductNo;
33150        if (EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.createSmsRestockLayerDisplayResult(sParam) === true) {
33151            return;
33152        }
33153    }
33154
33155    window.open('/product/sms_restock.html?product_no=' + iProductNo, 'sms_restock', 200, 100, 459, 490);
33156}
33157
33158// 예약 주문 체크
33159var STOCKTAKINGCHECKRESERVE = {
33160    checkReserve: function()
33161    {
33162        var bIsReserveStatus = EC$('.option_box_id').filter('[data-item-reserved="R"]').length > 0;
33163        // 예약 주문이 있는경우
33164        if (bIsReserveStatus === true) {
33165            alert(__('ITEMS.MAY.SHIPPED', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
33166        }
33167        return false;
33168    }
33169};
33170
33171
33172/**
33173 * sType - 1:바로구매, 2:장바구니,naver_checkout:네이버 페이 form.submit - 바로구매, 장바구니, 관심상품
33174 *         app: app 에서 필요한 장바구니데이터 "aAppBasketInsertItem" return
33175 * TODO 바로구매 - 장바구니에 넣으면서 주문한 상품 하나만 주문하기
33176 *
33177 * @param string sAction action url
33178 */
33179function product_submit(sType, sAction, oObj, aInfo, defer)
33180{
33181    // jwt에서 중복호출이 되어야하여 패스할 수 있도록 예외처리
33182    if (sType !== 'direct_buy' && unsetOnclikAction(oObj) === false) {
33183        return;
33184    }
33185    PRODUCTSUBMIT.initialize(sType, sAction, oObj, aInfo);
33186
33187    if (PRODUCTSUBMIT.isValidRequest() === false) {
33188        setTimeout(function() {
33189            setOnclikAction();
33190        }, 1000);
33191        return {
33192            'result': false,
33193            'code': 422,
33194            'message': 'fail valid request'
33195        }
33196    }
33197
33198    if (PRODUCTSUBMIT.setBasketForm() === false) {
33199        setTimeout(function() {
33200            setOnclikAction();
33201        }, 1000);
33202        return {
33203            'result': false,
33204            'code': 422,
33205            'message': 'fail basket form'
33206        }
33207    }
33208
33209    PRODUCTSUBMIT.setBasketAjax(defer);
33210
33211    setTimeout(function() {
33212        setOnclikAction();
33213    }, 1000);
33214
33215    return;
33216}
33217
33218/**
33219 * 선택한상품만 주문하기
33220 *
33221 * @param string sOptionParam 옵션 파람값
33222 * @param int iProductNo 상품번호
33223 * @param string sSelectedItemByEtype 상품연동형의 경우 입력되는 선택된옵션 json 데이터
33224 */
33225function selectbuy_action(sOptionParam, iProductNo, sSelectedItemByEtype)
33226{
33227    var sAddParam = '';
33228    if (typeof sSelectedItemByEtype !== 'undefined' && sSelectedItemByEtype != '') {
33229        sAddParam = '&' + sSelectedItemByEtype;
33230    }
33231
33232    var sChRefDataParam = '';
33233    if (CAFE24.getChRefData()) {
33234        sChRefDataParam = '&ch_ref=' + CAFE24.getChRefData();
33235    }
33236
33237    var sUrl = '/exec/front/order/basket/?command=select_prdcnt&product_no=' + iProductNo + '&option_type=' + (window['option_type'] || '') + sOptionParam + sAddParam + sChRefDataParam;
33238
33239    EC$.ajax(
33240    {
33241        url: sUrl,
33242        dataType: 'json',
33243        async: false,
33244        success: function(data)
33245        {
33246            if (data.result > 0) {
33247                //1+N상품이라면
33248                if (typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE !== 'undefined' && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNo) === true) {
33249                    sIsPrdOverride = 'F';
33250                } else {
33251                    if (confirm(CAFE24.SHOP_FRONT_NEW_PRODUCT_COMMON.getOverridePurchaseMessage(data.result)) === false) {
33252                        sIsPrdOverride = 'T';
33253                    }
33254                }
33255            }
33256        }
33257    });
33258}
33259var sOnclick = null;
33260var oThisSelector = null;
33261
33262/**
33263 * 중복클릭 방지를 위한 onclick off 처리
33264 * @param object oObject 클릭된 오브젝트
33265 * @returns {boolean}
33266 */
33267function unsetOnclikAction(oObject)
33268{
33269    oSelector = EC$(oObject);
33270    // 중복클릭 제어
33271    if (sOnclick !== null) {
33272        //alert(__('처리중입니다. 잠시만 기다려주세요.'));
33273        return false;
33274    }
33275    // onclick 속성 제거후 임시 저장
33276    sOnclick = oSelector.attr('onclick');
33277    oSelector.attr('onclick', '');
33278    oThisSelector = oSelector;
33279
33280    return true;
33281
33282}
33283/**
33284 * 중복클릭 onclick 복구
33285 */
33286function setOnclikAction()
33287{
33288    // 제거된 onclick 속성 복구
33289    if (sOnclick !== null) {
33290        oThisSelector.attr('onclick', sOnclick);
33291    }
33292    sOnclick = null;
33293    oThisSelector = null;
33294}
33295/**
33296 * 장바구니 담기(카테고리)
33297 *
33298 * @param int iProductNo 상품번호
33299 * @param int iCategoryNo 카테고리 번호
33300 * @param int iDisplayGroup display_group
33301 * @param string sBasketType 무이자 설정(A0000:일반, A0001:무이자)
33302 * @param string iQuantity 주문수량
33303 * @param string sItemCode 아이템코드
33304 * @param string sDelvType 배송타입
33305 */
33306function category_add_basket(iProductNo, iCategoryNo, iDisplayGroup, sBasketType, bList, iQuantity, sItemCode, sDelvType, sProductMaxType, sProductMax)
33307{
33308    if (unsetOnclikAction(this.event.target) === false) {
33309        return;
33310    }
33311    if (iQuantity == undefined) {
33312        iQuantity = 1;
33313    }
33314    if (typeof EC_FRONT_JS_CONFIG_SHOP  !== 'undefined' && typeof EC_FRONT_JS_CONFIG_SHOP.aExclusivePurchase !== 'undefined' && EC_FRONT_JS_CONFIG_SHOP.aExclusivePurchase !== null) {
33315        if (EC_FRONT_JS_CONFIG_SHOP.aExclusivePurchase.hasOwnProperty(iProductNo) === true) {
33316            if (EC_FRONT_JS_CONFIG_SHOP.aExclusivePurchase[iProductNo]) {
33317                alert(__('EXCLUSIVE.PURCHASE.ONLY.CANNOT', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION'));
33318                setTimeout(function() {
33319                    setOnclikAction();
33320                }, 1000);
33321                return false;
33322            }
33323        }
33324    }
33325    if (bList == true) {
33326        try {
33327            if (typeof EC_ListAction === 'object') {
33328                EC_ListAction.getOptionSelect(iProductNo, iCategoryNo, iDisplayGroup, sBasketType);
33329            }
33330        } catch (e) {
33331            PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.category_add_basket');
33332            alert(__('장바구니에 담을 수 없습니다.'));
33333            setTimeout(function() {
33334                setOnclikAction();
33335            }, 1000);
33336            return false;
33337        }
33338    } else {
33339        var sAction = '/exec/front/order/basket/';
33340        var sData = 'command=add&quantity=' + iQuantity + '&product_no=' + iProductNo + '&main_cate_no=' + iCategoryNo + '&display_group='
33341            + iDisplayGroup + '&basket_type=' + sBasketType + '&delvtype=' + sDelvType + '&product_max_type=' + sProductMaxType + '&product_max=' + sProductMax
33342            + '&iQuantity=' + iQuantity + '&sFrom=category';
33343        // 장바구니 위시리스트인지 여부
33344        if (typeof (basket_page_flag) !== 'undefined' && basket_page_flag == 'T') {
33345            sData = sData + '&basket_page_flag=' + basket_page_flag;
33346        }
33347
33348        action_basket(2, 'category', sAction, sData, sBasketType);
33349    }
33350
33351}
33352
33353/**
33354 * 구매하기
33355 *
33356 * @param int iProductNo 상품번호
33357 * @param int iCategoryNo 카테고리 번호
33358 * @param int iDisplayGroup display_group
33359 * @param string sBasketType 무이자 설정(A0000:일반, A0001:무이자)
33360 * @param string iQuantity 주문수량
33361 */
33362function add_order(iProductNo, iCategoryNo, iDisplayGroup, sBasketType, iQuantity)
33363{
33364    if (iQuantity == undefined) {
33365        iQuantity = 1;
33366    }
33367
33368    var sAction = '/exec/front/order/basket/';
33369    var sData = 'command=add&quantity=' + iQuantity + '&product_no=' + iProductNo + '&main_cate_no=' + iCategoryNo + '&display_group='
33370            + iDisplayGroup + '&basket_type=' + sBasketType;
33371
33372    action_basket(1, 'wishlist', sAction, sData, sBasketType);
33373}
33374
33375/**
33376 * 레이어 생성
33377 *
33378 * @param layerId
33379 * @param sHtml
33380 */
33381function create_layer(layerId, sHtml, oTarget)
33382{
33383    let sChRefData = CAFE24.getChRefData();
33384    //아이프레임일때만 상위객체에 레이어생성
33385    if (oTarget === parent) {
33386        oTarget.EC$('#' + layerId).remove();
33387        oTarget.EC$('body').append(EC$('<div id="' + layerId + '" style="position:absolute; z-index:10001;"></div>'));
33388        oTarget.EC$('#' + layerId).html(sHtml);
33389        oTarget.EC$('#' + layerId).show();
33390
33391        parent.ReferenceCurrencyPrice.init();
33392        //옵션선택 레이어 프레임일 경우 그대로 둘경우 영역에대해 클릭이 안되는부분때문에 삭제처리
33393        if (typeof(bIsOptionSelectFrame) !== 'undefined' && bIsOptionSelectFrame === true) {
33394            parent.CAPP_SHOP_NEW_PRODUCT_OPTIONSELECT.closeOptionCommon();
33395        }
33396    } else {
33397        EC$('#' + layerId).remove();
33398        EC$('<div id="' + layerId + '"></div>').appendTo('body');
33399        EC$('#' + layerId).html(sHtml);
33400        EC$('#' + layerId).show();
33401
33402        ReferenceCurrencyPrice.init();
33403    }
33404
33405    let sBasketUrl = '/order/basket.html?delvtype=' + delvtype;
33406    if (sChRefData !== undefined) {
33407        sBasketUrl += "&ch_ref=" + sChRefData;
33408    }
33409    // set delvtype to basket
33410    try {
33411        EC$(".xans-product-basketadd").find("a[href^='/order/basket.html']").attr("href", sBasketUrl);
33412    } catch (e) {}
33413    try {
33414        EC$(".xans-order-layerbasket").find("a[href='/order/basket.html']").attr("href", sBasketUrl);
33415    } catch (e) {}
33416}
33417
33418/**
33419 * 레이어 위치 조정
33420 *
33421 * @param layerId
33422 */
33423function position_layer(layerId)
33424{
33425    var obj = EC$('#' + layerId);
33426
33427    var x = 0;
33428    var y = 0;
33429    try {
33430        var hWd = parseInt(document.body.clientWidth / 2 + EC$(window).scrollLeft());
33431        var hHt = parseInt(document.body.clientHeight / 2 + EC$(window).scrollTop() / 2);
33432        var hBW = parseInt(obj.width()) / 2;
33433        var hBH = parseInt(hHt - EC$(window).scrollTop());
33434
33435        x = hWd - hBW;
33436        if (x < 0) x = 0;
33437        y = hHt - hBH;
33438        if (y < 0) y = 0;
33439
33440    } catch (e) {}
33441
33442    obj.css(
33443    {
33444        position: 'absolute',
33445        display: 'block',
33446        top: y + "px",
33447        left: x + "px"
33448    });
33449
33450}
33451
33452
33453// 장바구니 담기 처리중인지 체크 - (ECHOSTING-85853, 2013.05.21 by wcchoi)
33454var bIsRunningAddBasket = false;
33455
33456var aAppBasketInsertItem = null; // 장바구니 insert 동작 후, 해당 장바구니 데이터
33457var aCheckoutBasketItem;
33458var bIsCheckoutBasketSet = false; // 체크아웃 결제수단 (kakaopay...) 장바구니 세팅 여부
33459
33460/**
33461 * 장바구니/구매 호출
33462 *
33463 * @param sType
33464 * @param sGroup
33465 * @param sAction
33466 * @param sParam
33467 * @param aBasketType
33468 * @param bNonDuplicateChk
33469 */
33470
33471function action_basket(sType, sGroup, sAction, sParam, sBasketType, bNonDuplicateChk, defer)
33472{
33473    if (bIsRunningAddBasket) {
33474        //alert(__('처리중입니다. 잠시만 기다려주세요.'));
33475        return;
33476    }
33477
33478    // 장바구니 담기에 대해서만 처리
33479    // 중복 체크 안함 이 true가 아닐경우(false나 null)에만 중복체크
33480    if (sType == 2 && bNonDuplicateChk != true) {
33481        if (bIsRunningAddBasket === false) {
33482            bIsRunningAddBasket = true;
33483        }
33484    }
33485
33486    if (sType == 'sms_restock') {
33487        action_sms_restock(sParam);
33488        return;
33489    }
33490
33491    if (sType == 'email_restock') {
33492        action_email_restock();
33493        return;
33494    }
33495
33496    if (sType == 2 && CAFE24.SHOP_FRONT_BASKET_VALID.isBasketProductDuplicateValid(sParam) === false) {
33497        bIsRunningAddBasket = false;
33498        setTimeout(function() {
33499            setOnclikAction();
33500        }, 1000);
33501        return false;
33502    }
33503
33504    // UA 초기화 이슈로 동기호출로 변경 (ECHOSTING-446124)
33505    EC$.ajax({
33506        type: 'POST',
33507        url: sAction,
33508        data: sParam,
33509        async: false,
33510        success: function(data) {
33511
33512            // 바로구매(direct_buy)는 채널 UI 에서도 일반 결과 핸들러(basket_result_action)로 처리한다. (ECHOSTING-625233)
33513            // 채널 결과 핸들러(basket_result_action_channel)에는 directbuy 의 주문서 갱신(setOrderForm→formdirectbuy) 분기가 없어
33514            // 전용디자인 바로구매에서 상품/결제금액이 렌더되지 않기 때문이다.
33515            if (CAFE24.checkChannelUI() === true && sType !== 'direct_buy') {
33516                if (sType == 1) {
33517                    CAFE24_CHANNEL_MANAGE.do(function(options) {
33518                        var defaults = {
33519                            _sType: sType,
33520                            _sGroup: sGroup,
33521                            _data: data,
33522                            _sBasketType: sBasketType,
33523                            _sParam: sParam,
33524                            _defer: defer
33525                        };
33526                        var settings = EC$.extend({}, defaults, options);
33527
33528                        // settings 객체를 사용하여 작업 수행
33529                        basket_result_action_channel(settings._sType, settings._sGroup, settings._data, settings._sBasketType, settings._sParam, settings._defer);
33530                    });
33531
33532                    /*CAFE24_CHANNEL_MANAGE.do(function(_sType = sType, _sGroup = sGroup, _data = data, _sBasketType = sBasketType, _sParam = sParam, _defer = defer) {
33533                        basket_result_action_channel(_sType, _sGroup, _data, _sBasketType, _sParam, _defer);
33534                    });*/
33535                } else {
33536                    basket_result_action_channel(sType, sGroup, data, sBasketType, sParam, defer);
33537                }
33538            } else {
33539                basket_result_action(sType, sGroup, data, sBasketType, sParam, defer);
33540            }
33541
33542            bIsRunningAddBasket = false; // 장바구니 담기 처리 완료
33543
33544            setTimeout(function() {
33545                setOnclikAction();
33546            }, 1000);
33547
33548            // 세션스토리지 BasketProduct 캐시 삭제
33549            EC$(function() {
33550                try {
33551                    CAPP_ASYNC_METHODS.BasketProduct.removeCache();
33552                } catch (e) {
33553                }
33554            });
33555        },
33556        dataType: 'json'
33557    });
33558
33559}
33560
33561/**
33562 * 리스트나 상세에서 장바구니 이후의 액션을 처리하고 싶을 경우 이변수를 파라미터로 지정해줌
33563 */
33564var sProductLink = null;
33565/**
33566 * 장바구니 결과 처리
33567 *
33568 * @param sType
33569 * @param sGroup
33570 * @param aData
33571 * @param sBasketType
33572 * @param sParam
33573 */
33574function basket_result_action(sType, sGroup, aData, sBasketType, sParam, defer)
33575{
33576    if (aData == null) {
33577        return;
33578    }
33579
33580    var sHtml = '';
33581    var bOpener = false;
33582    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
33583    var bIsProgressLink = true;
33584
33585    var oCheckZoomPopUp = {
33586        isPopUp: function()
33587        {
33588            var bIsPopup = false;
33589            if (bIsProgressLink === true || (typeof(sIsPopUpWindow) !== "undefined" && sIsPopUpWindow === "T")) {
33590                if (CAPP_SHOP_FRONT_COMMON_UTIL.isPopupFromThisShopFront() === true) {
33591                    bIsPopup = true;
33592                }
33593            }
33594            return bIsPopup;
33595        }
33596    };
33597
33598    //var oOpener = findMainFrame();
33599    //var sLocation = location;
33600    var bBuyLayer = false;
33601
33602    // 쿠폰적용 가능상품 팝업 -> 상품명 클릭하여 상품상세 진입 -> 바로 구매 시,
33603    // 쿠폰적용 가능상품 팝업이 열려있으면 주문서 페이지로 이동되지 않고, 창이 닫이는 이슈 처리(ECHOSTING-266906)
33604    if (sType == 1 && window.opener !== null && oTarget.couponPopupClose !== undefined) {
33605        bOpener = true;
33606    }
33607
33608    if (aData.result >= 0) {
33609        try {
33610            bBuyLayer = ITEM.setBodyOverFlow(true);
33611        } catch (e) {
33612            PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.basket_result_action');
33613        }
33614
33615        // - insert 된 장바구니 데이터 : aAppBasketInsertItem
33616        if (sType == 'app') {
33617            aAppBasketInsertItem = aData['aBasketProduct'];
33618            defer(aAppBasketInsertItem);
33619            return;
33620        }
33621
33622        if (sType == 'checkout') {
33623            aCheckoutBasketItem = aData['aBasketProduct'];
33624            bIsCheckoutBasketSet = true;
33625            return;
33626        }
33627
33628        // 네이버 페이
33629        if (sType == 'naver_checkout') {
33630            var sUrl = '/exec/front/order/navercheckout';
33631
33632            // inflow param from naver common JS to Checkout Service
33633            try {
33634                if (typeof(wcs) === 'object') {
33635                    var inflowParam = wcs.getMileageInfo();
33636                    if (inflowParam != false) {
33637                        sUrl = sUrl + '?naver_inflow_param=' + inflowParam;
33638                    }
33639                }
33640            } catch (e) {}
33641
33642            // ECHOSTING-627626 CA_JS 광고 폼 데이터 동봉 위해 POST 폼 제출로 전환
33643            CAPP_SHOP_FRONT_COMMON_UTIL.submitNaverCheckout(sUrl, oTarget, (is_order_page == 'N' && bIsMobile == false));
33644            return false;
33645        }
33646
33647        // 배송유형
33648        var sDelvType = '';
33649        if (typeof(delvtype) !== 'undefined') {
33650            if (typeof(delvtype) === 'object') {
33651                sDelvType = EC$(delvtype).val();
33652            } else {
33653                sDelvType = delvtype;
33654            }
33655        } else if (aData.sDelvType != null) {
33656            sDelvType = aData.sDelvType;
33657        }
33658
33659        if (sType == 1 || sType === 'funding' || sType === 'simple_pay' || sType === 'reservation') { // 바로구매하기
33660            var sSimplePayType = '';
33661            if (sType === 'simple_pay' && aData.sPaymethod.length > 0) {
33662                sSimplePayType = '&paymethod=' + aData.sPaymethod;
33663            }
33664
33665            if (aData.isLogin == 'T') { // 회원
33666                var sUrl = "/order/orderform.html?basket_type=" + sBasketType + "&delvtype=" + sDelvType + sSimplePayType;
33667
33668                // URL 에 ch_ref 파라미터 추가
33669                if (CAFE24.hasChRef()) {
33670                    // 이미 ch_ref가 포함되어 있는지 확인
33671                    var urlObj = new URL(sUrl, window.location.origin);
33672                    if (!urlObj.searchParams.has('ch_ref')) {
33673                        sUrl = CAFE24.attachChRef(sUrl);
33674                    }
33675                }
33676
33677                if (bOpener === true) {
33678                    // 쿠폰적용 가능상품 팝업이 열려있을 때, 팝업이 아닌 현재 페이지(상품상세)가 주문서 페이지로 이동되도록 처리(ECHOSTING-266906)
33679                    self.location.href = sUrl;
33680                } else {
33681                    oTarget.location.href = sUrl;
33682                }
33683            } else { // 비회원
33684                sUrl = '/member/login.html?noMember=1&returnUrl=' + encodeURIComponent('/order/orderform.html?basket_type=' + sBasketType + "&delvtype=" + sDelvType + sSimplePayType);
33685                sUrl += '&delvtype=' + sDelvType;
33686
33687                // URL 에 ch_ref 파라미터 추가
33688                if (CAFE24.hasChRef()) {
33689                    // 이미 ch_ref가 포함되어 있는지 확인
33690                    var urlObj = new URL(sUrl, window.location.origin);
33691                    if (!urlObj.searchParams.has('ch_ref')) {
33692                        sUrl = CAFE24.attachChRef(sUrl);
33693                    }
33694                }
33695
33696                oTarget.location.href = sUrl;
33697            }
33698        } else if (sType === 'direct_buy') {
33699            CAFE24.SHOP_FRONT_ORDERFORM_DIRECTBUY.proc.setOrderForm(TotalAddSale.getDirectBuyParam());
33700            return;
33701        } else { // 장바구니담기
33702            var oData = CAFE24.PLUSAPP_BRIDGE.unserialize(sParam);
33703            CAFE24.PLUSAPP_BRIDGE.addBasket(oData);
33704            if (typeof CAFE24.KAKAO_PIXEL_BRIDGE !== 'undefined') {
33705                CAFE24.KAKAO_PIXEL_BRIDGE.addBasket(oData['product_no']);
33706            }
33707
33708            CAFE24.EC_SHOP_FRONT_BASKET_ACTION_EVENT.trigger(sParam, aData);
33709
33710            var oBasketEventData = CAFE24.EC_SHOP_FRONT_BASKET_ACTION_EVENT.getEventData();
33711            parent.postMessage({event_type: 'add_cart_success', basket_event_data: oBasketEventData}, window.parent.origin);
33712
33713            if (sGroup == 'detail') {
33714                if (mobileWeb === true) {
33715                    if (typeof (basket_page_flag) !== 'undefined' && basket_page_flag == 'T') {
33716                        oTarget.reload();
33717                        return;
33718                    }
33719                }
33720
33721                var oSearch = /basket.html/g;
33722                //레이어가 뜨는 설정이라면 페이지이동을 하지 않지만
33723                //레이어가 뜨어라고 확대보기팝업이라면 페이지 이동
33724
33725                if (typeof(aData.isDisplayBasket) !== "undefined" && aData.isDisplayBasket == 'T' && oSearch.test(window.location.pathname) == false) {
33726                    if ((typeof(aData.isDisplayLayerBasket) !== "undefined" && aData.isDisplayLayerBasket == 'T') && (typeof(aData.isBasketPopup) !== "undefined" && aData.isBasketPopup == 'T')) {
33727                        layer_basket2(sDelvType, oTarget);
33728                    } else {
33729                        //ECQAINT-14010 Merge이슈 : oTarget이 정상
33730                        layer_basket(sDelvType, oTarget);
33731                    }
33732
33733                    bIsProgressLink = false;
33734                }
33735
33736                //확인 레이어설정이 아니거나 확대보기 팝업페이지라면 페이지이동
33737                if (oCheckZoomPopUp.isPopUp() === true || bIsProgressLink === true) {
33738                    var sBasketUrl = "/order/basket.html?" + "&delvtype=" + sDelvType;
33739                    if (CAFE24.getChRefData() !== undefined) {
33740                        sBasketUrl += "&ch_ref=" + CAFE24.getChRefData();
33741                    }
33742                    oTarget.location.href = sBasketUrl;
33743                }
33744            } else {
33745                // from으로 위시리스트에서 요청한건지 판단.
33746                var bIsFromWishlist = false;
33747                if (typeof(aData.from) !== "undefined" && aData.from == "wishlist") {
33748                    bIsFromWishlist = true;
33749                }
33750
33751                // 장바구니 위시리스트인지 여부
33752                if (typeof (basket_page_flag) !== 'undefined' && basket_page_flag == 'T' || bIsFromWishlist == true) {
33753                    oTarget.reload();
33754                    return;
33755                }
33756                if (typeof(aData.isDisplayBasket) !== "undefined" && aData.isDisplayBasket === 'T') {
33757                    if ((typeof(aData.isDisplayLayerBasket) !== "undefined" && aData.isDisplayLayerBasket == 'T') && (typeof(aData.isBasketPopup) !== "undefined" && aData.isBasketPopup == 'T')) {
33758                        layer_basket2(sDelvType, oTarget);
33759                    } else {
33760                        layer_basket(sDelvType, oTarget);
33761                    }
33762                } else {
33763                    location.href = "/order/basket.html?" + "&delvtype=" + sDelvType;
33764                }
33765            }
33766        }
33767    } else {
33768        var msg = aData.alertMSG.replace('\\n', '\n');
33769
33770        // 디코딩 하기전에 이미 인코딩 된 '\n' 문자를 실제 개행문자로 변환
33771        // 목록에서 호출될 경우에는 인코딩 되지 않은 '\n' 문자 그대로 넘어오므로 추가 처리
33772        msg = msg.replace(/%5Cn|\\n/g, '%0A');
33773
33774        try {
33775            msg = decodeURIComponent(msg);
33776        } catch (err) {
33777            msg = unescape(msg);
33778        }
33779
33780        alert(msg);
33781
33782        if (aData.result == -111 && sProductLink !== null) {
33783            oTarget.href = '/product/detail.html?' + sProductLink;
33784        }
33785        if (aData.result == -101 || aData.result == -103) {
33786
33787
33788            sUrl = '/member/login.html?noMember=1&returnUrl=' + encodeURIComponent(oTarget.location.pathname + oTarget.location.search);
33789            oTarget.location.href = sUrl;
33790        }
33791
33792        if (aData.result == -113) {
33793            if (typeof(delvtype) !== 'undefined') {
33794                if (typeof(delvtype) === 'object') {
33795                    sDelvTypeForMove = EC$(delvtype).val();
33796                } else {
33797                    sDelvTypeForMove = delvtype;
33798                }
33799                oTarget.location.href = "/order/basket.html?" + "&delvtype=" + sDelvTypeForMove;
33800            } else {
33801                oTarget.location.href = "/order/basket.html";
33802            }
33803        }
33804    }
33805
33806    // ECHOSTING-130826 대응, 쿠폰적용상품 리스트에서 옵션상품(뉴옵션)담기 처리시, 화면이 자동으로 닫히지 않아 예외처리 추가
33807    if (oTarget.couponPopupClose !== undefined) {
33808        oTarget.couponPopupClose();
33809    }
33810    if (oCheckZoomPopUp.isPopUp() === true && bOpener === false) {
33811        self.close();
33812    } else {
33813        // ECHOSTING-130826 대응, 특정 화면에서 장바구니에 상품 담기 시 async 가 동작하지 않아,
33814        // 장바구니 담기처리 후처리 구간에 async 강제 실행추가
33815        // 쿠폰 적용 가능상품 리스트 에서 장바구니 담기시, 여기서 실행할 경우 js 오류가 발생하여, 함수 상단에 별도 처리 추가
33816        if (typeof(oTarget) !== 'undefined' && typeof(oTarget.CAPP_ASYNC_METHODS) !== 'undefined') {
33817            oTarget.CAPP_ASYNC_METHODS.init();
33818        } else {
33819            CAPP_ASYNC_METHODS.init();
33820        }
33821    }
33822}
33823
33824/**
33825 * 장바구니 결과 처리 by channel
33826 *
33827 * @param sType
33828 * @param sGroup
33829 * @param aData
33830 * @param sBasketType
33831 * @param sParam
33832 */
33833function basket_result_action_channel(sType, sGroup, aData, sBasketType, sParam, defer)
33834{
33835    if (aData == null) {
33836        return;
33837    }
33838
33839    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
33840    var sBasketPageUrl = 'basket.html';
33841    var sOrderFormPageUrl = 'orderform.html';
33842
33843    if (aData.result >= 0) {
33844        // 배송유형
33845        var sDelvType = '';
33846        if (typeof(delvtype) !== 'undefined') {
33847            if (typeof(delvtype) === 'object') {
33848                sDelvType = EC$(delvtype).val();
33849            } else {
33850                sDelvType = delvtype;
33851            }
33852        } else if (aData.sDelvType != null) {
33853            sDelvType = aData.sDelvType;
33854        }
33855
33856        var sPrefixUrl = EC_ROUTE.isBaseDomain(location.href) === true ? '/shop' + EC_SDE_SHOP_NUM : '';
33857        if (sType == 1) { // 바로구매하기
33858            oTarget.location.href = CAFE24.attachChRef(sPrefixUrl + '/order/' + sOrderFormPageUrl + '?basket_type=' + sBasketType + '&delvtype=' + sDelvType);
33859        } else { // 장바구니담기
33860            CAFE24.EC_SHOP_FRONT_BASKET_ACTION_EVENT.trigger(sParam, aData);
33861            var oBasketEventData = CAFE24.EC_SHOP_FRONT_BASKET_ACTION_EVENT.getEventData();
33862            $("#basketAddLayer a.move").each(function() {
33863                $(this).attr("href", CAFE24.attachChRef(sPrefixUrl + '/order/' + sBasketPageUrl + '?delvtype=' + sDelvType));
33864            });
33865
33866            $('#basketAddLayer').addClass('on');
33867
33868            parent.postMessage({event_type: 'add_cart_success', basket_event_data: oBasketEventData}, window.parent.origin);
33869        }
33870    } else {
33871        var msg = aData.alertMSG.replace('\\n', '\n');
33872
33873        // 디코딩 하기전에 이미 인코딩 된 '\n' 문자를 실제 개행문자로 변환
33874        // 목록에서 호출될 경우에는 인코딩 되지 않은 '\n' 문자 그대로 넘어오므로 추가 처리
33875        msg = msg.replace(/%5Cn|\\n/g, '%0A');
33876
33877        try {
33878            msg = decodeURIComponent(msg);
33879        } catch (err) {
33880            msg = unescape(msg);
33881        }
33882
33883        alert(msg);
33884    }
33885}
33886
33887function layer_basket(sDelvType, oTarget)
33888{
33889    var oProductName = null;
33890    if (typeof(product_name) !== 'undefined') {
33891        oProductName = {'product_name': product_name};
33892    }
33893    EC$('.xans-product-basketoption').remove();
33894    EC$.get('/product/add_basket.html?delvtype='+sDelvType, oProductName, function(sHtml)
33895        {
33896            sHtml = sHtml.replace(/<script.*?ind-script\/optimizer.php.*?<\/script>/g, '');
33897            // scirpt를 제거하면서 document.ready의 Async 모듈이 실행안되서 강제로 실행함
33898            CAPP_ASYNC_METHODS.init();
33899            create_layer('confirmLayer', sHtml, oTarget);
33900        });
33901}
33902
33903function layer_basket2(sDelvType, oTarget)
33904{
33905    EC$('.xans-order-layerbasket').remove();
33906    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
33907    var sUrl = '/product/add_basket2.html?delvtype=' + sDelvType + '&layerbasket=T';
33908
33909    // URL 에 ch_ref 파라미터 추가
33910    if (CAFE24.hasChRef()) {
33911        // 이미 ch_ref가 포함되어 있는지 확인
33912        var urlObj = new URL(sUrl, window.location.origin);
33913        if (!urlObj.searchParams.has('ch_ref')) {
33914            sUrl = CAFE24.attachChRef(sUrl);
33915        }
33916    }
33917
33918    EC$.get(sUrl, '', function(sHtml)
33919    {
33920        sHtml = sHtml.replace(/<script.*?ind-script\/optimizer.php.*?<\/script>/g, '');
33921
33922        // 장바구니 link에 ch_ref 파라미터 추가
33923        var chRefData = null;
33924        if (typeof CAFE24 !== 'undefined' && CAFE24.getChRefData && CAFE24.getChRefData()) {
33925            chRefData = CAFE24.getChRefData();
33926        } else {
33927            chRefData = $(':input[name="ch_ref"]').val();
33928        }
33929
33930        if (chRefData) {
33931            sHtml = sHtml.replace(
33932                /href\s*=\s*["']\/order\/basket\.html(?:\?([^"']*))?["']/g,
33933                function(match, existingQuery) {
33934                    let newUrl = '/order/basket.html';
33935
33936                    if (existingQuery) {
33937                        // 기존 쿼리스트링에서 ch_ref 제거 및 정리
33938                        const cleanQuery = existingQuery
33939                            .replace(/[?&]ch_ref=[^&]*/g, '')
33940                            .replace(/(^&)|(&$)/g, '');
33941
33942                        // 새로운 쿼리스트링 구성
33943                        const queryParams = cleanQuery
33944                            ? `${cleanQuery}&ch_ref=${encodeURIComponent(chRefData)}`
33945                            : `ch_ref=${encodeURIComponent(chRefData)}`;
33946
33947                        newUrl += `?${queryParams}`;
33948                    } else {
33949                        newUrl += `?ch_ref=${encodeURIComponent(chRefData)}`;
33950                    }
33951
33952                    return `href="${newUrl}"`;
33953                }
33954            );
33955        }
33956
33957        //scirpt를 제거하면서 document.ready의 Async 모듈이 실행안되서 강제로 실행함
33958        CAPP_ASYNC_METHODS.init();
33959        create_layer('confirmLayer', sHtml, oTarget);
33960    });
33961}
33962
33963function layer_wishlist(oTarget)
33964{
33965    EC$('.layerWish').remove();
33966    EC$.get('/product/layer_wish.html','' ,function(sHtml)
33967    {
33968        sHtml = sHtml.replace(/<script.*?ind-script\/optimizer.php.*?<\/script>/g, '');
33969        create_layer('confirmLayer', sHtml, oTarget);
33970    });
33971}
33972
33973function go_basket()
33974{
33975    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
33976    oTarget.location.href = '/order/basket.html';
33977    if (CAPP_SHOP_FRONT_COMMON_UTIL.isPopupFromThisShopFront() === true) {
33978        self.close();
33979    }
33980}
33981
33982function move_basket_page()
33983{
33984    var sLocation = location;
33985    try {
33986
33987        sLocation = ITEM.setBodyOverFlow(location);
33988    } catch (e) {
33989        PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.move_basket_page');
33990    }
33991
33992    sLocation.href = '/order/basket.html';
33993}
33994
33995/**
33996 * 이미지 확대보기 (상품상세 버튼)
33997 */
33998function go_detail()
33999{
34000    var sUrl = '/product/detail.html?product_no=' + iProductNo;
34001    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
34002
34003    if (typeof(iCategoryNo) !== 'undefined') {
34004        sUrl += '&cate_no='+iCategoryNo;
34005    }
34006
34007    if (typeof(iDisplayGroup) !== 'undefined') {
34008        sUrl += '&display_group='+iDisplayGroup;
34009    }
34010
34011    oTarget.location.href = sUrl;
34012    if (CAPP_SHOP_FRONT_COMMON_UTIL.isPopupFromThisShopFront() === true) {
34013        self.close();
34014    }
34015}
34016
34017/**
34018 * 바로구매하기/장바구니담기 Action  - 판매정보 > 구매제한
34019 */
34020function check_action_nologin(sBuyLimitType)
34021{
34022    sMsg = __('CAN.PURCHASE.GROUP', 'GLOBAL.BUY.LIMIT');
34023    if (sBuyLimitType == 'O' || sBuyLimitType == 'D') {
34024        sMsg = __('CAN.PURCHASE.MEMBER.USE', 'SHOP.JS.FRONT.NEW.PRODUCT.ACTION');
34025    }
34026    alert(sMsg);
34027    return false;
34028}
34029
34030/**
34031 * 바로구매하기 Action  - 불량회원 구매제한
34032 */
34033function check_action_block(sMsg)
34034{
34035    if (sMsg == '') {
34036        sMsg = __('쇼핑몰 관리자가 구매 제한을 설정하여 구매하실 수 없습니다.');
34037    }
34038    alert(sMsg);
34039}
34040
34041/**
34042 * 관심상품 등록 - 로그인하지 않았을 경우
34043 */
34044function add_wishlist_nologin(sUrl)
34045{
34046    PRODUCTSUBMIT.setLoginMovePage(sUrl , __('로그인 후 관심상품 등록을 해주세요.'));
34047
34048}
34049
34050/**
34051 * 바로구매하기 / 장바구니 담기 / 관심상품 등록 시 url 이동에 사용하는 메소드
34052 * @param sUrl 이동할 주소
34053 */
34054function btn_action_move_url(sUrl)
34055{
34056    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
34057
34058    sLocation = ITEM.setBodyOverFlow(location);
34059
34060    sUrl += '?returnUrl=' + encodeURIComponent(oTarget.location.pathname + oTarget.location.search);
34061    oTarget.location.replace(sUrl);
34062}
34063
34064/**
34065 * return_url 없이 url 이동에 사용하는 메소드
34066 * @param sUrl 이동할 주소
34067 */
34068function btn_action_move_no_return_url(sUrl)
34069{
34070    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
34071    oTarget.location.replace(sUrl);
34072}
34073
34074/**
34075 * 관심상품 등록 - 파라미터 생성
34076 * @param bIsUseOptionSelect 장바구니옵션선택 새모듈 사용여부(basket_option.html, Product_OptionSelectLayer)
34077 */
34078function add_wishlist(sMode, bIsUseOptionSelect)
34079{
34080    var sUrl = '//' + location.hostname;
34081    sUrl += '/exec/front/Product/Wishlist/';
34082    var param = location.search.substring(location.search.indexOf('?') + 1);
34083    sParam = param + '&command=add' + '&from=wish_icon';
34084    sParam += '&referer=' + encodeURIComponent('//' + location.hostname + location.pathname + location.search);
34085
34086    add_wishlist_action(sUrl, sParam, sMode, bIsUseOptionSelect);
34087}
34088
34089var bWishlistSave = false;
34090/**
34091 * @param bIsUseOptionSelect 장바구니옵션선택 새모듈 사용여부(basket_option.html, Product_OptionSelectLayer)
34092 */
34093function add_wishlist_action(sAction, sParam, sMode, bIsUseOptionSelect)
34094{
34095    //연동형 옵션 여부
34096    var bIsOlinkOption = Olnk.isLinkageType(sOptionType);
34097    if (bWishlistSave === true) {
34098        return false;
34099    }
34100    var required_msg = __('품목을 선택해 주세요.');
34101    if (sOptionType !== 'F') {
34102        var aItemCode = ITEM.getWishItemCode();
34103    } else {
34104        var aItemCode = null;
34105    }
34106    var sSelectedItemByEtype = '';
34107
34108    var frm = EC$('#frm_image_zoom');
34109    frm.find(":hidden").remove();
34110    frm.attr('method', 'POST');
34111    frm.attr('action', '/' + sAction);
34112
34113    if (bIsOlinkOption === true) {
34114        if (isNewProductSkin() === false) {
34115            sItemCode = Olnk.getSelectedItemForWishOldSkin(sProductCode, EC$('[id^="product_option_id"]'));
34116
34117            if (sItemCode !== false) {
34118                frm.append(getInputHidden('selected_item_by_etype[]', EC$.toJSON(sItemCode)));
34119                //sSelectedItemByEtype += 'selected_item_by_etype[]='+EC$.toJSON(sItemCode) + '&';
34120                aItemCode.push(sItemCode);
34121            }
34122
34123        } else {
34124            EC$('.soldout_option_box_id,.option_box_id').each(function(i) {
34125                sItemCode = Olnk.getSelectedItemForWish(sProductCode, EC$(this));
34126                if (sItemCode.bCheckNum === false) {
34127                    sItemCode = Olnk.getProductAllSelected(sProductCode , EC$(this) , 1);
34128                }
34129                frm.append(getInputHidden('selected_item_by_etype[]', EC$.toJSON(sItemCode)));
34130                //sSelectedItemByEtype += 'selected_item_by_etype[]='+EC$.toJSON(sItemCode) + '&';
34131                aItemCode.push(sItemCode);
34132            });
34133
34134            // 전부 선택인 경우 필요값 생성한다.
34135            if (sSelectedItemByEtype === '') {
34136                iQuantity = (buy_unit >= product_min ? buy_unit : product_min);
34137                aItemValueNo = Olnk.getProductAllSelected(sProductCode , EC$('[id^="product_option_id"]') , 1);
34138                if (aItemValueNo !== false) {
34139                    frm.append(getInputHidden('selected_item_by_etype[]', EC$.toJSON(aItemValueNo)));
34140                    //sSelectedItemByEtype += 'selected_item_by_etype[]='+EC$.toJSON(aItemValueNo) + '&';
34141                    aItemCode.push(aItemValueNo);
34142                }
34143            }
34144
34145            NEWPRD_ADD_OPTION.setItemAddOptionName(frm);
34146            var iOptionBoxLength = EC$('.option_box_id').length - 1;
34147            EC$('.option_box_id').each(function(i) {
34148
34149                iQuantity = EC$('#' + EC$(this).attr('id').replace('id','quantity')).val();
34150                _aItemValueNo = Olnk.getSelectedItemForBasket(sProductCode, EC$(this), iQuantity);
34151
34152                if (_aItemValueNo.bCheckNum === false) { // 옵션박스는 있지만 값이 선택이 안된경우
34153                    _aItemValueNo = Olnk.getProductAllSelected(sProductCode , EC$(this) , iQuantity);
34154                }
34155
34156                var oItem = EC$('[name="item_code[]"]').eq(i);
34157                var sItemCode = sProductCode + '000A_' + i;
34158
34159                //품목별 추가옵션 셋팅
34160                var ePerAddOption = EC$('.option_products .option').eq(i).find(".input_addoption:visible");
34161                if (ePerAddOption.length > 0) { // 옵션 박스안에서 개별 입력시
34162                    sItemCode = Olnk.getCustomOptionItemCode(sProductCode, iOptionBoxLength, i);
34163                    NEWPRD_ADD_OPTION.setItemPerAddOptionData(sItemCode, ePerAddOption, frm);
34164                } else {
34165                    var sItemAddOption = NEWPRD_ADD_OPTION.getAddOptionValue(oItem.attr('data-item-add-option'));
34166                    NEWPRD_ADD_OPTION.setItemAddOption(sItemCode, sItemAddOption, frm);
34167                }
34168            });
34169
34170
34171        }
34172
34173        if (bIsUseOptionSelect !== true && (/^\*+$/.test(aItemCode) === true || aItemCode == '')) {
34174            alert(required_msg);
34175            return false;
34176        }
34177    } else {
34178        if (isNewProductSkin() === true) {
34179            //품목별 추가옵션 이름 셋팅
34180            NEWPRD_ADD_OPTION.setItemAddOptionName(frm);
34181
34182            EC$('[name="quantity_opt[]"][id^="option_box"]').each(function(i) {
34183
34184                var oItem = EC$('[name="item_code[]"]').eq(i);
34185                var sItemCode = oItem.val();
34186
34187                //품목별 추가옵션 셋팅
34188                var ePerAddOption = EC$('.option_product').eq(i).find(".input_addoption:visible");
34189                if (ePerAddOption.length > 0) { // 옵션 박스안에서 개별 입력시
34190                    NEWPRD_ADD_OPTION.setItemPerAddOptionData(sItemCode, ePerAddOption, frm);
34191                } else {
34192                    var sItemAddOption = NEWPRD_ADD_OPTION.getAddOptionValue(oItem.attr('data-item-add-option'));
34193                    NEWPRD_ADD_OPTION.setItemAddOption(sItemCode, sItemAddOption, frm);
34194                }
34195
34196            });
34197
34198        }
34199    }
34200
34201    if (aItemCode === false && bIsUseOptionSelect !== true) {
34202        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.setLayer(iProductNo, iCategoryNo, 'normal') === true) {
34203            return;
34204        }
34205        alert(required_msg);
34206        return false;
34207    }
34208
34209
34210    if (aItemCode !== null) {
34211        var sItemCode = '';
34212        var aTemp = [];
34213
34214        if (Olnk.isLinkageType(sOptionType) === true) {
34215            frm.append(getInputHidden('selected_item[]', '000A'));
34216            //sParam = sParam + '&' + 'selected_item[]=000A&' + sSelectedItemByEtype;
34217        } else {
34218            for (var x in aItemCode) {
34219                try {
34220                    var opt_id = aItemCode[x].substr(aItemCode[x].length-4, aItemCode[x].length);
34221                    frm.append(getInputHidden('selected_item[]', opt_id));
34222                    //aTemp.push('selected_item[]='+opt_id);
34223                } catch (e) {
34224                    PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.add_wishlist_action');
34225                }
34226            }
34227        }
34228    }
34229
34230    // URLSearchParams 객체를 사용하여 파라미터 파싱
34231    const params = new URLSearchParams(sParam);
34232    if (!params.has('product_no') && (typeof(iProductNo) !== 'undefined' && iProductNo !== '' && iProductNo !== null)) {
34233        frm.append(getInputHidden('product_no', iProductNo));
34234    }
34235    if (!params.has('cate_no') && (typeof(iCategoryNo) !== 'undefined' && iCategoryNo !== '' && iCategoryNo !== null)) {
34236        frm.append(getInputHidden('cate_no', iCategoryNo));
34237    }
34238    frm.append(getInputHidden('option_type', sOptionType));
34239    //sParam = sParam + '&product_no='+iProductNo;
34240
34241
34242    // 추가 옵션 체크 (품목기반 추가옵션일때는 폼제출때 검증 불필요)
34243    //뉴모듈사용시에는 체크안함
34244    if (bIsUseOptionSelect !== true && (NEWPRD_ADD_OPTION.isItemBasedAddOptionType() !== true && checkAddOption() === false)) {
34245        return false;
34246    }
34247
34248    // 추가옵션
34249    var aAddOptionStr = new Array();
34250    var aAddOptionRow = new Array();
34251    if (add_option_name) {
34252        for (var i=0; i<add_option_name.length; i++) {
34253            if (add_option_name[i] !== '' && EC$('#' + add_option_id + i).length > 0) {
34254                aAddOptionRow.push(add_option_name[i] + '*' + EC$('#' + add_option_id + i).val());
34255            }
34256        }
34257    }
34258    aAddOptionStr.push(aAddOptionRow);
34259
34260    // 단일 상품의 개별 추가 입력 옵션 처리
34261    if (has_option === 'F' && typeof add_option_input !== 'undefined') {
34262        NEWPRD_ADD_OPTION.addItem(ITEM.getItemCode()[0]);
34263        var iAddOptionIndex = NEWPRD_ADD_OPTION.getLastIndex();
34264        for (var x in add_option_input) {
34265            if (add_option_input.hasOwnProperty(x) === true) {
34266                NEWPRD_ADD_OPTION.addCustomOption(iAddOptionIndex, {
34267                    type: 'text',
34268                    value: EC$('#' + add_option_input[x].id).val(),
34269                    info: add_option_input[x].info
34270                }, 'input');
34271            }
34272        }
34273    }
34274
34275    frm.append(getInputHidden('add_option', aAddOptionStr.join('|')));
34276    //sParam += '&add_option=' + encodeURIComponent(aAddOptionStr.join('|'));
34277
34278    // 파일첨부 옵션 유효성 체크
34279    if (bIsUseOptionSelect !== true && FileOptionManager.checkValidation() === false) return;
34280
34281    bWishlistSave = true;
34282
34283    // 파일첨부 옵션의 파일업로드가 없을 경우 바로 관심상품 넣기
34284    if (FileOptionManager.existsFileUpload() === false) {
34285        NEWPRD_ADD_OPTION.setItemPerAddOptionForm(frm);
34286        sParam = sParam + '&' + frm.serialize();
34287        add_wishlist_request(sParam, sMode);
34288    // 파일첨부 옵션의 파일업로드가 있으면
34289    } else {
34290        FileOptionManager.upload(function(mResult) {
34291            // 파일업로드 실패
34292            if (mResult===false) {
34293                bWishlistSave = false;
34294                return false;
34295            }
34296
34297            // 파일업로드 성공
34298            for (var sId in mResult) {
34299                // 해당 품목에 파일 첨부 옵션 항목 추가
34300                NEWPRD_ADD_OPTION.pushFileList(sId, mResult);
34301                frm.append(getInputHidden(sId, FileOptionManager.encode(mResult[sId])));
34302                //sParam += '&'+sId+'='+FileOptionManager.encode(mResult[sId]);
34303            }
34304
34305
34306            NEWPRD_ADD_OPTION.setItemPerAddOptionForm(frm);
34307
34308            sParam = sParam + '&' + frm.serialize();
34309            add_wishlist_request(sParam, sMode);
34310        });
34311    }
34312}
34313
34314function add_wishlist_request(sParam, sMode)
34315{
34316    var sUrl = '/exec/front/Product/Wishlist/';
34317
34318    EC$.post(
34319        sUrl,
34320        sParam,
34321        function(data) {
34322            if (sMode != 'back') {
34323                add_wishlist_result(data);
34324            }
34325            bWishlistSave = false;
34326        },
34327        'json');
34328}
34329
34330function add_wishlist_result(aData, aPrdData)
34331{
34332    var oTarget = CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame();
34333    var agent = navigator.userAgent.toLowerCase();
34334
34335    if (aData == null) return;
34336    //새로운 모듈 사용시에는 중복되어있어도 처리된것으로 간주함.. 왜 그렇게하는지는 이해불가
34337    if (aData.result == 'SUCCESS' || (aData.bIsUseOptionSelect === true && aData.result === 'NO_TARGET')) {
34338
34339        bBuyLayer = ITEM.setBodyOverFlow(true);
34340
34341        if (typeof iProductNo !== 'undefined') {
34342            var iSendProductNo = iProductNo;
34343        } else if (typeof aPrdData !== 'undefined') {
34344            var iSendProductNo = aPrdData.product_no;
34345        }
34346
34347        if (iSendProductNo) {
34348            CAFE24.PLUSAPP_BRIDGE.addWishList(iSendProductNo);
34349            if (typeof CAFE24.KAKAO_PIXEL_BRIDGE !== 'undefined') {
34350                CAFE24.KAKAO_PIXEL_BRIDGE.addWishList(iSendProductNo);
34351            }
34352        }
34353
34354        if (CAPP_ASYNC_METHODS.hasOwnProperty('WishList') === true && typeof iProductNo !== 'undefined') {
34355            // 관심상품 추가시 sessionStorage 추가
34356            CAPP_ASYNC_METHODS.WishList.setSessionStorageItem(iProductNo, aData.command);
34357        }
34358
34359        if (CAPP_ASYNC_METHODS.hasOwnProperty('Wishcount') === true) {
34360            CAPP_ASYNC_METHODS.Wishcount.restoreCache();
34361            CAPP_ASYNC_METHODS.Wishcount.execute();
34362        }
34363
34364        if (aData.confirm == 'T') {
34365            layer_wishlist(CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame());
34366            return;
34367        }
34368
34369        if ($('.ec-product-listwishicon').attr('icon_status') === 'off') {
34370            CAPP_PRODUCT_LIST_WISHICON.getResultWishIconAjax(aData, $('.ec-product-listwishicon'));
34371        }
34372        alert(__('관심상품으로 등록되었습니다.'));
34373    } else if (aData.result == 'ERROR') {
34374        alert(__('실패하였습니다.'));
34375    } else if (aData.result == 'NOT_LOGIN') {
34376        alert(__('회원 로그인 후 이용하실 수 있습니다.'));
34377    } else if (aData.result == 'INVALID_REQUEST') {
34378        alert(__('파라미터가 잘못되었습니다.'));
34379    } else if (aData.result == 'NO_TARGET') {
34380        alert(__('이미 등록되어 있습니다.'));
34381    } else if (aData.result == 'INVALID_PRODUCT') {
34382        alert(__('파라미터가 잘못되었습니다.'));
34383    }
34384}
34385
34386/**
34387* 추가된 함수
34388* 해당 value값을 받아 replace 처리
34389* @param string sValue value
34390* @return string replace된 sValue
34391*/
34392function replaceCheck(sName,sValue)
34393{
34394   //ECHOSTING-9736
34395   if (typeof(sValue) === "string" && (sName == "option_add[]" || sName.indexOf("item_option_add") === 0)) {
34396        sValue = sValue.replace(/'/g, '\\&#039;');
34397   }
34398   // 타입이 string 일때 연산시 단일 따움표 " ' " 문자를 " ` " 액센트 문자로 치환하여 깨짐을 방지
34399   return sValue;
34400}
34401
34402
34403/**
34404 * name, value값을 받아 input hidden 태그 반환
34405 *
34406 * @param string sName name
34407 * @param string sValue value
34408 * @return string input hidden 태그
34409 */
34410function getInputHidden(sName, sValue)
34411{
34412    sValue = replaceCheck(sName,sValue); // 추가된 부분 (replaceCheck 함수 호출)
34413    return EC$('<input>').attr({'type': 'hidden', 'name': sName}).val(sValue);
34414}
34415
34416
34417/**
34418 * 필수옵션이 선택되었는지 체크
34419 *
34420 * @return bool 필수옵션이 선택되었다면 true, 아니면 false 반환
34421 */
34422function checkOptionRequired(sReq)
34423{
34424    var bResult = true;
34425    // 옵션이 없다면 필수값 체크는 필요없음.
34426    if (has_option === 'F') {
34427        return bResult;
34428    }
34429    var sTargetOptionId = product_option_id;
34430    if (sReq != null) {
34431        sTargetOptionId = sReq;
34432    }
34433
34434    if (option_type === 'F') {
34435        // 단독구성
34436        var iOptionCount = EC$('select[id^="' + sTargetOptionId + '"][required="true"]').length;
34437        if (iOptionCount > 0) {
34438            if (ITEM.getItemCode() === false) {
34439                bResult = false;
34440                return false;
34441            }
34442
34443            var aRequiredOption = new Object();
34444            var aItemCodeList = ITEM.getItemCode();
34445            // 필수 옵션정보와 선택한 옵션 정보 비교
34446            for (var i=0; i<aItemCodeList.length; i++) {
34447                var sTargetItemCode = aItemCodeList[i];
34448                EC$('select[id^="' + sTargetOptionId + '"][required="true"] option').each(function() {
34449                    if (EC$(this).val() == sTargetItemCode) {
34450                        var sProductOptionId = EC$(this).parent().attr('id');
34451                        aRequiredOption[sProductOptionId] = true;
34452                    }
34453                });
34454
34455            }
34456            // 필수옵션별 개수보다 선택한 옵션개수가 적을경우 리턴
34457            if (iOptionCount > Object.size(aRequiredOption)) {
34458                bResult = false;
34459                return bResult;
34460            }
34461        }
34462    } else {
34463        if (Olnk.isLinkageType(sOptionType) === true) {
34464            if (isNewProductSkin() === false) {
34465                EC$('select[id^="' + product_option_id + '"][required="true"]').each(function() {
34466                    var sel = parseInt(EC$(this).val());
34467
34468                    if (isNaN(sel) === true) {
34469                        EC$(this).focus();
34470                        bResult = false;
34471                        return false;
34472                    }
34473                });
34474                // 추가 구매 check
34475                EC$('.' + EC$.data(document, 'multiple_option_select_class')).each(function(i)
34476                {
34477                    if (EC$(this).prop('required') === true) {
34478                        var sel = parseInt(EC$(this).val());
34479
34480                        if (isNaN(sel) === true) {
34481                            EC$(this).focus();
34482                            bResult = false;
34483                            return false;
34484                        }
34485                    }
34486                });
34487            } else { // 연동형 사용중이면서 뉴스킨
34488                var aItemCodeList = ITEM.getItemCode();
34489                if (aItemCodeList === false) {
34490                    bResult = false;
34491                    return false;
34492                }
34493                // 연동형 옵션의 버튼 사용중이지만 선택된 품목이 없는 경우 , 뉴스킨에서만 동작해야 함.
34494                if (Olnk.getOptionPushbutton(EC$('#option_push_button')) === true && EC$('.option_box_id').length === 0) {
34495                    bResult = false;
34496                    return false;
34497                }
34498            }
34499            return bResult;
34500        }
34501        if (ITEM.getItemCode() === false) {
34502            bResult = false;
34503            return false;
34504        }
34505        // 조합구성
34506        if (item_listing_type == 'S') {
34507            // 분리선택형
34508            var eTarget = CAFE24.UTIL.parseJSON(option_value_mapper);
34509            for (var x in eTarget) {
34510                if (ITEM.getItemCode().indexOf(eTarget[x]) > -1) {
34511                    bResult = true;
34512                    break;
34513                } else {
34514                    bResult = false;
34515                }
34516            }
34517            if (bResult === false) {
34518                bResult = false;
34519                return false;
34520            }
34521        } else {
34522            EC$('select[id^="' + product_option_id + '"][required="true"]').each(function() {
34523                var eTarget = EC$(this).find('option[value!="*"][value!="**"]');
34524                bResult = false;
34525                eTarget.each(function() {
34526                    if (ITEM.getItemCode().indexOf(EC$(this).val()) > -1) {
34527                        bResult = true;
34528                        return false;
34529                    }
34530                });
34531                if (bResult === false) {
34532                    return false;
34533                }
34534            });
34535        }
34536    }
34537
34538    return bResult;
34539}
34540
34541/**
34542 * 추가 옵션 입력값 체크
34543 *
34544 * @return bool 모든 추가옵션에 값이 입력되었다면 true, 아니면 false
34545 *
34546 */
34547/**
34548 * 추가 입력 옵션의 값 체크
34549 * @param string sReq 셀렉터를 기본값 이외로 사용할 경우
34550 * @param object oParent 전체 인풋이 아닌 특정 객체 하위의 엘리먼트만 검사할경우
34551 * @returns {boolean}
34552 */
34553function checkAddOption(sReq, oParent)
34554{
34555    var sAddOptionField = add_option_id;
34556
34557    var sAddOptionSelector = '[id^="' + sAddOptionField + '"]:not(.input_peraddoption)';
34558    if (sReq != null) {
34559        sAddOptionField = sReq;
34560        sAddOptionSelector = '[id="' + sAddOptionField + '"]:not(.input_peraddoption)';
34561    }
34562    var oTargetElement = EC$(sAddOptionSelector);
34563    if (oParent !== null && typeof(oParent) !== 'undefined') {
34564        oTargetElement = oParent.find(sAddOptionSelector);
34565    }
34566
34567    return NEWPRD_ADD_OPTION.validateAddOptionForm(oTargetElement);
34568}
34569
34570/**
34571 * 수량 가져오기
34572 *
34573 * @return mixed 정상적인 수량이면 수량(integer) 반환, 아니면 false 반환
34574 */
34575function getQuantity()
34576{
34577    // 뉴상품인데 디자인이 수정안됐을 수 있다.
34578    if (isNewProductSkin() === false) {
34579        iQuantity = parseInt(EC$(quantity_id).val(),10);
34580    } else {
34581        if (has_option == 'T') {
34582            var iQuantity = 0;
34583
34584            if (Olnk.isLinkageType(sOptionType) === true) {
34585                iQuantity = parseInt(EC$(quantity_id).val(),10);
34586                return iQuantity;
34587            }
34588
34589            EC$('[name="quantity_opt[]"]').each(function() {
34590                iQuantity = iQuantity + parseInt(EC$(this).val(),10);
34591            });
34592        } else {
34593            var iQuantity = parseInt(EC$(quantity_id).val().replace(/^[\s]+|[\s]+$/g,'').match(/[\d\-]+/),10);
34594            if (isNaN(iQuantity) === true || EC$(quantity_id).val() == '' || EC$(quantity_id).val().indexOf('.') > 0) {
34595                return false;
34596            }
34597        }
34598
34599    }
34600
34601    return iQuantity;
34602}
34603
34604/**
34605 * 수량 체크
34606 *
34607 * @return mixed 올바른 수량이면 수량을, 아니면 false
34608 */
34609function checkQuantity()
34610{
34611    // 수량 가져오기
34612    var iQuantity = getQuantity();
34613
34614    if (isNewProductSkin() === false) {
34615        if (iQuantity === false) return false;
34616
34617        // 구스킨의 옵션 추가인 경우 수량을 모두 합쳐야 함..하는수 없이 each추가
34618        // 재고 관련도 여기서 하나?
34619        if (Olnk.isLinkageType(option_type) === true) {
34620            var sOptionIdTmp = '';
34621            EC$('select[id^="' + product_option_id + '"]').each(function() {
34622                if (/^\*+$/.test(EC$(this).val()) === false) {
34623                    sOptionIdTmp = EC$(this).val();
34624                    return false;
34625                }
34626            });
34627
34628            EC$('.EC_MultipleOption').each(function(i) {
34629                iQuantity += parseInt(EC$(this).find('.' + EC$.data(document,'multiple_option_quantity_class')).val(),10);
34630            });
34631
34632            if (Olnk.getStockValidate(sOptionIdTmp , iQuantity) === true) {
34633                alert(__('상품의 수량이 재고수량 보다 많습니다.'));
34634                EC$(quantity_id).focus();
34635                return false;
34636            }
34637        }
34638
34639        if (iQuantity < product_min) {
34640            alert(sprintf(__('최소 주문수량은 %s개 입니다.'), product_min));
34641            EC$(quantity_id).focus();
34642            return false;
34643        }
34644        if (iQuantity > product_max && product_max > 0) {
34645            alert(sprintf(__('최대 주문수량은 %s개 입니다.'), product_max));
34646            EC$(quantity_id).focus();
34647            return false;
34648        }
34649
34650    } else {
34651        var bResult = true;
34652        var bSaleMainProduct = false;
34653        var aQuantity = new Array();
34654        var iTotalOuantity = 0;
34655        var iProductMin = product_min;
34656        var iProductMax = product_max;
34657
34658        var sTotalProductSelector = '#totalProducts > table > tbody';
34659        if (CAFE24.checkChannelUI() === true) {
34660            sTotalProductSelector = '#totalProducts > div';
34661        }
34662        EC$(sTotalProductSelector).not('.add_products').find('[name="quantity_opt[]"]').each(function() {
34663            // 본상품 구매여부
34664            bSaleMainProduct = true;
34665            iQuantity = parseInt(EC$(this).val());
34666
34667            var iProductNum = iProductNo;
34668            // 추가 구성상품인 경우 product_min ,  product_max 값은 다른값을 비교해야 함..
34669            if (EC$(this).attr('id').indexOf('add_') > -1) {
34670                iProductMin = EC$('#'+EC$(this).attr('id').replace('quantity','productmin')).val();
34671                iProductMax = EC$('#'+EC$(this).attr('id').replace('quantity','productmax')).val();
34672                var iProductNum = EC$('#'+EC$(this).attr('id').replace('quantity','id')).attr('class').replace('option_add_box_','');
34673            }
34674            if (typeof(aQuantity[iProductNum]) === 'undefined') {
34675                aQuantity[iProductNum] = new Array();
34676            }
34677            aQuantity[iProductNum].push(iQuantity);
34678
34679            // 상품기준의 경우 품목 총합으로 판단
34680            if (order_limit_type !== 'P') {
34681                if (iQuantity < iProductMin) {
34682                    alert(sprintf(__('상품별 최소 주문수량은 %s 입니다.'), iProductMin));
34683                    EC$(quantity_id).focus();
34684                    bResult = false;
34685                    return false;
34686                }
34687                if (iQuantity > iProductMax && iProductMax > 0) {
34688                    alert(sprintf(__('상품별 최대 주문수량은 %s 입니다.'), iProductMax));
34689                    EC$(quantity_id).focus();
34690                    bResult = false;
34691                    return false;
34692                }
34693            }
34694            iTotalOuantity = iTotalOuantity + iQuantity;
34695        });
34696
34697        if (bResult == false) {
34698            return bResult;
34699        }
34700        if (typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE === 'object') {
34701            for (var iProductNum in aQuantity) {
34702                if (aQuantity.hasOwnProperty(iProductNum) === false) {
34703                    continue;
34704                }
34705                if (CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNum) === false) {
34706                    continue;
34707                }
34708
34709                if (CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.isValidQuantity(aQuantity[iProductNum], iProductNum) === false) {
34710                    return false;
34711                }
34712            }
34713        }
34714        // 본상품 없이 구매가능하기때문에 본상품있을떄만 체크
34715        if (bSaleMainProduct === true) {
34716            if (order_limit_type === 'P') {
34717                if (iTotalOuantity < iProductMin) {
34718                    alert(sprintf(__('최소 주문수량은 %s개 입니다.'), iProductMin));
34719                    bResult = false;
34720                    return false;
34721                }
34722                if (iTotalOuantity > iProductMax && iProductMax > 0) {
34723                    alert(sprintf(__('최대 주문수량은 %s개 입니다.'), iProductMax));
34724                    bResult = false;
34725                    return false;
34726                }
34727            }
34728            if (buy_unit_type === 'P') {
34729                if (iTotalOuantity % parseInt(buy_unit, 10) !== 0) {
34730                    alert(sprintf(__('구매 주문단위는 %s개 입니다.'), parseInt(buy_unit, 10)));
34731                    bResult = false;
34732                    return false;
34733                }
34734            }
34735        }
34736        if (EC$('.add_products').find('[name="quantity_opt[]"]').length > 0) {
34737            var aTotalQuantity = {};
34738            EC$('.add_products').find('[name="quantity_opt[]"]').each(function () {
34739                    iQuantity = parseInt(EC$(this).val());
34740                    if (typeof(aTotalQuantity[EC$(this).attr('product-no')]) === 'undefined' || aTotalQuantity[EC$(this).attr('product-no')] < 1) {
34741                        aTotalQuantity[EC$(this).attr('product-no')] = 0;
34742                    }
34743                    aTotalQuantity[EC$(this).attr('product-no')] += parseInt(EC$(this).val(), 10);
34744
34745                }
34746            );
34747
34748            for (var iProductNo in aTotalQuantity) {
34749                var aProductQuantityInfo = ProductAdd.getProductQuantityInfo(iProductNo);
34750
34751                if (aProductQuantityInfo.order_limit_type === 'P') {
34752                    if (aTotalQuantity[iProductNo] < aProductQuantityInfo.product_min) {
34753                        alert(sprintf(__('최소 주문수량은 %s개 입니다.'), aProductQuantityInfo.product_min));
34754                        bResult = false;
34755                        return false;
34756                    }
34757                    if (aTotalQuantity[iProductNo] > aProductQuantityInfo.product_max && aProductQuantityInfo.product_max > 0) {
34758                        alert(sprintf(__('최대 주문수량은 %s개 입니다.'), aProductQuantityInfo.product_max));
34759                        bResult = false;
34760                        return false;
34761                    }
34762                }
34763                if (aProductQuantityInfo.buy_unit_type === 'P') {
34764                    if (aTotalQuantity[iProductNo] % parseInt(aProductQuantityInfo.buy_unit, 10) !== 0) {
34765                        alert(sprintf(__('구매주문단위는 %s개 입니다.'), parseInt(aProductQuantityInfo.buy_unit, 10)));
34766                        bResult = false;
34767                        return false;
34768                    }
34769                }
34770            }
34771        }
34772        if (bResult == false) {
34773            return bResult;
34774        }
34775    }
34776
34777    return iQuantity;
34778}
34779
34780function commify(n)
34781{
34782    var reg = /(^[+-]?\d+)(\d{3})/; // 정규식
34783    n += ''; // 숫자를 문자열로 변환
34784    while (reg.test(n)) {
34785        n = n.replace(reg, '$1' + ',' + '$2');
34786    }
34787    return n;
34788}
34789
34790var isClose = 'T';
34791function optionPreview(obj, sAction, sProductNo, closeType)
34792{
34793    var sPreviewId = 'btn_preview_';
34794    var sUrl = '/product/option_preview.html';
34795    var layerId = EC$('#opt_preview_' + sAction + '_' + sProductNo);
34796
34797    // layerId = action명 + product_no 로 이루어짐 (한 페이지에 다른 종류의 상품리스트가 노출될때 구분 필요)
34798    if (EC$(layerId).length > 0) {
34799        EC$(layerId).show();
34800    } else if (sProductNo != '') {
34801        EC$.post(sUrl, 'product_no=' + sProductNo + '&action=' + sAction, function(result)
34802        {
34803            EC$(obj).after(result.replace(/[<]script( [^ ]+)? src=\"[^>]*>([\s\S]*?)[<]\/script>/g,""));
34804        });
34805    }
34806}
34807
34808function closeOptionPreview(sAction, sProductNo)
34809{
34810    isClose = 'T';
34811    setTimeout("checkOptionPreview('" + sAction + "','" + sProductNo + "')", 150);
34812}
34813
34814function checkOptionPreview(sAction, sProductNo)
34815{
34816    var layerId = EC$('#opt_preview_' + sAction + '_' + sProductNo);
34817    if (isClose == 'T') EC$(layerId).hide();
34818}
34819
34820function openOptionPreview(sAction, sProductNo)
34821{
34822    isClose = 'F';
34823    var layerId = EC$('#opt_preview_' + sAction + '_' + sProductNo);
34824    EC$(layerId).show();
34825
34826    EC$(layerId).mousemouseenter(function()
34827    {
34828        EC$(layerId).show();
34829    }).mouseleave(function()
34830    {
34831        EC$(layerId).hide();
34832    });
34833
34834}
34835
34836/**
34837 * 네이버 페이 주문하기
34838 */
34839function nv_add_basket_1_product()
34840{
34841    bIsMobile = false;
34842
34843    if (_isProc == 'F') {
34844        alert(__("네이버 페이 입점상태를 확인하십시오."));
34845        return;
34846    }
34847
34848    if (typeof(set_option_data) !== 'undefined') {
34849        alert(__('세트상품은 네이버 페이 구매가 불가하오니, 쇼핑몰 바로구매를 이용해주세요. 감사합니다.'));
34850        return;
34851    }
34852
34853    product_submit('naver_checkout', '/exec/front/order/basket/');
34854}
34855
34856/**
34857 * 네이버 페이 찜하기
34858 */
34859function nv_add_basket_2_product()
34860{
34861    if (_isProc == 'F') {
34862        alert(__("네이버 페이 입점상태를 확인하십시오."));
34863        return;
34864    }
34865
34866    window.open("/exec/front/order/navercheckoutwish?product_no=" + iProductNo, "navercheckout_basket",
34867            'scrollbars=yes,status=no,toolbar=no,width=450,height=300');
34868}
34869
34870/**
34871 * 네이버 페이 주문하기
34872 */
34873function nv_add_basket_1_m_product()
34874{
34875    bIsMobile = true;
34876
34877    if (_isProc == 'F') {
34878        alert(__("네이버 페이 입점상태를 확인하십시오."));
34879        return;
34880    }
34881
34882    if (typeof(set_option_data) !== 'undefined') {
34883        alert(__('세트상품은 네이버 페이 구매가 불가하오니, 쇼핑몰 바로구매를 이용해주세요. 감사합니다.'));
34884        return;
34885    }
34886
34887    product_submit('naver_checkout', '/exec/front/order/basket/');
34888}
34889
34890/**
34891 * 네이버 페이 찜하기
34892 */
34893function nv_add_basket_2_m_product()
34894{
34895    if (_isProc == 'F') {
34896        alert(__("네이버 페이 입점상태를 확인하십시오."));
34897        return;
34898    }
34899
34900    window.location.href = "/exec/front/order/navercheckoutwish?product_no=" + iProductNo;
34901    //window.open("/exec/front/order/navercheckoutwish?product_no=" + iProductNo, "navercheckout_basket", 'scrollbars=yes,status=no,toolbar=no,width=450,height=300');
34902}
34903
34904/**
34905 * 옵션 추가 구매시에 같은 옵션을 검사하는 함수
34906 *
34907 * @returns Boolean
34908 */
34909function duplicateOptionCheck()
34910{
34911    var bOptionDuplicate = getOptionDuplicate();
34912    //var bAddOptionDuplicate = getAddOptionDuplicate();
34913
34914    if (bOptionDuplicate !== true) { //}&& bAddOptionDuplicate !== true) {
34915        alert(__('동일한 옵션의 상품이 있습니다.'));
34916        return false;
34917    }
34918
34919    return true;
34920}
34921
34922/**
34923 * 텍스트 인풋 옵션 중복 체크
34924 *
34925 * @returns {Boolean}
34926 */
34927function getAddOptionDuplicate()
34928{
34929    var aOptionRow = new Array();
34930    var iOptionLength = 0;
34931    var aOptionValue = new Array();
34932    var bReturn = true;
34933    // 기본 옵션
34934    EC$('[id^="' + add_option_id + '"]').each(function()
34935    {
34936        aOptionRow.push(EC$(this).val());
34937    });
34938    aOptionValue.push(aOptionRow.join(',@,'));
34939    EC$('.EC_MultipleOption').each(function()
34940    {
34941        aOptionRow = new Array();
34942        EC$(EC$(this).find('.' + EC$.data(document, 'multiple_option_input_class'))).each(function()
34943        {
34944            aOptionRow.push(EC$(this).val());
34945        });
34946        var sOptionRow = aOptionRow.join(',@,');
34947        if (EC$.inArray(sOptionRow, aOptionValue) > -1) {
34948            bReturn = false;
34949            return false;
34950        } else {
34951            aOptionValue.push(sOptionRow);
34952        }
34953    });
34954    return bReturn;
34955}
34956/**
34957 * 일반 셀렉트박스형 옵션 체크 함수
34958 *
34959 * @returns {Boolean}
34960 */
34961function getOptionDuplicate() {
34962    // 선택여부는 이미 선택이 되어 있음
34963    var aOptionId = new Array();
34964    var aOptionValue = new Array();
34965    var aOptionRow = new Array();
34966    var iOptionLength = 0;
34967    // 기본 옵션
34968    EC$('select[id^="' + product_option_id + '"]').each(function (i) {
34969        aOptionValue.push(EC$(this).val());
34970        iOptionLength++;
34971    });
34972    // 추가 구매
34973    EC$('.' + EC$.data(document, 'multiple_option_select_class')).each(function (i) {
34974        aOptionValue.push(EC$(this).val());
34975    });
34976
34977    var aOptionRow = new Array();
34978    for (var x in aOptionValue) {
34979        var sOptionValue = aOptionValue[x];
34980        aOptionRow.push(sOptionValue);
34981        if (x % iOptionLength == iOptionLength - 1) {
34982            var sOptionId = aOptionRow.join('-');
34983
34984            if (EC$.inArray(sOptionId, aOptionId) > -1) {
34985                return false;
34986            }
34987            aOptionId.push(sOptionId);
34988            aOptionRow = new Array();
34989        }
34990    }
34991
34992    return true;
34993}
34994
34995//sms 재입고
34996function action_sms_restock(sParam)
34997{
34998    // 모바일 접속 및 레이어 팝업 여부 확인
34999    if (typeof(EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER) !== 'undefined') {
35000        if (EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.createSmsRestockLayerDisplayResult(sParam) === true) {
35001            return;
35002        }
35003    }
35004
35005    window.open('#none', 'sms_restock' ,'width=459, height=490, scrollbars=yes');
35006    EC$('#frm_image_zoom').attr('target', 'sms_restock');
35007    EC$('#frm_image_zoom').attr('action', '/product/sms_restock.html');
35008    EC$('#frm_image_zoom').submit();
35009}
35010
35011//email 재입고
35012function action_email_restock(iProductNo)
35013{
35014    if (typeof(iProductNo) === 'undefined') {
35015        iProductNo = '';
35016    }
35017    if ((window.navigator.standalone || (window.matchMedia && window.matchMedia('(display-mode: standalone)').matches)) === true) {
35018        window.open('/product/email_restock.html?' + EC$('#frm_image_zoom').serialize(), 'email_restock' ,'width=459, height=490, scrollbars=yes');
35019    } else {
35020        window.open('#none', 'email_restock' ,'width=459, height=490, scrollbars=yes');
35021        EC$('#frm_image_zoom').attr('target', 'email_restock');
35022        EC$('#frm_image_zoom').attr('action', '/product/email_restock.html?product_no' + iProductNo);
35023        EC$('#frm_image_zoom').submit();
35024    }
35025}
35026
35027// 최대 할인쿠폰 다운받기 팝업
35028function popupDcCoupon(product_no, coupon_no, cate_no, opener_url, location)
35029{
35030    var aUrl = [];
35031    if (location === 'Front' || typeof location === 'undefined') {
35032        aUrl.push('product');
35033    }
35034    aUrl.push('coupon_popup.html');
35035    window.open(EC_ROUTE.getPrefixUrl('/' + aUrl.join('/')) + "?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");
35036}
35037
35038/**
35039 * 관련상품 열고 닫기
35040 */
35041function ShowAndHideRelation()
35042{
35043    try {
35044        var sRelation = EC$('ul.mSetPrd').parent();
35045        var sRelationDisp = sRelation.css('display');
35046        if (sRelationDisp === 'none') {
35047            EC$('#setTitle').removeClass('show');
35048            sRelation.show();
35049        } else {
35050            EC$('#setTitle').addClass('show');
35051            sRelation.hide();
35052        }
35053    } catch (e) { }
35054}
35055
35056var ITEM = {
35057    getItemCode: function()
35058    {
35059        var chk_has_opt = '';
35060        try {
35061            chk_has_opt = has_option;
35062        } catch (e) {chk_has_opt = 'T';}
35063
35064        if (chk_has_opt == 'F') {
35065            return [item_code];
35066        } else {
35067            // 필수값 체크
35068            var bRequire = false;
35069            // 옵션이 없음
35070            if (EC$('[id^="product_option_id"]').length < 1) {
35071                return false;
35072            }
35073            EC$('[id^="product_option_id"]').each(function() {
35074                if (EC$(this).prop('required') === true || EC$(this).attr('required') === 'required') {
35075                    bRequire = true;
35076                    return false;
35077                }
35078            });
35079
35080            var aItemCode = [];
35081            if (bRequire === true) {
35082                if (EC$('#totalProducts').length === 0 || (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === false)) {
35083                    sItemCode = this.getOldProductItemCode();
35084                    if (sItemCode !== false) {
35085                        if (typeof(sItemCode) === 'string') {
35086                            aItemCode.push(sItemCode);
35087                        } else {
35088                            aItemCode = sItemCode;
35089                        }
35090                    } else {
35091                        // 옵션이 선택되지 않음
35092                        return false;
35093                    }
35094                } else {
35095                    if (EC$('.option_box_id').length == 0) {
35096                        // 옵션이 선택되지 않음
35097                        return false;
35098                    }
35099                    EC$('.option_box_id').each(function() {
35100                        aItemCode.push(EC$(this).val());
35101                    });
35102                }
35103            }
35104
35105
35106            return aItemCode;
35107        }
35108    },
35109    getWishItemCode: function()
35110    {
35111        var chk_has_opt = '';
35112        try {
35113            chk_has_opt = has_option;
35114        } catch (e) {chk_has_opt = 'T';}
35115
35116        if (chk_has_opt == 'F') {
35117            return [item_code];
35118        } else {
35119            // 필수값 체크
35120            var bRequire = false;
35121            EC$('[id^="product_option_id"]').each(function() {
35122                if (EC$(this).prop('required') === true || EC$(this).attr('required') === 'required') {
35123                    bRequire = true;
35124                    return false;
35125                }
35126            });
35127
35128            var aItemCode = new Array();
35129            if (bRequire === true) {
35130                if (EC$('#totalProducts').length === 0) {
35131                    sItemCode = this.getOldProductItemCode();
35132                    if (sItemCode !== false) {
35133                        if (typeof(sItemCode) === 'string') {
35134                            aItemCode.push(sItemCode);
35135                        } else {
35136                            aItemCode = sItemCode;
35137                        }
35138                    } else {
35139                        // 옵션이 선택되지 않음
35140                        return false;
35141                    }
35142                } else {
35143                    if (EC$('.soldout_option_box_id,.option_box_id').length == 0) {
35144                        // 옵션이 선택되지 않음
35145                        return false;
35146                    }
35147                    EC$('.soldout_option_box_id,.option_box_id').each(function() {
35148                        aItemCode.push(EC$(this).val());
35149                    });
35150                }
35151            }
35152
35153            return aItemCode;
35154        }
35155    },
35156    getOldProductItemCode: function(sSelector)
35157    {
35158        if (sSelector === undefined) {
35159            sSelector = '[id^="product_option_id"]';
35160        }
35161        var sItemCode = null;
35162        // 뉴상품 옵션 선택 구매
35163        if (has_option === 'F') {
35164            // 화면에 있음
35165            sItemCode = item_code;
35166        } else {
35167            if (item_listing_type == 'S') {
35168                var aOptionValue = new Array();
35169                EC$(sSelector).each(function() {
35170                    if (ITEM.isOptionSelected(EC$(this).val()) === true) {
35171                        aOptionValue.push(EC$(this).val());
35172                    }
35173                });
35174
35175                if (option_type === 'T') {
35176                    var aCodeMap = CAFE24.UTIL.parseJSON(option_value_mapper);
35177                    sItemCode = aCodeMap[aOptionValue.join('#$%')];
35178                } else {
35179                    sItemCode = aOptionValue;
35180                }
35181            } else {
35182                sItemCode = EC$(sSelector).val();
35183            }
35184        }
35185
35186        if (sItemCode === undefined) {
35187            return false;
35188        }
35189
35190        return sItemCode;
35191    },
35192    isOptionSelected: function(aOption)
35193    {
35194        var sOptionValue = null;
35195        if (typeof aOption === 'string') {
35196            sOptionValue = aOption;
35197        } else {
35198            if (aOption.length === 0) return false;
35199            sOptionValue = aOption.join('-|');
35200        }
35201
35202        sOptionValue = '-|'+sOptionValue+'-|';
35203        return !(/-\|\*{1,2}-\|/g).test(sOptionValue);
35204    },
35205    setBodyOverFlow: function(sType)
35206    {
35207        var sLocation = location;
35208        var bBuyLayer = false;
35209
35210        //var oReturnData = new Object();
35211        if (CAFE24.SHOP_FRONT_PRODUCT_OPTIONLAYER.isExistLayer(true) === true) {
35212            //parent.EC$('html, body').css('overflowY', 'auto');
35213            closeBuyLayer(false);
35214            sLocation = parent.location;
35215            bBuyLayer = true;
35216        }
35217
35218        //프레임으로 선언된 페이지일경우
35219        if (typeof(bIsOptionSelectFrame) !== 'undefined' && bIsOptionSelectFrame === true) {
35220            sLocation = parent.location;
35221            bBuyLayer = true;
35222        }
35223        /*
35224        oReturnData['sLocation'] = sLocation;
35225        oReturnData['bBuyLayer'] = bBuyLayer;
35226        */
35227
35228        oReturnData = sLocation;
35229
35230        if (typeof(sType) === 'boolean') {
35231            oReturnData = bBuyLayer;
35232        }
35233        return oReturnData;
35234    }
35235};
35236
35237CAFE24.SHOP_FRONT_PRODUCT_RESTOCK = (function() {
35238
35239    return {
35240        isRestock: function(sType) {
35241
35242            if (sType === 'sms_restock') {
35243                return true;
35244            }
35245
35246            if (sType === 'email_restock') {
35247                return true;
35248            }
35249
35250            return false;
35251        },
35252        openRestockEmailPopup: function()
35253        {
35254            product_submit('email_restock');
35255        },
35256        bindOpenRestockEmailPopup: function(product_no)
35257        {
35258            action_email_restock(product_no);
35259
35260        }
35261    };
35262})();
35263
35264var EC_SHOP_FRONT_PRODUCT_RESTOCK = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_RESTOCK');
35265
35266//상세 장바구니 담기확인창에서 스크립트를 중목으로 볼러오는부분을 제거하기위해서 추가
35267//사용자 디자인에서도 basket.js에 있는 함수에 의존적이라서 추가가 안되어있다면 아래 함수들을 실행하도록 함
35268if (typeof(layer_basket_paging) !== 'function') {
35269  //레이어 장바구니 페이징
35270  function layer_basket_paging(page_no)
35271  {
35272      var sUrl = '/product/add_basket2.html?page=' + page_no + '&layerbasket=T';
35273      if (typeof(sBasketDelvType) !== 'undefined') {
35274          sUrl += sUrl + '&delvtype=' + sBasketDelvType;
35275      }
35276
35277      // URL 에 ch_ref 파라미터 추가
35278      if (CAFE24.hasChRef()) {
35279        // 이미 ch_ref가 포함되어 있는지 확인
35280        var urlObj = new URL(sUrl, window.location.origin);
35281        if (!urlObj.searchParams.has('ch_ref')) {
35282            sUrl = CAFE24.attachChRef(sUrl);
35283        }
35284      }
35285
35286      EC$.get(sUrl, '', function(sHtml)
35287      {
35288          sHtml = sHtml.replace(/<script.*?ind-script\/optimizer.php.*?<\/script>/g, '');
35289          EC$('#confirmLayer').html(sHtml);
35290          EC$('#confirmLayer').show();
35291
35292          // set delvtype to basket
35293          try {
35294              EC$(".xans-order-layerbasket").find("a[href='/order/basket.html']").attr("href", "/order/basket.html?delvtype=" + delvtype);
35295          } catch (e) {
35296              PRODUCTSUBMIT.DEBUG.messageOut(e, 'PRODUCT_ACTION.layer_basket_paging');
35297          }
35298          ReferenceCurrencyPrice.init();
35299      });
35300  }
35301}
35302
35303if (typeof(Basket) === 'undefined') {
35304  var Basket = {
35305      orderLayerAll: function(oElem) {
35306          var aParam = {basket_type: 'all_buy'};
35307          var sOrderUrl = EC$(oElem).attr('link-order') || '/order/orderform.html?basket_type='+ aParam.basket_type;
35308
35309          if (sBasketDelvType != "") {
35310              sOrderUrl += '&delvtype=' + sBasketDelvType;
35311          }
35312
35313          // URL 에 ch_ref 파라미터 추가
35314          var sChRef = null;
35315          if (typeof CAFE24 !== 'undefined' && CAFE24.getChRefData && typeof CAFE24.getChRefData === 'function') {
35316              sChRef = CAFE24.getChRefData();
35317          } else {
35318              sChRef = sessionStorage.getItem('ch_ref');
35319          }
35320        
35321          if (sChRef) {
35322              sOrderUrl = sOrderUrl.replace(/[?&]ch_ref=[^&]*/g, '');
35323              var querySeparator = (sOrderUrl.includes('?')) ? '&' : '?';
35324              sOrderUrl += querySeparator + 'ch_ref=' + encodeURIComponent(sChRef);
35325
35326              aParam['ch_ref'] = sChRef;
35327          }
35328
35329          var sLoginUrl = EC$(oElem).attr('link-login') || '/member/login.html';
35330
35331          EC$.post('/exec/front/order/order/', aParam, function(data) {
35332            if (data.result < 0) {
35333                // [ECQAUNIT-75276] 몰 언어 알럿을 선택 언어로 번역 표시 (내부 폴백 포함, CommonUtil은 DispAbstract 공통 로드)
35334                CAPP_SHOP_FRONT_COMMON_UTIL.alertTranslated(data.alertMSG);
35335                return;
35336            }
35337
35338            if (data.isLogin == 'F') { // 비로그인 주문 > 로그인페이지로 이동
35339                sLoginUrl = sLoginUrl + '?noMember=1&returnUrl=' + escape(sOrderUrl);
35340
35341                // URL 에 ch_ref 파라미터 추가
35342                if (CAFE24.hasChRef()) {
35343                  // 이미 ch_ref가 포함되어 있는지 확인
35344                  var urlObj = new URL(sLoginUrl, window.location.origin);
35345                  if (!urlObj.searchParams.has('ch_ref')) {
35346                      sLoginUrl = CAFE24.attachChRef(sLoginUrl);
35347                  }
35348                }
35349
35350                location.href = sLoginUrl;
35351            } else {
35352                // URL 에 ch_ref 파라미터 추가
35353                var sChRef = null;
35354                if (typeof CAFE24 !== 'undefined' && CAFE24.getChRefData && typeof CAFE24.getChRefData === 'function') {
35355                    sChRef = CAFE24.getChRefData();
35356                } else {
35357                    sChRef = sessionStorage.getItem('ch_ref');
35358                }
35359              
35360                if (sChRef) {
35361                    sOrderUrl = sOrderUrl.replace(/[?&]ch_ref=[^&]*/g, '');
35362                    var querySeparator = (sOrderUrl.includes('?')) ? '&' : '?';
35363                    sOrderUrl += querySeparator + 'ch_ref=' + encodeURIComponent(sChRef);
35364                }
35365
35366                location.href = sOrderUrl;
35367            }
35368        }, 'json');
35369      }
35370  };
35371}
35372
35373/**
35374 * 장바구니 유효성 검증 validation
35375 */
35376CAFE24.SHOP_FRONT_BASKET_VALID = {
35377    // 장바구니 상품 중복여부 확인
35378    isBasketProductDuplicateValid: function(sParam) {
35379        var bReturn = true;
35380
35381        EC$.ajax({
35382            url: '/exec/front/order/Basketduplicate/',
35383            type: 'post',
35384            data: sParam,
35385            async: false,
35386            dataType: 'json',
35387            success: function(data) {
35388                if (data.result === true) {
35389                    if (confirm(__('장바구니에 동일한 상품이 있습니다. ' + '\n' + '장바구니에 추가하시겠습니까?')) === false) {
35390                        bReturn = false;
35391                        return false;
35392                    }
35393                }
35394            }
35395        });
35396
35397        return (bReturn !== false);
35398    }
35399};
35400
35401/**
35402 * 카테고리 쿠키정보 세팅
35403 * @param aCookieInfo
35404 */
35405function setCategoryCookie(aCookieInfo)
35406{
35407    // 4차 도메인 대응으로 모바일 대표도메인인 경우 /m 하위 경로로 쿠키 설정
35408    var sPath = EC_ROUTE.getMobile() === true && EC_ROUTE.isBaseDomain() === true ? '/m/product' : '/product';
35409    if (EC$.cookie('ec_category') !== null) {
35410        EC$.cookie('ec_category', null, {'path': sPath});
35411    }
35412
35413    if (aCookieInfo.hasOwnProperty('category_no') === false || aCookieInfo.hasOwnProperty('category_name') === false) {
35414        return;
35415    }
35416
35417    if (typeof aCookieInfo['category_no'] !== 'number' || typeof aCookieInfo['category_name'] !== 'string') {
35418        return;
35419    }
35420
35421    var sCookie = EC$.param(aCookieInfo);
35422    EC$.cookie('ec_category', sCookie, {'path': sPath});
35423}
35424
35425/**
35426 * 자사몰 랜딩 쿠키 세팅
35427 */
35428function setShoppingPayCookie()
35429{
35430    EC$.cookie('ec_provide_shoppingpay', 'T', {'path': '/'});
35431}
35432
35433function setInAppCookie()
35434{
35435    EC$.cookie('co_linktype', 'in_app');
35436}
35437
35438var EC_SHOP_FRONT_BASKET_VALIID = CAFE24.getDeprecatedNamespace('SHOP_FRONT_BASKET_VALID');
35439
35440CAFE24.EC_SHOP_FRONT_BASKET_ACTION_EVENT = (function () {
35441    var sEventName = 'EC_PRODUCT_ACTION_BASKET';
35442    var oParam = {};
35443    var bIsProcess = false;
35444    return {
35445        init: function (iProductNo) {
35446            bIsProcess = true;
35447            oParam = {
35448                mall_id: SHOP.getMallID(),
35449                shop_no: CAFE24.SDE_SHOP_NUM,
35450                product_no: iProductNo,
35451                contents: [],
35452                currency: CAFE24.SHOP_CURRENCY_INFO[CAFE24.SDE_SHOP_NUM].aShopCurrencyInfo.currency_code,
35453            };
35454        },
35455        pushContent: function (oData) {
35456            oParam.contents.push(oData);
35457        },
35458        trigger: function (sParam, aResult) {
35459            var oData = this.queryStringToJSON(sParam);
35460            this.init(oData.product_no);
35461
35462            // [ECHOSTING-623890] 추가할인액 계산(비동기 AJAX) 데이터 미도착/timeout 시 getSaleItem()이 false를 반환하여
35463            // price:0 / variant_code 누락의 빈 페이로드가 발화되고 메타 픽셀 등 구독자가 이를 드롭(간헐 미집계)한다.
35464            // 계산기 미준비면 서버 장바구니 응답 기반 기존 경로(setDataFromParam)로 폴백한다.
35465            if (typeof TotalAddSale !== 'undefined' && this.isTotalAddSaleReady()) {
35466                this.setDataFromTotalAddSale();
35467            } else {
35468                this.setDataFromParam(oData, aResult);
35469            }
35470
35471            if (!bIsProcess) {
35472                EC$('body').trigger(sEventName, oParam);
35473            }
35474        },
35475        isTotalAddSaleReady: function () {
35476            var oProductList = TotalAddSale.getProductList();
35477            if (typeof oProductList === 'undefined' || Object.keys(oProductList).length === 0) {
35478                return false;
35479            }
35480            for (var sItemCode in oProductList) {
35481                if (oProductList.hasOwnProperty(sItemCode) && TotalAddSale.getSaleItem(sItemCode) === false) {
35482                    return false;
35483                }
35484            }
35485            return true;
35486        },
35487        setDataFromTotalAddSale: function () {
35488            var basketProductList = TotalAddSale.getProductList();
35489            if (typeof basketProductList !== 'undefined' && Object.keys(basketProductList).length > 0) {
35490                oParam.category = CAFE24.FRONT_JS_CONFIG_SHOP.oCategoryInfo;
35491                oParam.total_price = TotalAddSale.getTotalOrderPrice();
35492                for (var sItemCode in basketProductList) {
35493                    if (basketProductList.hasOwnProperty(sItemCode)) {
35494                        var oSaleItem = TotalAddSale.getSaleItem(sItemCode);
35495                        // sale 데이터 미계산(바로구매 등) 시 해당 품목 스킵하여 결과 콜백 체인 중단 방지 (ECHOSTING-625233)
35496                        if (oSaleItem === false) {
35497                            continue;
35498                        }
35499                        var sVariantCode = typeof(set_option_data) !== 'undefined' ? item_code : oSaleItem.item_code;
35500                        this.pushContent({
35501                            price: Math.floor(parseFloat(oSaleItem.item_price) || 0),
35502                            variant_code: sVariantCode,
35503                            quantity: parseInt(oSaleItem.quantity, 10) || 1,
35504                            name: product_name
35505                        });
35506                    }
35507                }
35508
35509                bIsProcess = false;
35510            }
35511        },
35512        setDataFromParam: function (oData, aResult) {
35513            if (typeof aResult !== 'undefined' && typeof aResult.aBasketProduct === 'object') {
35514                var iTotalPrice = 0;
35515                for (var i = 0; i < aResult.aBasketProduct.length; i++) {
35516                    var iItemPrice = Math.floor(parseFloat(aResult.aBasketProduct[i].tax_included_product_price) || 0);
35517                    var iQuantity = parseInt(aResult.aBasketProduct[i].quantity, 10) || 1;
35518                    iTotalPrice += iItemPrice * iQuantity;
35519                    this.pushContent({
35520                        variant_code: aResult.aBasketProduct[i].item_code,
35521                        quantity: iQuantity,
35522                        name: aResult.aBasketProduct[i].product_name,
35523                        price: iItemPrice,
35524                    });
35525                }
35526                oParam.total_price = iTotalPrice;
35527
35528                bIsProcess = false;
35529            }
35530        },
35531        getEventData: function () {
35532            // [ECHOSTING-623890] 미발화 결정(bIsProcess=true: 계산기 미준비 + 폴백 데이터 부재) 시 null 반환 →
35533            // relay 송신부(상세/레이어/세트)가 빈 payload를 부모로 보내지 않게 하여,
35534            // 수신부(NewProductOptionSelect/Channel)의 truthy 가드가 빈 이벤트 재발사를 차단한다.
35535            if (bIsProcess) {
35536                return null;
35537            }
35538            return JSON.parse(JSON.stringify(oParam));
35539        },
35540        queryStringToJSON: function (sParam) {
35541            var aParam = decodeURIComponent(sParam).split('&');
35542            var oResult = {};
35543            EC$.each(aParam, function (iKey, sText) {
35544                sText = sText.split('=');
35545                var sName = sText[0];
35546                var sValue = sText[1];
35547                if (sName.length) {
35548                    if (oResult[sName] !== undefined) {
35549                        if (!oResult[sName].push) {
35550                            oResult[sName] = [oResult[sName]];
35551                        }
35552                        oResult[sName].push(sValue || '');
35553                    } else {
35554                        oResult[sName] = sValue || '';
35555                    }
35556                }
35557            });
35558            return oResult;
35559        }
35560    };
35561})();
35562
35563EC$(function () {
35564    CAPP_PRODUCT_LIST_WISHICON.init();
35565});
35566var CAPP_PRODUCT_LIST_WISHICON = {
35567    iDuplicateSecond: 2000, //중복 클릭 제한시간
35568    iClickCount: 0,
35569    iRecentClickProductNo: 0,
35570    iTimeoutId: 0, // 중복방지 대기시간 실행 시퀀스 번호
35571    sCommand: 'add',
35572    bRequesting: false, // 등록/삭제 요청 처리중 여부 (ECHOSTING-631149)
35573    init: function()
35574    {
35575        var iProductNo = 0;
35576        var iCategoryNo = 0;
35577        var oObj = null;
35578        var sLogin = '';
35579        var bIsIndividualSetProduct = false;
35580        try {
35581            EC$(document).on('click', '.ec-product-listwishicon', function () {
35582                oObj = EC$(this);
35583                iProductNo = parseInt(oObj.attr('productno'));
35584                iCategoryNo = oObj.attr('categoryno');
35585                sLogin = oObj.attr('login_status');
35586                bIsIndividualSetProduct = oObj.attr('individual-set') === 'T';
35587                if (oObj.data('ec-redirect') === 'T') {
35588                    location.href = EC$(this).data('ec-redirect-url');
35589                    return;
35590                }
35591
35592                if (sLogin !== 'T') {
35593                    alert(__('로그인 후 관심상품 등록을 해주세요.'));
35594                    location.href = '/member/login.html?returnUrl=' + encodeURIComponent(location.pathname + location.search);
35595                    return;
35596                }
35597
35598
35599                // 이전 요청이 아직 처리중이면 무시 - 응답 전 연타로 같은 add 요청이
35600                // 중복 전송되어 wish_list duplicate key 가 발생하는 것을 방지 (ECHOSTING-631149)
35601                // 클릭 카운트 상태를 바꾸기 전에 확인해야 무시된 클릭이 응답 후 토글 클릭을 막지 않는다
35602                if (CAPP_PRODUCT_LIST_WISHICON.bRequesting === true) {
35603                    return;
35604                }
35605
35606                if (CAPP_PRODUCT_LIST_WISHICON.iRecentClickProductNo === iProductNo) {
35607                    if (CAPP_PRODUCT_LIST_WISHICON.iClickCount === 1) {
35608                        CAPP_PRODUCT_LIST_WISHICON.iClickCount++;
35609                        CAPP_PRODUCT_LIST_WISHICON.initCount();
35610                    } else if (CAPP_PRODUCT_LIST_WISHICON.iClickCount > 1) {
35611                        return;
35612                    }
35613                } else {
35614                    CAPP_PRODUCT_LIST_WISHICON.iClickCount = 0;
35615                    CAPP_PRODUCT_LIST_WISHICON.iRecentClickProductNo = iProductNo;
35616                    if (CAPP_PRODUCT_LIST_WISHICON.iTimeoutId > 0) {
35617                        clearTimeout(CAPP_PRODUCT_LIST_WISHICON.iTimeoutId);
35618                    }
35619                }
35620
35621                // DB 처리전 카운트를 해야 정확히 중복체크가능
35622                CAPP_PRODUCT_LIST_WISHICON.iClickCount++;
35623
35624                if (oObj.attr('icon_status') === 'on') {
35625                    CAPP_PRODUCT_LIST_WISHICON.sCommand = 'del';
35626                } else {
35627                    CAPP_PRODUCT_LIST_WISHICON.sCommand = 'add';
35628                }
35629
35630                var sUrl = '/exec/front/Product/Wishlist/';
35631                var sParam = 'command=' + CAPP_PRODUCT_LIST_WISHICON.sCommand + '&from=wish_icon';
35632                sParam += '&referer=' + encodeURIComponent('//' + location.hostname + location.pathname + location.search);
35633                sParam += '&product_no=' + iProductNo + '&cate_no=' + iCategoryNo;
35634                if (bIsIndividualSetProduct === true) {
35635                    sParam += '&set_product=T';
35636                }
35637
35638                CAPP_PRODUCT_LIST_WISHICON.bRequesting = true;
35639                EC$.ajax({
35640                    type: 'POST',
35641                    url: sUrl,
35642                    data: sParam,
35643                    dataType: 'json',
35644                    success: function (data) {
35645                        CAPP_PRODUCT_LIST_WISHICON.getResultWishIconAjax(data, oObj);
35646                    },
35647                    // 실패 응답에서도 잠금을 해제해야 재시도가 가능하다 (ECHOSTING-631149)
35648                    complete: function () {
35649                        CAPP_PRODUCT_LIST_WISHICON.bRequesting = false;
35650                    }
35651                });
35652            });
35653        } catch (e) {}
35654    },
35655
35656    /**
35657     * 클릭후 시간체크
35658     */
35659    initCount: function()
35660    {
35661        CAPP_PRODUCT_LIST_WISHICON.iTimeoutId = setTimeout(function() {
35662            CAPP_PRODUCT_LIST_WISHICON.iClickCount = 0;
35663        }, CAPP_PRODUCT_LIST_WISHICON.iDuplicateSecond);
35664    },
35665
35666    getResultWishIconAjax: function(aData, oObj)
35667    {
35668        var STORAGE_KEY = 'localWishList' + CAFE24.SDE_SHOP_NUM;
35669        if (aData == null) return;
35670        if (aData.result == 'SUCCESS') {
35671            var iProductNo = EC$(oObj).attr('productno');
35672
35673            EC$('.ec-product-listwishicon[productno="'+iProductNo+'"]').each(function() {
35674                var oStorageData = CAFE24.UTIL.parseJSON(sessionStorage.getItem(STORAGE_KEY));
35675                if (EC$(this).attr('icon_status') === 'off') {
35676                    var src = aData.data.wish_icon.on;
35677                    var alt = aData.data.wish_alt.on;
35678                    if (oStorageData !== null && oStorageData.hasOwnProperty('on_tags') === true) {
35679                        src = oStorageData.on_tags.src;
35680                        alt = oStorageData.on_tags.alt;
35681                    }
35682                    EC$(this).attr('src', src);
35683                    EC$(this).attr('alt', alt);
35684                    EC$(this).attr('icon_status', 'on');
35685                } else {
35686                    var src = aData.data.wish_icon.off;
35687                    var alt = aData.data.wish_alt.off;
35688                    if (oStorageData !== null && oStorageData.hasOwnProperty('off_tags') === true) {
35689                        src = oStorageData.off_tags.src;
35690                        alt = oStorageData.off_tags.alt;
35691                    }
35692                    EC$(this).attr('src', src);
35693                    EC$(this).attr('alt', alt);
35694                    EC$(this).attr('icon_status', 'off');
35695                }
35696            });
35697
35698            if (CAPP_ASYNC_METHODS.hasOwnProperty('WishList') === true) {
35699                // 관심상품 추가/삭제시 sessionStorage 추가/삭제 처리
35700                CAPP_ASYNC_METHODS.WishList.setSessionStorageItem(iProductNo, CAPP_PRODUCT_LIST_WISHICON.sCommand);
35701            }
35702
35703            if (CAPP_ASYNC_METHODS.hasOwnProperty('Wishcount') === true) {
35704                CAPP_ASYNC_METHODS.Wishcount.restoreCache();
35705                CAPP_ASYNC_METHODS.Wishcount.execute();
35706            }
35707
35708            if (CAPP_PRODUCT_LIST_WISHICON.sCommand === 'add') { // 위시리스트 등록시에만 실행
35709                CAFE24.PLUSAPP_BRIDGE.addWishList(iProductNo);
35710                if (typeof CAFE24.KAKAO_PIXEL_BRIDGE !== 'undefined') {
35711                    CAFE24.KAKAO_PIXEL_BRIDGE.addWishList(iProductNo);
35712                }
35713            }
35714
35715        } else if (aData.result == 'ERROR') {
35716            alert(__('실패하였습니다.'));
35717        } else if (aData.result == 'NOT_LOGIN') {
35718            alert(__('회원 로그인 후 이용하실 수 있습니다.'));
35719        } else if (aData.result == 'INVALID_REQUEST') {
35720            alert(__('파라미터가 잘못되었습니다.'));
35721        }
35722    }
35723};
35724
35725/**
35726 * 문화세 적용 여부를 설정하고 반환하는 객체
35727 */
35728var SHOP_FRONT_PRODUCT_CULTURAL_TAX = {
35729    is_cultural_tax: 'F',
35730
35731    /**
35732     * 문화세 적용 여부를 반환합니다.
35733     * @returns {string} 'T' 또는 'F'로 문화세 적용 여부
35734     */
35735    getIsCulturalTax: function() {
35736        return CAFE24.FRONT_JS_CONFIG_SHOP.is_cultural_tax || this.is_cultural_tax;
35737    }
35738};
35739/**
35740 * 추가구성 상품 라이브러리
35741 */
35742var TotalAddSale = function() {
35743    //추가할인액계산
35744    var oProductList = new Object();
35745    var oOlnkProductList = new Object();
35746    var oTotalAddSaleParam = new Object();
35747    var iTotalAddSalePrice = 0;
35748    var oTotalAddSaleData = new Object();
35749    var oProductOptionType = new Object();
35750    var bSoldOut = false;
35751
35752    var oDefaultOption = {
35753        url: "/exec/front/shop/CalculatorProduct",
35754        type: "GET",
35755        data: oTotalAddSaleParam,
35756        dataType: "json",
35757        timeout: 5000,
35758        compleat: function() {
35759            TotalAddSale.setAsyncMode(true);
35760        }
35761    };
35762
35763    var updateItemPrice = function() {
35764
35765        //판매가 회원 공개인 경우 제외
35766        if (sIsDisplayNonmemberPrice === 'T') {
35767            return;
35768        }
35769
35770        if (TotalAddSale.getIsUseSalePrice() === false) {
35771            return;
35772        }
35773
35774        var oData = TotalAddSale.oTotalAddSaleData;
35775        var iLayer = EC$('#product_detail_option_layer').length;
35776
35777        //1+N혜택상품은 가격이 보이지 않게 처리
35778        if (TotalAddSale.getIsBundleProduct() === true) {
35779            EC$('.ec-front-product-item-price[product-no="' + iProductNo + '"]').html('');
35780            if (iLayer > 0) {
35781                EC$(top.document).find('.ec-front-product-item-price[product-no="' + iProductNo + '"]').html('');
35782            }
35783
35784            return;
35785        }
35786
35787        //세트상품 제외
35788        var bIsSetProduct = false;
35789        if (typeof(set_option_data) !== 'undefined') {
35790            bIsSetProduct = true;
35791        }
35792
35793        for (var sKey in oData) {
35794            if (oData.hasOwnProperty(sKey) === false) {
35795                continue;
35796            }
35797
35798            if (typeof(oData[sKey]) !== 'object') {
35799                continue;
35800            }
35801
35802            //표시항목설정 > "판매가 부가세 표시문구"이 사용함일경우 key가 object로 생김
35803            if (sKey === 'product_tax_type_text') {
35804                continue;
35805            }
35806
35807            //본상품이 세트상품일 경우에는 본상품은 제외하고 추가구성상품만 할인가로 처리
35808            var oElement = EC$('.ec-front-product-item-price[code="' + sKey + '"]');
35809            if (bIsSetProduct === true && parseInt(oElement.attr('product-no')) === parseInt(iProductNo)) {
35810                continue;
35811            }
35812
35813            var iProductItemPrice = 0;
35814
35815            if (oData[sKey].display_vat_separately === true) {
35816                //부가세 별도표시일경우
35817                iProductItemPrice = oData[sKey].vat_sub_total_price - oData[sKey].vat_sale_price;
35818                iProductItemPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iProductItemPrice);
35819            } else {
35820                //부가세 포함일 경우
35821                iProductItemPrice = oData[sKey].item_quantity_price - oData[sKey].add_sale;
35822                iProductItemPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iProductItemPrice);
35823            }
35824
35825            oElement.html(iProductItemPrice);
35826            if (iLayer > 0) {
35827                EC$(top.document).find('.ec-front-product-item-price[code="' + sKey + '"]').html(iProductItemPrice);
35828            }
35829        }
35830    };
35831
35832    /**
35833     * 적립금 갱신
35834     * @param sOptionBoxId
35835     * @param sWithoutOptionId
35836     */
35837    var updateMileage = function(sOptionBoxId, sWithoutOptionId) {
35838
35839
35840        // 적립금 표시중이 아니거나, 판매가 회원 공개인 경우 제외
35841        if (sIsMileageDisplay !== 'T' || sIsDisplayNonmemberPrice === 'T') {
35842            return;
35843        }
35844
35845        var oData = TotalAddSale.oTotalAddSaleData;
35846        var iQuantity = 1;
35847        var iLayer = EC$('#product_detail_option_layer').length;
35848
35849        // TotalAddSale.oTotalAddSaleData 없는 경우 리턴
35850        if (typeof(oData) === 'undefined') {
35851            return;
35852        }
35853
35854        // deep copy
35855        oData = JSON.parse(JSON.stringify(oData));
35856
35857        // 이미 갱신된 현재 적립금은 추가 갱신하지 않도록 삭제
35858        if (typeof(sWithoutOptionId) !== 'undefined' && oData.hasOwnProperty(sWithoutOptionId) === true) {
35859            delete oData[sWithoutOptionId];
35860        }
35861
35862        // 적립금 갱신
35863        for (var sKey in oData) {
35864            if (oData.hasOwnProperty(sKey) === true) {
35865                if (typeof(oData[sKey]) === 'object') {
35866                    var sMileageVal = CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice(TotalAddSale.getMileageGenerateCalc(sKey, typeof(oData[sKey].quantity) !== 'undefined' ? oData[sKey].quantity : iQuantity));
35867
35868                    EC$('.mileage_price[code="' + sKey + '"]').html(sMileageVal);
35869
35870                    if (iLayer > 0) {
35871                        EC$(top.document).find('.mileage_price[code="' + sKey + '"]').html(sMileageVal);
35872                    }
35873                }
35874            }
35875        }
35876    };
35877
35878    /**
35879     * 추가할인액 주문api조회
35880     * @param fCallback 콜백함수
35881     * @return TotalAddSale.iTotalAddSalePrice
35882     */
35883    var getCalculatorSalePrice = function (fCallback, iPrice, sProductType) {
35884
35885        EC_SHOP_FRONT_DEBUG.log("getCalculatorSalePrice - fn");
35886
35887        if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm === true) {
35888            fCallback(iPrice);
35889            CAFE24.SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY.setDirectBuyOrderBasket();
35890        } else {
35891            var oOption = {
35892                success: function(oResponse) {
35893                    if (oResponse.Result === false) {
35894                        if (oResponse.hasOwnProperty('msg') === true) {
35895                            alert(oResponse.msg);
35896                            // [ECHOSTING-604271] 추가구성상품이 재고를 초과했을때 본상품의 재고가 변경되지않도록 처리
35897                            if (oResponse.has_option === 'F' && sProductType !== 'addproduct') {
35898                                var iStockNumber = parseInt(oResponse.stock_number, 10);
35899
35900                                // 구매단위(buy_unit) 보정: 서버에서 이미 보정하지만 클라이언트에서도 방어적으로 처리
35901                                // 예) buy_unit=3, 서버응답=5 -> floor(5/3)*3 = 3 (구매단위에 맞는 수량으로 변경)
35902                                if (typeof buy_unit !== 'undefined' && parseInt(buy_unit, 10) > 1) {
35903                                    var iBuyUnit = parseInt(buy_unit, 10);
35904                                    iStockNumber = Math.floor(iStockNumber / iBuyUnit) * iBuyUnit;
35905                                }
35906
35907                                EC$(quantity_id).val(iStockNumber);
35908                            }
35909                            delete oDefaultOption.data['product'][oResponse.sItemCode];
35910                        }
35911                        return;
35912                    }
35913
35914                    //var oResponse = oResponseData.data;console.log(typeof oResponse.flag);
35915                    // 글로벌이면서 일체형 세트상품의 구성상품 과세비율 또는 과세타입이 다른 경우에는 구매 불가
35916                    if (typeof oResponse.flag !== 'undefined' && oResponse.flag === false && oResponse.code === 4221) {
35917                        // 알럿 - [$상품명] 상품은 구매할 수 있는 상품이 아닙니다.
35918                        ProductSet.getCompareSetAlert();
35919                        return;
35920                    }
35921
35922                    TotalAddSale.oTotalAddSaleData = oResponse;
35923                    if (TotalAddSale.bSoldOut === false) {
35924                        TotalAddSale.iTotalAddSalePrice = oResponse.iTotalAddSalePrice;
35925                        TotalAddSale.iTotalOrderPrice = oResponse.iTotalOrderPrice;
35926                        TotalAddSale.oProductTaxTypeText = oResponse.product_tax_type_text;
35927                        TotalAddSale.sDisplayVatSeparately = oResponse.display_prd_vat_separately;
35928                    }
35929
35930                    fCallback(iPrice);
35931                }, error: function () {
35932                    if (EC$('.EC-price-warning').length > 0) {
35933                        EC$('.EC-price-warning').removeClass('displaynone').show();
35934                    } else {
35935                        alert(__('할인가가 적용된 최종 결제예정금액은 주문 시 확인할 수 있습니다.'));
35936                    }
35937                    fCallback(iPrice);
35938                }
35939
35940            };
35941
35942            // 품절일 경우 할인액 계산 제외
35943            if (EC$('.soldout_option_box_id').length > 0) {
35944                EC$('.soldout_option_box_id').each(function () {
35945                    delete oDefaultOption.data['product'][EC$(this).val()];
35946                });
35947            }
35948
35949            if (typeof (iCategoryNo) !== 'undefined' && parseInt(iCategoryNo) > 0) {
35950                oOption.data = EC$.extend(oDefaultOption.data, {cate_no: parseInt(iCategoryNo)});
35951            }
35952            EC$.ajax(EC$.extend(oDefaultOption, oOption));
35953        }
35954    };
35955    /* 단일 선택형인 경우 처리가 필요함. 대량 구매 할인 정책때문에 파라미터 제거 처리 */
35956    var setAddSaleParamRemove = function(sOptionId) {
35957
35958        // 단일 선택형인지 확인
35959        if (oSingleSelection.isItemSelectionTypeS() === true && sOptionId !== '') {
35960            var oProductListData = TotalAddSale.getProductList();
35961            var sUniqueProductId = '';
35962            var bRegexp = false;
35963
35964            // 연동형의 경우 아이템코드가 조합형과 다르다.
35965            if (sOptionId.indexOf('||') > -1 || sOptionId.indexOf('#$%') > -1) {
35966                sUniqueProductId = sOptionId.replace(/[0-9]+/g, '');
35967                bRegexp = true;
35968            } else if (oProductOptionType[sOptionId] === 'F') { // 독립형의 경우 각 개별적으로 갯수가 존재함.
35969                sUniqueProductId = sOptionId;
35970            } else {
35971                sUniqueProductId = sOptionId.substring(0, 8);
35972            }
35973
35974            for (var sKey in oProductListData) {
35975                var sOptionKey = sKey;
35976                if (bRegexp === true) {
35977                    sOptionKey = sOptionKey.replace(/[0-9]+/g, '');
35978                }
35979                if (sOptionKey.indexOf(sUniqueProductId) > -1) {
35980                    TotalAddSale.removeProductData(sKey);
35981                }
35982            }
35983
35984        }
35985    };
35986    var getDirectBuyParam = function() {
35987        var aStockData = new Array();
35988        if (typeof(option_stock_data) !== 'undefined') {
35989            aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
35990        }
35991        var oProduct = TotalAddSale.getParam();
35992        var oParam = new Object();
35993        var oProductParam = new Object();
35994        oParam['product_no'] = oProduct['product_no'];
35995
35996        if (typeof(oProduct['product']) !== 'undefined' && Object.keys(oProduct['product']).length > 0) {
35997            var i = 0;
35998            for (var sKey in oProduct['product']) {
35999                if (typeof(aStockData[sKey]) !== 'undefined' && aStockData[sKey].is_auto_soldout === 'T') {
36000                    continue;
36001                }
36002                oProductParam[i] = {'item_code': sKey, 'quantity': oProduct['product'][sKey]};
36003                oParam['items'] = oProductParam;
36004                i++;
36005            }
36006        } else {
36007            oParam['items'] = null;
36008        }
36009        return oParam;
36010    };
36011
36012    return {
36013        updatePrice: function(sOptionBoxId, sWithoutOptionId) {
36014            updateItemPrice();
36015            updateMileage(sOptionBoxId, sWithoutOptionId);
36016        },
36017
36018        updateItemPrice: function() {
36019            updateItemPrice();
36020        },
36021
36022        removeProductData: function(sOptionKey)
36023        {
36024            delete oProductList[sOptionKey];
36025        },
36026        // 총 추가할인액 반환
36027        // GE presentment 활성 시 iTotalAddSalePrice 는 CalculatorProduct 서버 응답에서
36028        // convertGlobalePresentment() 로 이미 표시통화 변환된 값이므로 여기서 환율을 재적용하지 않는다.
36029        // (환율 재적용 시 이중 변환되어 총 상품금액이 어긋난다 — ECQAUNIT-74832)
36030        getTotalAddSalePrice: function() {
36031            if (typeof CAFE24.SHOP_FRONT_PRODUCT_FUNDING === 'object' && CAFE24.SHOP_FRONT_PRODUCT_FUNDING.isFundingProduct() === true) {
36032                return 0;
36033            }
36034            return TotalAddSale.iTotalAddSalePrice;
36035        },
36036        // 계산할 정보 셋팅
36037        setParam: function(sKey, value) {
36038            oTotalAddSaleParam[sKey] = value;
36039        },
36040        clearAddSaleParam: function(sKey)
36041        {
36042            delete oTotalAddSaleParam[sKey];
36043        },
36044        getParam: function()
36045        {
36046            return oTotalAddSaleParam;
36047        },
36048        // 계산될 상품리스트
36049        getProductList: function() {
36050            return oProductList;
36051        },
36052        // 총 추가할인금액 리셋
36053        setTotalAddSalePrice: function(iSalePrice) {
36054            TotalAddSale.iTotalAddSalePrice = iSalePrice;
36055
36056            if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm === true) {
36057                CAFE24.SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY.resetDirectBuyOrderBasket();
36058            }
36059        },
36060        // 계산할 정보 수량 셋팅
36061        setQuantity: function(sItemCode, sQuantity) {
36062            TotalAddSale.setAddSaleParamRemove(sItemCode);
36063            oProductList[sItemCode] = sQuantity;
36064        },
36065        setOlnkAddProduct: function(sItemCode, iProductNo) {
36066            oOlnkProductList[sItemCode] = iProductNo;
36067        },
36068        getOlnkAddProductList: function() {
36069            return oOlnkProductList;
36070        },
36071        // api호출
36072        getCalculatorSalePrice: function(fCallback, iPrice, sProductType) {
36073            getCalculatorSalePrice(fCallback, iPrice, sProductType);
36074        },
36075        // 총 추가할인액 반환
36076        getItemAddSalePrice: function(sItemCode) {
36077            if (typeof(TotalAddSale.oTotalAddSaleData) !== 'undefined') {
36078                return parseFloat(TotalAddSale.oTotalAddSaleData[sItemCode].unit_add_sale , 10);
36079            } else {
36080                return 0;
36081            }
36082        },
36083        // 총 추가할인금액 리셋
36084        setSoldOutFlag: function(bSoldOut) {
36085            if (typeof(bSoldOut) === 'undefined' || bSoldOut === null) {
36086                bSoldOut = false;
36087            }
36088            TotalAddSale.bSoldOut = bSoldOut;
36089        },
36090        // 적립금 총 계산
36091        getMileageGenerateCalc: function(sItemCode, iQuantity) {
36092            if (TotalAddSale.bSoldOut === false && typeof(TotalAddSale.oTotalAddSaleData) !== 'undefined') {
36093                if (typeof(TotalAddSale.oTotalAddSaleData[sItemCode]) !== 'undefined' && typeof(TotalAddSale.oTotalAddSaleData[sItemCode].mileage_generate_calc) !== 'undefined') {
36094                    return parseFloat(TotalAddSale.oTotalAddSaleData[sItemCode].mileage_generate_calc, 10);
36095                } else {
36096                    return 0;
36097                }
36098            } else {
36099                return (typeof(mileage_generate_calc) !== 'undefined') ? mileage_generate_calc * iQuantity : 0;
36100            }
36101        },
36102        // 적립금 유효성 검증
36103        checkVaildMileageValue: function(iMileageValue) {
36104            if (typeof (iMileageValue) === 'undefined' && iMileageValue === 0.00 || iMileageValue <= 0) {
36105                return false;
36106            }
36107
36108            return true;
36109        },
36110        /**
36111         * @deprecated 추가할인가 재계산 필요 여부 리턴
36112         * @returns true
36113         */
36114        needRecalculatorSalePrice: function() {
36115            /*
36116             * 해당 메소드 동작처리시 대량 구매 할인의 경우 product_sale_price 값이 존재하지 않으며
36117             * TotalAddSale.iTotalAddSalePrice 값도 대량 구매 할인의 경우 필요하지 않게 됨
36118             */
36119            return true;
36120        },
36121        // 판매가 부가세 표시문구 설정
36122        getProductTaxTypeText: function() {
36123            return TotalAddSale.oProductTaxTypeText;
36124        },
36125        // 실제 총 주문금액
36126        getTotalOrderPrice: function() {
36127            return TotalAddSale.iTotalOrderPrice;
36128        },
36129        // 부가세 별도 표시 설정
36130        getDisplayVatSeparately: function() {
36131            return TotalAddSale.sDisplayVatSeparately;
36132        },
36133        getItemSalePrice: function(sItemCode)
36134        {
36135            if (typeof(TotalAddSale.oTotalAddSaleData[sItemCode]) === 'undefined') {
36136                return false;
36137            }
36138            return TotalAddSale.oTotalAddSaleData[sItemCode].unit_sale_price;
36139        },
36140        getSaleItem: function(sItemCode)
36141        {
36142            // 바로구매 등 sale 데이터 미계산 상태(oTotalAddSaleData undefined)에서의 접근 방어 (ECHOSTING-625233)
36143            if (typeof(TotalAddSale.oTotalAddSaleData) === 'undefined' || typeof(TotalAddSale.oTotalAddSaleData[sItemCode]) === 'undefined') {
36144                return false;
36145            }
36146            return TotalAddSale.oTotalAddSaleData[sItemCode];
36147        },
36148        // 부가세 고정세율 총상품금액
36149        getVatSubTotalPrice: function(sItemCode) {
36150            var sDisplayVatSeparately = TotalAddSale.getDisplayVatSeparately();
36151            if (typeof(sDisplayVatSeparately) === 'undefined') {
36152                return 0;
36153            }
36154
36155            if (sDisplayVatSeparately !== true) {
36156                return 0;
36157            }
36158
36159            if (typeof(TotalAddSale.oTotalAddSaleData[sItemCode]) === 'undefined') {
36160                return 0;
36161            }
36162
36163            return TotalAddSale.oTotalAddSaleData[sItemCode].vat_sub_total_price;
36164        },
36165        //품목 선택시 할인가를 보여줄것인지 여부
36166        getIsUseSalePrice: function () {
36167
36168            if (typeof (EC_FRONT_JS_CONFIG_SHOP) !== 'object') {
36169                return false;
36170            }
36171
36172            //디자인에서 옵션을 설정하지 않으면 처리하지 않음
36173            if (EC_FRONT_JS_CONFIG_SHOP.bECUseItemSalePrice === false) {
36174                return false;
36175            }
36176
36177            return true;
36178        },
36179
36180        //1+N상품인지 여부
36181        getIsBundleProduct: function () {
36182            if (typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE !== 'undefined' && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNo) === true) {
36183                return true;
36184            }
36185
36186            return false;
36187        } ,
36188        //
36189        setAddSaleParamRemove: function(sOptionId)
36190        {
36191            return setAddSaleParamRemove(sOptionId);
36192        } ,
36193        setProductOptionType: function (sOptionId, sOptType) {
36194            if (oSingleSelection.isItemSelectionTypeS() === true && sOptionId !== '') {
36195                oProductOptionType[sOptionId] = sOptType;
36196            }
36197
36198        },
36199        getDirectBuyParam: function()
36200        {
36201            return getDirectBuyParam();
36202        },
36203        setSubscriptionParam: function()
36204        {
36205            var isSubscription = 'F';
36206            if (EC$('.EC_regular_delivery:checked').val() === 'T') {
36207                isSubscription = 'T';
36208            }
36209            TotalAddSale.setParam('is_subscription',isSubscription);
36210
36211        },
36212        /**
36213         * 예약형 상품의 추가금액을 반환
36214         * @param string sOptionLinkData 옵션코드
36215         * @returns int 추가금액
36216         */
36217        getReservationLinkAddPrice : function(sOptionLinkData)
36218        {
36219            let iAddPrice = 0;
36220            // item_option_link는 number(단일 옵션) 또는 "5-3" 형태의 string(다중 옵션)으로 들어오고
36221            // sOptionLinkData는 항상 string이므로, 양쪽을 string으로 정규화해 비교한다.
36222            // (int 캐스팅 시 "5-3"이 5로 파싱되어 다른 품목과 오매칭될 수 있음)
36223            var sNormalizedLink = String(sOptionLinkData).trim();
36224            for (var sItemCode in TotalAddSale.oTotalAddSaleData) {
36225                if (TotalAddSale.oTotalAddSaleData[sItemCode].hasOwnProperty('item_option_link') === false) {
36226                    continue;
36227                }
36228                if (String(TotalAddSale.oTotalAddSaleData[sItemCode]['item_option_link']).trim() !== sNormalizedLink) {
36229                    continue;
36230                }
36231                iAddPrice = TotalAddSale.oTotalAddSaleData[sItemCode]['opt_price'];
36232                break;
36233            }
36234            return iAddPrice;
36235        }
36236    };
36237}();
36238// sms 재입고 알림 모바일 레이어 팝업
36239CAFE24.SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER = {
36240    bExistMobileLayerModule: false,
36241    sRequireSmsRestockParam: '',
36242
36243    setCheckSmsRestockLayerPopup: function()
36244    {
36245        //모바일이 아니라면 사용하지 않음
36246        if (mobileWeb === false && EC_MOBILE_DEVICE === false) {
36247            return;
36248        }
36249
36250        if (EC$('a[id^="btn_restock"]').length < 1 && typeof EC_FRONT_JS_CONFIG_SHOP.aRestockButton === 'undefined') {
36251            return;
36252        }
36253
36254        //아이프레임 내에서는 레이어를 다시띄우지 않음
36255        if (CAPP_SHOP_FRONT_COMMON_UTIL.findTargetFrame() === parent) {
36256            return;
36257        }
36258
36259        EC$.ajax({
36260            url: '/exec/front/Product/Moduleexist?section=product&file=sms_restock_layer&module=Product_RestockSms',
36261            dataType: 'json',
36262            success: function (data) {
36263                if (data.result === true) {
36264                    EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.bExistMobileLayerModule = true;
36265                }
36266            }
36267        });
36268    },
36269    createSmsRestockLayerDisplayResult: function(sParam)
36270    {
36271        //레이어 사용가능상태가 아니면 false로 바로 리턴
36272        if (EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.bExistMobileLayerModule === false) {
36273            return false;
36274        }
36275
36276        if (CAFE24.UTIL.trim(sParam).length < 1) {
36277            return false;
36278        }
36279
36280        try {
36281            EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.sRequireSmsRestockParam = sParam;
36282            EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.setProductSmsRestockCreateLayer();
36283        } catch (e) {
36284            return false;
36285        }
36286
36287        return true;
36288    },
36289    setProductSmsRestockCreateLayer: function()
36290    {
36291        try {
36292            EC$('#ec-product-sms-restock-layer').remove();
36293        } catch (e) {}
36294
36295        var sSmsLayerUrl = '/product/sms_restock_layer.html?' + EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER.sRequireSmsRestockParam + '&bSmsRestockLayer=T';
36296        var aSmsRestockLayerHtml = [];
36297
36298        aSmsRestockLayerHtml.push('<div id="ec-product-sms-restock-layer" style="position:fixed; top:0; left:0; right:0; bottom:0; webkit-overflow-scrolling:touch; z-index:999;">');
36299        aSmsRestockLayerHtml.push('<iframe src="'+sSmsLayerUrl+'" id="smsRestockLayerIframe" frameborder="0" style="width:100%; height:100%;"></iframe>');
36300        aSmsRestockLayerHtml.push('</div>');
36301
36302        EC$('body').append(aSmsRestockLayerHtml.join(''));
36303        EC$('body').addClass('eMobilePopup');
36304    },
36305    closeSmsRestockLayer: function()
36306    {
36307        if (opener) {
36308            self.close();
36309        } else {
36310            parent.EC$('body').attr('id', 'layout');
36311            parent.EC$('body').removeClass('eMobilePopup');
36312            parent.EC$('#ec-product-sms-restock-layer').remove();
36313        }
36314    }
36315};
36316
36317var EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_PRODUCT_SMS_RESTOCK_LAYER');
36318
36319CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE = {
36320    /**
36321     * 로컬 스토리지 지원 여부
36322     * @return bool 지원하면 true, 지원하지 않으면 false
36323     */
36324    isSupport: function() {
36325        if (window.localStorage) {
36326            return true;
36327        } else {
36328            return false;
36329        }
36330    },
36331
36332    /**
36333     * 로컬 스토리지에 데이터 셋팅
36334     * @param string sKey 키
36335     * @param mixed mData 저장할 데이터
36336     * @param int iLifeTime 살아있는 시간(초) (기본 1일)
36337     * @return bool 정상 저장 여부
36338     */
36339    setItem: function(sKey, mData, iLifeTime) {
36340        if (this.isSupport() === false) {
36341            return false;
36342        }
36343
36344        iLifeTime = iLifeTime || 86400;
36345
36346        try {
36347            window.localStorage.setItem(sKey, JSON.stringify({
36348                iExpireTime: Math.floor(new Date().getTime() / 1000) + iLifeTime,
36349                mContent: mData
36350            }));
36351        } catch (e) {
36352            return false;
36353        }
36354
36355        return true;
36356    },
36357
36358    /**
36359     * 로컬 스토리지에서 데이터 리턴
36360     * @param string sKey 키
36361     * @return mixed 데이터
36362     */
36363    getItem: function(sKey) {
36364        if (this.isSupport() === false) {
36365            return null;
36366        }
36367
36368        var sData = window.localStorage.getItem(sKey);
36369        try {
36370            if (sData) {
36371                var aData = JSON.parse(sData);
36372                if (aData.iExpireTime > Math.floor(new Date().getTime() / 1000)) {
36373                    return aData.mContent;
36374                } else {
36375                    window.localStorage.removeItem(sKey);
36376                }
36377            }
36378        } catch (e) { }
36379
36380        return null;
36381    },
36382
36383    /**
36384     * 로컬 스토리지에서 데이터 삭제
36385     * @param string sKey 키
36386     */
36387    removeItem: function(sKey) {
36388        if (this.isSupport() === false) {
36389            return;
36390        }
36391
36392        window.localStorage.removeItem(sKey);
36393    }
36394};
36395
36396var EC_SHOP_FRONT_NEW_LIKE_BROWSER_CACHE = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_LIKE_BROWSER_CACHE');
36397
36398/**
36399 * 좋아요 관련 공통
36400 */
36401CAFE24.SHOP_FRONT_NEW_LIKE_COMMON = {
36402    CACHE_LIFE_TIME: 3600,
36403    CACHE_KEY_MY_LIKE_CATEGORY: 'localMyLikeCategoryNoList',
36404    CACHE_KEY_MY_LIKE_PRODUCT: 'localMyLikeProductNoList',
36405
36406    aConfig: {
36407        bIsUseLikeProduct: false,
36408        bIsUseLikeCategory: false
36409    },
36410
36411    init: function(aConfig) {
36412        this.aConfig = aConfig;
36413    },
36414
36415    /**
36416     * 내 분류 좋아요 번호 리스트를 가져와서 successCallbackFn 콜백 함수를 실행합니다.
36417     * @param function successCallbackFn 성공시 실행할 콜백 함수
36418     * @param function completeCallbackFn ajax 호출 완료 후 실행할 콜백 함수
36419     */
36420    getMyLikeCategoryNoInList: function(successCallbackFn, completeCallbackFn) {
36421        var self = this;
36422
36423        var aData = CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.getItem(self.CACHE_KEY_MY_LIKE_CATEGORY);
36424        if (aData !== null) {
36425            successCallbackFn(aData);
36426            if (typeof completeCallbackFn === 'function') {
36427                completeCallbackFn();
36428            }
36429        } else {
36430            EC$.ajax({
36431                url: '/exec/front/shop/LikeCommon',
36432                type: 'get',
36433                data: {
36434                    'mode': 'getMyLikeCategoryNoInList'
36435                },
36436                dataType: 'json',
36437                success: function(oReturn) {
36438                    if (oReturn.bResult === true) {
36439                        aData = oReturn.aData;
36440                        CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.setItem(self.CACHE_KEY_MY_LIKE_CATEGORY, aData, self.CACHE_LIFE_TIME);
36441                        successCallbackFn(aData);
36442                    }
36443                },
36444                complete: function() {
36445                    completeCallbackFn();
36446                }
36447            });
36448        }
36449    },
36450
36451    /**
36452     * 내 분류 좋아요 번호 리스트 캐시를 퍼지합니다.
36453     */
36454    purgeMyLikeCategoryNoInList: function() {
36455        CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.removeItem(this.CACHE_KEY_MY_LIKE_CATEGORY);
36456    },
36457
36458    /**
36459     * 내 상품 좋아요 번호 리스트를 가져와서 successCallbackFn 콜백 함수를 실행합니다.
36460     * @param function successCallbackFn 성공시 실행할 콜백 함수
36461     * @param function completeCallbackFn ajax 호출 완료 후 실행할 콜백 함수
36462     */
36463    getMyLikeProductNoInList: function(successCallbackFn, completeCallbackFn) {
36464        var self = this;
36465
36466        var aData = CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.getItem(self.CACHE_KEY_MY_LIKE_PRODUCT);
36467        if (aData !== null) {
36468            successCallbackFn(aData);
36469            if (typeof completeCallbackFn === 'function') {
36470                completeCallbackFn();
36471            }
36472        } else {
36473            EC$.ajax({
36474                url: '/exec/front/shop/LikeCommon',
36475                type: 'get',
36476                data: {
36477                    'mode': 'getMyLikeProductNoInList'
36478                },
36479                dataType: 'json',
36480                success: function(oReturn) {
36481                    if (oReturn.bResult === true) {
36482                        aData = oReturn.aData;
36483                        CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.setItem(self.CACHE_KEY_MY_LIKE_PRODUCT, aData, self.CACHE_LIFE_TIME);
36484                        successCallbackFn(aData);
36485                    }
36486                },
36487                complete: function() {
36488                    completeCallbackFn();
36489                }
36490            });
36491        }
36492    },
36493
36494    /**
36495     * 내 상품 좋아요 번호 리스트 캐시를 퍼지합니다.
36496     */
36497    purgeMyLikeProductNoInList: function() {
36498        CAFE24.SHOP_FRONT_NEW_LIKE_BROWSER_CACHE.removeItem(this.CACHE_KEY_MY_LIKE_PRODUCT);
36499    },
36500    // 숫자 관련 콤마 제거 처리(ECHOSTING-260504)
36501    getNumericRemoveCommas: function(mText) {
36502        var sSearchCommas = ',';
36503        var sReplaceEmpty = '';
36504
36505        if (EC$.inArray(typeof(mText), ['number', 'undefined']) > -1) {
36506            return mText;
36507        }
36508
36509        while (mText.indexOf(sSearchCommas) > -1) {
36510            mText = mText.replace(sSearchCommas, sReplaceEmpty);
36511        }
36512
36513        return mText;
36514    },
36515    // 숫자 관련 콤마 처리 (ECHOSTING-260504)
36516    getNumberFormat: function(iNumber) {
36517        iNumber += '';
36518
36519        var objRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');
36520        while (objRegExp.test(iNumber)) {
36521            iNumber = iNumber.replace(objRegExp, '$1,$2');
36522        }
36523
36524        return iNumber;
36525    }
36526};
36527
36528var EC_SHOP_FRONT_NEW_LIKE_COMMON = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_LIKE_COMMON');
36529
36530
36531/**
36532 * 목록 > 상품 좋아요.
36533 */
36534CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT = {
36535    bIsReady: false, // 좋아요 클릭준비완료 여부.
36536    bIsSetEvent: false, // 좋아요 버튼 이벤트 지정 여부.
36537    aImgSrc: [], // 좋아요(On/Off) 아이콘 경로.
36538    aImgAlt: [], // 좋아요(On/Off) 아이콘 Alt태그
36539    aMyLikePrdNo: [], // 유저가 이미 좋아요 선택한 상품번호
36540    oMyshopLikeCntNode: null, // layout_shopingInfo 좋아요 span 노드
36541
36542    // 상품 좋아요 초기화
36543    init: function() {
36544        // 상품 좋아요 사용안함시
36545        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.aConfig.bIsUseLikeProduct !== true) {
36546            return;
36547        }
36548
36549        // ajax 유저가 이미 좋아요 선택한 상품번호 얻기 + 아이콘세팅
36550        this.setLoadData();
36551    },
36552
36553    // 유저가 이미 좋아요 선택한 상품번호 얻기 + 아이콘세팅
36554    setLoadData: function() {
36555        if (EC$('.likePrdIcon').count < 1) {
36556            return;
36557        }
36558
36559        var self = this;
36560
36561        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getMyLikeProductNoInList(function(aData) {
36562            self.aImgSrc = aData.imgSrc;
36563            self.aImgAlt = aData.imgAlt;
36564            self.aMyLikePrdNo = aData.rows;
36565
36566            // 아이콘(on) 세팅
36567            self.setMyLikeProductIconOn();
36568
36569            // 좋아요 클릭 이벤트핸들러 지정
36570            if (self.bIsSetEvent === false) {
36571                self.setEventHandler();
36572                self.bIsSetEvent = true;
36573            }
36574        }, function() {
36575            self.bIsReady = true;
36576        });
36577    },
36578
36579    // 페이지 로드시 유저가 좋아요한 상품 On.아이콘으로 변경
36580    setMyLikeProductIconOn: function() {
36581        var aData = this.aMyLikePrdNo;
36582
36583        for (var i=0; i < aData.length; i++) {
36584            // selected 스타일 적용
36585            EC$(".likePrd_" + aData[i].product_no).each(function() {
36586                EC$(this).addClass('selected');
36587            });
36588
36589            // 아이콘 이미지경로 변경
36590            EC$(".likePrdIcon[product_no='" + aData[i].product_no + "']").each(function() {
36591                EC$(this).attr({'src': CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgSrc.on, 'icon_status': 'on', 'alt': CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgAlt.on});
36592            });
36593        }
36594    },
36595
36596    // 이벤트핸들러 지정
36597    setEventHandler: function() {
36598        // 좋아요 아이콘 클릭 이벤트
36599        try {
36600            EC$(document).on('click', '.likePrd', CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.clickLikeIcon);
36601            var sContext = '';
36602            if (typeof(PREVIEWPRDOUCT) === 'undefined') {
36603                sContext = window.parent.document;
36604            }
36605        } catch (e) {}
36606
36607
36608        // 마이쇼핑 > 상품좋아요 페이지
36609        if (EC$(".xans-myshop-likeproductlist", sContext).length > 0) {
36610            // 팝업 확대보기창 닫기 이벤트
36611            if (EC$(".xans-product-zoompackage").length > 0) {
36612                EC$('.xans-product-zoompackage div.close').on('click', CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.closeZoomReload);
36613            }
36614        }
36615    },
36616
36617    // 좋아요 아이콘 클릭 이벤트핸들러
36618    clickLikeIcon: function() {
36619        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.bIsReady === false) {
36620            return;
36621        }
36622
36623        // 클릭한 상품의 좋아요수, 아이콘 정보얻기
36624        var iPrdNo = EC$('.likePrdIcon', this).attr('product_no');
36625        var iCateNo = EC$('.likePrdIcon', this).attr('category_no');
36626        var sIconStatus= EC$('.likePrdIcon', this).attr('icon_status');
36627        // 카운트 string > int 형으로 변환 (ECHOSTING-260504)
36628        var iLikeCount = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getNumericRemoveCommas(EC$('.likePrdCount', this).text());
36629
36630        // 아이콘경로 및 좋아요수 증감처리
36631        var sNewImgSrc = sNewIconStatus = "";
36632        var iNewLikeCount = 0;
36633        var oLikeWrapNode = EC$(".likePrd_" + iPrdNo);
36634
36635        if (sIconStatus === 'on') {
36636            sNewIconStatus = 'off';
36637            sNewImgSrc = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgSrc.off;
36638            sNewImgAlt = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgAlt.off;
36639            if (iLikeCount > 0) {
36640                iNewLikeCount = --iLikeCount;
36641            }
36642
36643            oLikeWrapNode.each(function() {
36644                EC$(this).removeClass('selected');
36645            });
36646        } else {
36647            sNewIconStatus = 'on';
36648            sNewImgSrc = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgSrc.on;
36649            sNewImgAlt = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.aImgAlt.on;
36650            iNewLikeCount = ++iLikeCount;
36651
36652            // 동일상품 selected 스타일적용
36653            oLikeWrapNode.each(function() {
36654                EC$(this).addClass('selected');
36655            });
36656        }
36657        // 좋아요 카운트 number_format (ECHOSTING-260504)
36658        iNewLikeCount = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getNumberFormat(iNewLikeCount);
36659        // 상단.layout_shopingInfo 좋아요수 업데이트
36660        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.updateShopInfoCount(sNewIconStatus);
36661
36662        // 좋아요 아이콘이미지 + 좋아요수 업데이트
36663        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.updateLikeIconCount(iPrdNo, sNewImgSrc, sNewIconStatus, iNewLikeCount, sNewImgAlt);
36664
36665        // ajax 호출 좋아요수(상품) + 마이쇼핑 좋아요 저장
36666        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.submitMyLikeProduct(iPrdNo, iCateNo, sNewIconStatus);
36667
36668        // 확대보기 팝업에서 좋아요 클릭시, 부모프레임 좋아요 업데이트
36669        if (EC$(".xans-product-zoompackage").length > 0) {
36670            window.parent.CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.updateShopInfoCount(sNewIconStatus);
36671            window.parent.CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.updateLikeIconCount(iPrdNo, sNewImgSrc, sNewIconStatus, iNewLikeCount);
36672        }
36673    },
36674
36675    // 마이쇼핑 > 상품좋아요 목록 > 팝업 확대보기창 닫기 이벤트핸들러
36676    closeZoomReload: function() {
36677        var sIconsStatus = EC$('.xans-product-zoompackage .likePrdIcon').attr('icon_status');
36678
36679        // 팝업에서 좋아요를 취소했으면 좋아요 목록 새로고침
36680        if (sIconsStatus === 'off') {
36681            window.parent.location.reload();
36682        }
36683    },
36684
36685    // 좋아요 아이콘이미지 + 좋아요수 업데이트
36686    updateLikeIconCount: function(iPrdNo, sImgSrc, sIconStatus, iLikeCount, sNewImgAlt) {
36687        // 클릭한 동일상품 아이콘 변경
36688        EC$(".likePrdIcon[product_no='" + iPrdNo + "']").each(function() {
36689            EC$(this).attr({'src': sImgSrc, 'icon_status': sIconStatus, 'alt': sNewImgAlt});
36690        });
36691
36692        // 클릭한 동일상품 좋아요수 변경
36693        EC$('.likePrdCount_' + iPrdNo).each(function() {
36694            EC$(this).text(iLikeCount);
36695        });
36696    },
36697
36698    // 상단.layout_shopingInfo 좋아요수 업데이트
36699    updateShopInfoCount: function(sIconStatus) {
36700        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.oMyshopLikeCntNode === null) {
36701            CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.oMyshopLikeCntNode = EC$('#xans_myshop_like_prd_cnt');
36702        }
36703
36704        var iMyshopLikeCnt;
36705        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.oMyshopLikeCntNode !== null) {
36706            iMyshopLikeCnt = parseInt(EC$(CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.oMyshopLikeCntNode).text());
36707            iMyshopLikeCnt = (sIconStatus === 'on') ? iMyshopLikeCnt + 1 : iMyshopLikeCnt - 1;
36708            iMyshopLikeCnt = (iMyshopLikeCnt < 0 || isNaN(iMyshopLikeCnt)) ? 0 : iMyshopLikeCnt;
36709            CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.oMyshopLikeCntNode.text(iMyshopLikeCnt + '개');
36710        }
36711
36712        if (EC$('#xans_myshop_main_like_prd_cnt').length > 0 && iMyshopLikeCnt >= 0) {
36713            EC$('#xans_myshop_main_like_prd_cnt').text(iMyshopLikeCnt);
36714        }
36715    },
36716
36717    // 상품 좋아요수 + 마이쇼핑 좋아요 저장
36718    submitMyLikeProduct: function(iPrdNo, iCateNo, sIconStatus) {
36719        if (sIconStatus === 'on') {
36720            this.aMyLikePrdNo.push(iPrdNo);
36721        } else {
36722            this.aMyLikePrdNo.pop(iPrdNo);
36723        }
36724
36725        EC$.ajax({
36726            url: '/exec/front/shop/LikeCommon',
36727            type: 'get',
36728            data: {
36729                'mode': 'saveMyLikeProduct',
36730                'iPrdNo': iPrdNo,
36731                'iCateNo': iCateNo,
36732                'sIconStatus': sIconStatus
36733            },
36734            dataType: 'json',
36735            success: function(oReturn) {
36736                if (oReturn.bResult === true) {
36737                    CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.purgeMyLikeProductNoInList();
36738                }
36739            },
36740            complete: function() {
36741                CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.bIsReady = true;
36742            }
36743        });
36744    }
36745};
36746
36747var EC_SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT');
36748
36749EC$(function() {
36750    CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_PRODUCT.init(); // 상품 좋아요.
36751});
36752
36753CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE = {
36754    oBundleConfig: {},
36755
36756    iProductQuantity: 0,
36757
36758    init: function(oInit)
36759    {
36760        if (typeof(oInit) === 'object') {
36761            this.oBundleConfig = oInit;
36762        } else {
36763            if (sBundlePromotion === '' || typeof(sBundlePromotion) === 'undefined') {
36764                return;
36765            }
36766            this.oBundleConfig = CAFE24.UTIL.parseJSON(sBundlePromotion);
36767        }
36768        // 강제로 후킹
36769        buy_unit = 1;
36770        product_min = 1;
36771        product_max = 0;
36772
36773        EC$.data(document,'BundlePromotion', true);
36774    },
36775    getQuantityStep: function(iProductNum)
36776    {
36777        return this.oBundleConfig[iProductNum].bundle_quantity + 1;
36778    },
36779    /**
36780     * 실제 UI의 수량대신 1+N 이벤트로 인해 후킹된 상품 수량을 리턴
36781     */
36782    getQuantity: function(iQuantity, iProductNum)
36783    {
36784        var iReturn = iQuantity;
36785        if (typeof(this.oBundleConfig[iProductNum]) === 'undefined') {
36786            return iReturn;
36787        }
36788
36789        iReturn = Math.ceil(iQuantity / this.getQuantityStep(iProductNum));
36790
36791        return iReturn;
36792    },
36793    /**
36794     * 정확한 구매 수량이 맞는지 검증
36795     */
36796    isValidQuantity: function(aQuantity, iProductNum)
36797    {
36798        var bReturn = true;
36799        if (typeof(this.oBundleConfig[iProductNum]) === 'undefined') {
36800            return bReturn;
36801        }
36802
36803        if (this.isValidQuantityCheck(aQuantity, iProductNum) === false) {
36804            alert(this.getAlertMessage([iProductNum]));
36805            return false;
36806        }
36807        return bReturn;
36808    },
36809    isValidQuantityCheck: function(aQuantity, iProductNum)
36810    {
36811        var iQuantityStep = this.getQuantityStep(iProductNum);
36812
36813        if (this.oBundleConfig[iProductNum].bundle_apply_type === 'P') {
36814            CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.iProductQuantity = 0;
36815            EC$.map(aQuantity, function(pv) {
36816                CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.iProductQuantity += pv;
36817            });
36818            return (CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.iProductQuantity % iQuantityStep) === 0;
36819        }
36820
36821        if (this.oBundleConfig[iProductNum].bundle_apply_type === 'I') {
36822            for (var i in aQuantity) {
36823                if (aQuantity.hasOwnProperty(i) === false) {
36824                    continue;
36825                }
36826                if (aQuantity[i] % iQuantityStep !== 0) {
36827                    return false;
36828                }
36829            }
36830        }
36831        return true;
36832    },
36833    getAlertMessage: function(iProductNum)
36834    {
36835        var sSubject = this.oBundleConfig[iProductNum].bundle_apply_type === 'P' ? '옵션에 상관없이' : '동일한 옵션으로';
36836        var sReturn = '1+%s 이벤트상품입니다.\n'+sSubject+' 수량을 %s개 단위로 구매해주세요.';
36837        return sprintf(__(sReturn), this.oBundleConfig[iProductNum].bundle_quantity, this.getQuantityStep(iProductNum));
36838    }
36839};
36840
36841var EC_SHOP_FRONT_PRODUCT_DEATAIL_BUNDLE = CAFE24.getDeprecatedNamespace('SHOP_FRONT_PRODUCT_DETAIL_BUNDLE');
36842
36843CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT = {
36844    aProductNo: [], bIsReviewTalk: 'F', setReviewTalkCnt: function () {
36845        var bIsUse = this.checkUseReviewTalk();
36846
36847        if (bIsUse === true) {
36848            this.setDataProductNo();
36849            this.setResponseCountData();
36850        }
36851    },
36852
36853    checkUseReviewTalk: function () {
36854        return (this.bIsReviewTalk === 'T' && EC$('.reviewtalk_review_count').length > 0) ? true : false;
36855    },
36856
36857    setDataProductNo: function () {
36858        var aAllProductNo = [];
36859        EC$('.reviewtalk_review_count').each(function () {
36860            aAllProductNo.push(EC$(this).attr('data-product-no'));
36861        });
36862
36863        CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT.aProductNo = EC$.uniqueSort(aAllProductNo);
36864    },
36865
36866    setResponseCountData: function () {
36867        if (this.aProductNo.length < 1) {
36868            return;
36869        }
36870
36871        EC$.ajax({
36872            url: '/exec/front/shop/ApiReviewtalkReviewcnt', type: 'get', data: {
36873                'product_no': this.aProductNo.join('_')
36874            }, dataType: 'json', success: function (oResponse) {
36875                if (oResponse.result === true) {
36876                    CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT.setResponseData(oResponse.data);
36877                }
36878            }
36879        });
36880    },
36881
36882    //천단위 콤마 표시
36883    number_format: function(str)
36884    {
36885        // 3자리씩 ,로 끊어서 리턴
36886        str = String(parseInt(str));
36887        var regexp = /^(-?[0-9]+)([0-9]{3})($|\.|,)/;
36888        while (regexp.test(str)) {
36889            str = str.replace(regexp, "$1,$2$3");
36890        }
36891        return str;
36892    },
36893
36894    setResponseData: function (oResponseData) {
36895        var oProductReviewCnt = oResponseData;
36896
36897        if (this.checkUseReviewTalk() === true) {
36898            EC$('.reviewtalk_review_count').each(function () {
36899                var iProductNo = EC$(this).attr('data-product-no');
36900                var sFormat = EC$(this).attr('data-format');
36901                var iReviewCount = 0;
36902
36903                if (oProductReviewCnt.hasOwnProperty(iProductNo) === true && oProductReviewCnt[iProductNo].hasOwnProperty('review_count') === true) {
36904                    iReviewCount = oProductReviewCnt[iProductNo].review_count;
36905                }
36906
36907                EC$(this).text(sFormat.replace('REVIEWTALKCOUNT', CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT.number_format(iReviewCount)));
36908
36909                var sAddClass = 'reviewtalk_count_display_' + iReviewCount;
36910                EC$(this).parent().addClass(sAddClass);
36911                EC$(this).parent().siblings('.title').addClass(sAddClass);
36912            });
36913        }
36914    }
36915};
36916
36917var EC_SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT');
36918
36919EC$(function () {
36920    CAFE24.SHOP_FRONT_REVIEW_TALK_REVIEW_COUNT.setReviewTalkCnt();
36921});
36922
36923
36924var isMobile = false;
36925var sInputMileBackground = '';
36926EC$(function() {
36927    // 모바일접속 여부
36928    // mobileWeb 값이 있으면 참조하고 없으면 m. 도메인 체크
36929    if (mobileWeb == undefined) {
36930        if (window.location.hostname.substr(0, 2) == 'm.' ||
36931            window.location.hostname.substr(0, 12) == 'mobile--shop' ||
36932            window.location.hostname.substr(0, 11) == 'skin-mobile' ||
36933            typeof EC_ROUTE !== 'undefined' && EC_ROUTE.getIsMobile() ||
36934            typeof EC_MOBILE !== 'undefined' && EC_MOBILE
36935        ) {
36936            isMobile = true;
36937        }
36938    } else {
36939        isMobile = mobileWeb;
36940    }
36941
36942    // 주문서 작성 페이지
36943    try {
36944        EC$('#np_use0').prop('checked', true);
36945
36946        EC$('#np_use0').click(function() {
36947            if (EC$(this).prop('checked') == false) {
36948                initNaverMileage();
36949                if (isMobile == true && typeof(nbp) === 'object') {
36950                    nbp.mileage.inactive();
36951                }
36952            } else {
36953                if (isMobile == true && typeof(nbp) === 'object') {
36954                    nbp.mileage.active();
36955                }
36956            }
36957            if (isMobile == false) {
36958                setNaverPoint();
36959            }
36960        });
36961    } catch (e) {}
36962
36963    // 네이버마일리지 적립금과 동시사용 불가에 따른 처리
36964    // 동시사용 불가인 경우 디자인 수정을 안했을때 기존꺼 노출
36965    try {
36966        if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == false) {
36967            EC$('div.boardView').find('#input_mile').parents('div').first().removeClass('displaynone');
36968            EC$('div.boardView').find('#np_use0').parents('div').first().removeClass('displaynone');
36969        }
36970    } catch (e) {}
36971
36972    // 적립금동시사용불가 디자인적용에 따른 처리
36973    try {
36974        if (isApplyDesignNMCanUseWithMileage()) {
36975            EC$('#either_mileage_navermileage_select0').prop('checked', true);
36976            if (isMobile == true) {
36977                EC$('input[name^="mileage_use_select"]').click(function() {
36978                    var oInputMile = getInputMileObject();
36979                    if (EC$(this).val() == 'mileage') {
36980                        initNaverMileage();
36981                        oInputMile.css('background', sInputMileBackground);
36982                        oInputMile.prop('readonly', false);
36983                        if (isApplyDesignNMCanUseWithMileage() == true) {
36984                            nbp.mileage.inactive();
36985                        }
36986                    } else {
36987                        sInputMileBackground = oInputMile.css('background');
36988                        oInputMile.val(0);
36989                        oInputMile.prop('readonly', true);
36990                        oInputMile.css('background', '#CCCCCC');
36991                        if (isApplyDesignNMCanUseWithMileage() == true) {
36992                            nbp.mileage.active();
36993                        }
36994
36995                        if (bInflowParam != false) {
36996                        } else {
36997                            EC$('#_either_mileage_acc').hide();
36998                        }
36999                    }
37000                    set_total_price();
37001                });
37002            } else {
37003                EC$('#navermileage_use_container').css({"display": "none"});
37004                EC$('input[id^="either_mileage_navermileage_select1"]').css("margin-left", "10px");
37005                EC$('label[for^="either_mileage_navermileage_select"]').css("padding-left", "3px");
37006
37007                EC$('input[name^="mileage_use_select"]').click(function() {
37008                    var oMileageUseContainer = EC$('#mileage_use_container');
37009                    var oNavermileageUseContainer = EC$('#navermileage_use_container');
37010                    var oNavermileageGuideContainer = EC$('#navermileage_guide_cotainer');
37011                    var oInputMile = getInputMileObject();
37012                    oMileageUseContainer.css('display', 'none');
37013                    oNavermileageUseContainer.css('display', 'none');
37014                    oNavermileageGuideContainer.css('display', 'none');
37015
37016                    if (EC$(this).val() == 'mileage') {
37017                        oMileageUseContainer.css('display', '');
37018                        initNaverMileage();
37019                    } else {
37020                        oNavermileageUseContainer.css('display', '');
37021                        oNavermileageGuideContainer.css('display', '');
37022                        oInputMile.val(0);
37023
37024                        //네이버 ON 상태는 꼭 이렇게 비교하라고 해서 이렇게 함
37025                        if (bInflowParam != false) {
37026                        } else {
37027                            EC$('#either_divNvPointBtnAdd').hide();
37028                            EC$('#either_divNvDefaultGuide').html('네이버 통해 방문 시 적립/사용 가능');
37029                        }
37030
37031                    }
37032
37033                    if (bInflowParam != false) {
37034                        setNaverPoint();
37035                    }
37036                    set_total_price();
37037                });
37038
37039                var oNavermileageGuideContainer = EC$('#navermileage_guide_cotainer');
37040                oNavermileageGuideContainer.css('display', 'none');
37041            }
37042        }
37043    } catch (e) {}
37044
37045
37046    // PC 쇼핑몰 >
37046 주문서 작성페이지
37047    if (isMobile == false) {
37048        try {
37049            // 네이버마일리지 가이드 폭조정(동시사용 불가능 UI)
37050            EC$('.navermileage_guide').css({'text-align': 'center', 'padding-top': '5px', 'padding-bottom': '5px', 'background-color': '#f7f7ff'});
37051
37052            // 적립률 색상 변경 & bold처리
37053            EC$('#txt_np_save').css({'color': '#1ec228', 'font-weight': 'bold'});
37054            EC$('#divNvPointOpr').css({'color': '#1ec228', 'font-weight': 'bold'});
37055        } catch (e) {}
37056    }
37057
37058    // 네이버 추가 적립률 네이버공통스크립트로 부터 가져오기
37059    try {
37060        var oNaverMileage = {
37061            'def': 0,
37062            'base': 0,
37063            'add': 0
37064        };
37065        oNaverMileage.def = EC$('#np_save_rate_default').val();
37066
37067        var oNvSaveRateBase = EC$('#naver_mileage_save_rate_base');
37068        var oNvMileageHelp = EC$('#imgNaverMileageHelp');
37069        if (EC$('.naver_mileage_compare').length > 0 || mobileWeb === true) { // 상품비교, 모바일
37070            oNvSaveRateBase = EC$('.naver_mileage_save_rate_base');
37071            oNvMileageHelp = EC$('.img_naver_mileage_help');
37072        }
37073
37074        // get save rate of naverMileage
37075        if (typeof(wcs) === 'object') {
37076            var bInflowParam = wcs.getMileageInfo();
37077            if (bInflowParam != false) {
37078                oNaverMileage.base = wcs.getBaseAccumRate();
37079                oNaverMileage.add = wcs.getAddAccumRate();
37080
37081                if (isMobile == false) {
37082                    if (EC$('.xans-order-form').length > 0) {//주문서
37083                        var oNaverStateImg = '<img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin:3px">';
37084                        EC$('#either_mileage_navermileage_select0').parents('tbody').find('th > label').html('적립금&<br>네이버마일리지<br>' + oNaverStateImg + '(택1)');
37085
37086                        EC$('#naverPointStatus').html(oNaverStateImg);
37087                        EC$('#naverPointStatus img').css({'margin': '-3px 3px 0'});
37088
37089                        EC$('#either_imgNaverMileageHelp').attr('//img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
37090
37091                        if (EC$('#np_use0').parent().find("img").attr("src") == null || EC$('#np_use0').parent().find("img").attr("src") == undefined) {
37092                            EC$('#np_use0').parent().append(oNaverStateImg);
37093                        }
37094                        EC$('#imgNaverMileageHelp').attr('src', '//img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
37095                    } else {
37096                        EC$('#imgNaverMileageHelp').css({'margin-top': '-2px'});
37097                    }
37098                }
37099
37100            } else {
37101                oNaverMileage.base = oNaverMileage.def;
37102
37103                if (isMobile == false) {
37104                    if (EC$('.xans-order-form').length > 0) {//주문서
37105                        var oNaverStateImg = '<img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png" style="margin:3px">';
37106
37107                        //택1 일 경우 (어차피 display none 일 때는 안 보임)
37108                        EC$('#either_mileage_navermileage_select0').parents('tbody').find('th > label').html('적립금&<br>네이버마일리지<br>' + oNaverStateImg + '(택1)');
37109
37110                        EC$('#naverPointStatus').html(oNaverStateImg);
37111                        EC$('#naverPointStatus img').css({'margin': '-3px 3px 0'});
37112
37113                        EC$('#np_use0').hide();
37114                        EC$('#divNvPointBtnAdd').hide();
37115                        EC$('#divNvDefaultGuide').html('네이버 통해 방문 시 적립/사용 가능');
37116
37117
37118                        EC$('label[for="np_use0"]').parent().html('네이버 마일리지' + oNaverStateImg);
37119                        EC$('#imgNaverMileageHelp').attr('src', '//img.cafe24.com/images/ec_admin/btn/icon_q_green.gif');
37120                        EC$('.naverInfo').hide();
37121                    } else {//상품상세
37122                        var sNaverStateImg = '//img.echosting.cafe24.com/design/skin/default/product/txt_naver_off2.png';
37123                        var sOnClick = "NaverMileage.openMileageIntroPopup('http://static.mileage.naver.net/static/20130708/ext/intro.html');";
37124                        oNvSaveRateBase.parent().html('네이버 마일리지 <a href="#none" onclick="' + sOnClick + '"><img src="' + sNaverStateImg + '" style="margin-top:-2px;"></a><br>(네이버 통해 방문 시 적립/사용 가능)');
37125
37126                    }
37127                }
37128
37129            }
37130        } else {
37131            oNaverMileage.base = EC$('#np_save_rate').val();
37132            oNaverMileage.add = EC$('#np_save_rate_add').val();
37133        }
37134
37135        if (oNaverMileage.base == 0 || oNaverMileage.base == '') {
37136            oNaverMileage.base = oNaverMileage.def;
37137        }
37138
37139        // casting data type
37140        oNaverMileage.def = castDataType(oNaverMileage.def);
37141        oNaverMileage.base = castDataType(oNaverMileage.base);
37142        oNaverMileage.add = castDataType(oNaverMileage.add);
37143
37144        // true -  상품상세/상품비교 페이지, false - 주문서 ì
37144ž‘성 페이지
37145        if (document.getElementById('naver_mileage_save_rate_base') != undefined && document.getElementById('naver_mileage_save_rate_base') != null) {
37146            //ECHOSTING-73678
37147            oNvMileageHelp.attr('src','//img.echosting.cafe24.com/design/skin/default/product/txt_naver_on2.png');
37148
37149            if (oNaverMileage.base > 0) {
37150                var iTotalNaverMileageRate = oNaverMileage.base + oNaverMileage.add;
37151                oNvSaveRateBase.html(iTotalNaverMileageRate + '%');
37152            } else {
37153                oNvSaveRateBase.html(oNaverMileage.def + '%');
37154            }
37155        } else {
37156            var iSaveRateSum = oNaverMileage.base;
37157            if (oNaverMileage.add > 0) {
37158                iSaveRateSum += oNaverMileage.add;
37159            }
37160            EC$('#divNvDefaultGuide .naver_mileage_save_rate_sum').html(castDataType(iSaveRateSum));
37161            EC$('#either_divNvDefaultGuide .naver_mileage_save_rate_sum').html(castDataType(iSaveRateSum));
37162        }
37163        // 모바일 > 주문서 작성 페이지인 경우에만 실행(마일리지 모바일버전은 ui노출부분이 다르다.)
37164        if (isMobile) {
37165            initNavermileageWithWcs();
37166
37167            if (EC$('#frm_order_act').length > 0) {//주문서
37168                var bUseSelectMileage = isApplyDesignNMCanUseWithMileage();
37169            }
37170
37171            if (bInflowParam != false) {
37172                if (EC$('.xans-product-detail').length > 0 || EC$('.xans-product-detaildesign').length > 0) { //상품상세
37173                    var sOnImg = '<img src="//img.echosting.cafe24.com/design/skin/mobile/txt_naver_on1.png" style="width:28px;margin-bottom:-1px;">';
37174                    EC$('.naver_mileage_save_rate_add').html('적립 ' + sOnImg);
37175                    EC$('.naverMileageSaveText').hide();
37176                } else {//주문서
37177                    EC$('#naverMileageTitle').append(' <img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin-bottom:-1px">');
37178
37179                    if (bUseSelectMileage) {//택1
37180                        EC$('#navermileage_use_container').find('label > span').append(' <img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_on1.png" style="margin-bottom:-1px">');
37181                    }
37182                }
37183            } else {
37184                if (EC$('#frm_order_act').length > 0) {//주문서
37185                    EC$('#np_use0').hide();
37186                    EC$('#naverMileageTitle').append(' <img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png">');
37187                    EC$('#_mileage_acc').html('네이버 통해 방문 시 적립/사용 가능 ');
37188
37189                    if (bUseSelectMileage) {//택1
37190                        EC$('#navermileage_use_container').find('label > span').append(' <img src="//img.echosting.cafe24.com/design/skin/default/product/txt_naver_off1.png" style="margin-bottom:-1px">');
37191                        EC$('#_mile_acc_rate').parent().hide();
37192                        EC$('#navermileage_use_container').find('.either_navermileage_use_container').append('네이버 통해 방문 시 적립/사용 가능');
37193                    }
37194
37195                } else {//상품상세
37196                    EC$('.naver_mileage_save_rate_base').hide();
37197                    var sOffImg = '<img src="//img.echosting.cafe24.com/design/skin/mobile/txt_naver_off1.png" style="width:28px;margin-bottom:-1px;">';
37198                    EC$('.naver_mileage_save_rate_add').html(sOffImg+ ' (네이버 통해 방문 시 적립/사용 가능) ');
37199                    EC$('.naverMileageSaveText').hide();
37200                }
37201            }
37202        }
37203
37204    } catch (e) {}
37205});
37206
37207var naver_reqTxId;
37208var bNvOn = false;
37209var NaverMileage = {
37210    onNvPointLayer: function(dMode)
37211    {
37212        bNvOn = true;
37213        var obj = document.getElementById('divNvPointInfo');
37214        EC$('#divNvPointInfo').show();
37215
37216        var leftMargine = obj.offsetWidth;
37217        if (dMode == 1) {
37218            var XY = EC$('#imgNaverMileageHelp').position();
37219
37220            obj.style.top = XY.top+14+'px';
37221            obj.style.left = XY.left-150+'px';
37222
37223            if (obj.attachEvent) {
37224                obj.attachEvent('onmouseover', NaverMileage.setNvOn);
37225            } else {
37226                obj.addEventListener('mouseover', NaverMileage.setNvOn, false);
37227            }
37228        }
37229        return true;
37230    },
37231    setNvOn: function() {
37232        bNvOn = true;
37233    },
37234    offNvPointLayerTic: function(bIntval)
37235    {
37236        bNvOn = false;
37237        if (bIntval == true) {
37238            setTimeout("NaverMileage.offNvPointLayer()", 200);
37239        } else {
37240            NaverMileage.offNvPointLayer();
37241        }
37242    },
37243    offNvPointLayer: function()
37244    {
37245        if (bNvOn == false) EC$('#divNvPointInfo').hide();
37246    },
37247
37248    openMileageIntroPopup: function(sUrl)
37249    {
37250        var iWidth = 404;
37251        var iHeight = 412;
37252        var iLeft = (screen.width - iWidth) / 2;
37253        var iTop = (screen.height - iHeight) / 2;
37254        var sOpt = 'width='+iWidth+', height='+iHeight+', left='+iLeft+', top='+iTop+', status=no, resizable=no';
37255
37256        window.open(sUrl, 'mileageIntroPopup', sOpt);
37257    }
37258};
37259
37260
37261function showNaverCashShowAccumPopup()
37262{
37263    if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == false) {
37264        var oInputMile = getInputMileObject();
37265        if (parseInt(oInputMile.val()) > 0) {
37266            alert(__('네이버마일리지는 적립금과 동시사용할 수 없습니다.'));
37267            return false;
37268        }
37269    }
37270
37271    if (document.getElementById('np_use0').checked == false) {
37272        alert(__('네이버 마일리지 사용/적립 시에는 좌측의 체크박스를 선택하셔야 합니다.'));
37273        return false;
37274    }
37275    var sUrl = "https://service.mileage.naver.com/service/accumulation/"+EC$('#np_api_id').val()+"?doneUrl="+EC$('#np_done_url').val();
37276
37277    var sUrl = "https://service.mileage.naver.com/service/v2/accumulation/"+EC$('#np_api_id').val()+"?doneUrl="+EC$('#np_done_url').val();
37278    if (typeof(sIsNaverMileageSandbox) !== 'undefined') {
37279        if (sIsNaverMileageSandbox == 'T') {
37280            var sUrl = "https://sandbox-service.mileage.naver.com/service/v2/accumulation/"+EC$('#np_api_id').val()+"?doneUrl="+EC$('#np_done_url').val();
37281        }
37282    }
37283
37284    if (naver_reqTxId) {
37285        sUrl = sUrl + "&reqTxId=" + naver_reqTxId;
37286    }
37287
37288    var sNcisy = new String();
37289    if (typeof(wcs) === 'object') {
37290        var inflowParam = wcs.getMileageInfo();
37291        if (inflowParam != false) {
37292            sNcisy = inflowParam;
37293        }
37294    } else {
37295        sNcisy = EC$('#np_ncisy').val();
37296    }
37297
37298    sUrl = sUrl + "&Ncisy=" + sNcisy;
37299    sUrl = sUrl + "&sig=" + EC$('#np_req_sig').val();
37300    sUrl = sUrl + "&timestamp=" + EC$('#np_timestamp').val();
37301
37302    try {
37303        if (typeof(EC$('#r_total_price').val()) !== 'undefined') {
37304            var iMaxUseAmount = CAFE24.SHOP_PRICE.toShopPrice(EC$('#r_total_price').val());
37305            sUrl = sUrl + "&maxUseAmount=" + iMaxUseAmount;
37306        }
37307    } catch (e) {}
37308
37309    var sWinName = document.getElementById('np_window_name').value;
37310    window.open(sUrl , sWinName, "width=496,height=434,status=no,resizable=no");
37311}
37312
37313function enableNaverCashPanel(baseAccumRate, addAccumRate, useAmount, balanceAmount, reqTxId, sig, resultCode, mileageUseAmount, cashUseAmount, totalUseAmount)
37314{
37315    naver_reqTxId = reqTxId;
37316
37317    if (CAFE24.SHOP_PRICE.toShopPrice(stringReplace(',','',EC$('#total_price').val())) + parseInt(EC$('#np_use_amt').val()) < parseInt(totalUseAmount)) {
37318        alert(__('결제하셔야 할 금액보다 사용금액이 큽니다. 다시 사용금액을 입력해주세요'));
37319        return false;
37320    }
37321
37322    if (EC$('#np_req_tx_id').val() != null && reqTxId != '' && reqTxId != 0 && resultCode == 'E1000') {
37323        EC$('#np_req_tx_id').val(reqTxId);
37324        EC$('#np_save_rate').val(baseAccumRate);
37325        EC$('#np_save_rate_add').val(addAccumRate);
37326        EC$('#np_use_amt').val(useAmount);
37327        EC$('#np_mileage_use_amount').val(mileageUseAmount);
37328        EC$('#np_cash_use_amount').val(cashUseAmount);
37329        EC$('#np_total_use_amount').val(totalUseAmount);
37330        EC$('#np_use_amt').val(useAmount);
37331        EC$('#np_balance_amt').val(balanceAmount);
37332        EC$('#np_sig').val(sig);
37333        if (EC$('#np_use0').prop('checked') == true) {
37334            EC$('#np_use').val('T');
37335        } else {
37336            EC$('#np_use').val('');
37337        }
37338    } else {
37339        initNaverMileage();
37340    }
37341
37342    EC$('#imgNaverMileageHelp').show();
37343
37344    // PC쇼핑몰인경우만 ui에 사용 마일리지&캐쉬 정보 적용
37345    if (isMobile == false) {
37346        setNaverPoint();
37347    }
37348}
37349
37350
37351function setNaverPoint()
37352{
37353    try {
37354
37355        var bUseNaverMileage = false;
37356        if (isApplyDesignNMCanUseWithMileage()) {
37357            if (EC$('#either_mileage_navermileage_select1').prop('checked') == true) {
37358                bUseNaverMileage = true;
37359            }
37360        } else {
37361            if (EC$('#np_use0').prop('checked') == true) {
37362                bUseNaverMileage = true;
37363            }
37364        }
37365
37366        if (bUseNaverMileage == false) {
37367            initNaverMileage();
37368        }
37369
37370        var sNpReqTxId = document.getElementById('np_req_tx_id').value;
37371        var iNpUseAmt = CAFE24.SHOP_PRICE.toShopPrice(document.getElementById('np_use_amt').value);
37372        var iNpMileageUseAmt = CAFE24.SHOP_PRICE.toShopPrice(document.getElementById('np_mileage_use_amount').value);
37373        var iNpCashUseAmt = CAFE24.SHOP_PRICE.toShopPrice(document.getElementById('np_cash_use_amount').value);
37374        var iNpTotalUseAmt = CAFE24.SHOP_PRICE.toShopPrice(document.getElementById('np_total_use_amount').value);
37375        var iNpBalanceAmt = CAFE24.SHOP_PRICE.toShopPrice(document.getElementById('np_balance_amt').value);
37376        var iNpSaveRate = parseFloat(document.getElementById('np_save_rate').value);
37377        var iNpSaveRateAdd = parseFloat(document.getElementById('np_save_rate_add').value);
37378        var iNpSaveRateTotal = iNpSaveRate + iNpSaveRateAdd;
37379
37380        if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
37381            var elmNvDefaultGuide = document.getElementById('either_divNvDefaultGuide');
37382            var oDivNvPointUse = document.getElementById('either_divNvPointUse');
37383            var oDivNvPointSave = document.getElementById('either_divNvPointSave');
37384            var oDivNvPointOpr = document.getElementById('either_divNvPointOpr');
37385            var oDivNvPointBtnAdd = document.getElementById('either_divNvPointBtnAdd');
37386            var oDivNvPointBtnMod = document.getElementById('either_divNvPointBtnMod');
37387            var oTxtNpUse = document.getElementById('either_txt_np_use');
37388            var oTxtNpSave = document.getElementById('either_txt_np_save');
37389            var oExTxNpSave = document.getElementById('either_ex_tx_np_save');
37390            var oExTxNpUse = document.getElementById('either_ex_tx_np_use');
37391
37392            var bInflowParam = wcs.getMileageInfo();
37393
37394        } else {
37395            var elmNvDefaultGuide = document.getElementById('divNvDefaultGuide');
37396            var oDivNvPointUse = document.getElementById('divNvPointUse');
37397            var oDivNvPointSave = document.getElementById('divNvPointSave');
37398            var oDivNvPointOpr = document.getElementById('divNvPointOpr');
37399            var oDivNvPointBtnAdd = document.getElementById('divNvPointBtnAdd');
37400            var oDivNvPointBtnMod = document.getElementById('divNvPointBtnMod');
37401            var oTxtNpUse = document.getElementById('txt_np_use');
37402            var oTxtNpSave = document.getElementById('txt_np_save');
37403            var oExTxNpSave = document.getElementById('ex_tx_np_save');
37404            var oExTxNpUse = document.getElementById('ex_tx_np_use');
37405        }
37406
37407
37408        if (isUseNaverMileage() == false) {
37409            elmNvDefaultGuide.style.display = '';
37410        }
37411
37412        oDivNvPointUse.style.display = 'none';
37413        oDivNvPointSave.style.display = 'none';
37414        oDivNvPointOpr.style.display = 'none';
37415        oDivNvPointBtnAdd.style.display = 'none';
37416        oDivNvPointBtnMod.style.display = 'none';
37417
37418        if (iNpTotalUseAmt > 0 && iNpSaveRate > 0) {//& opr
37419            oDivNvPointOpr.style.display = 'inline';
37420        }
37421        if (iNpTotalUseAmt > 0 || iNpSaveRateTotal > 0) {
37422            oDivNvPointBtnMod.style.display = 'inline';
37423        } else {
37424            oDivNvPointBtnAdd.style.display = 'inline';
37425        }
37426        if (iNpSaveRateTotal > 0) {//적립
37427            if (elmNvDefaultGuide) {
37428                elmNvDefaultGuide.style.display = 'none';
37429            }
37430
37431            oDivNvPointSave.style.display = 'inline';
37432            oTxtNpSave.innerHTML = oExTxNpSave.innerHTML.replace("[np_rate]", iNpSaveRateTotal);
37433        }
37434
37435        set_total_price();
37436
37437        if (iNpTotalUseAmt > 0) {
37438            if (elmNvDefaultGuide) {
37439                elmNvDefaultGuide.style.display = 'none';
37440            }
37441
37442            oDivNvPointUse.style.display = 'inline';
37443            var sTmp = oExTxNpUse.innerHTML;
37444
37445            var aUseNaverValue = new Array();
37446            if (iNpMileageUseAmt > 0) {
37447                aUseNaverValue.push('마일리지 ' + addCommas(iNpMileageUseAmt) + '원');
37448            }
37449            if (iNpCashUseAmt > 0) {
37450                aUseNaverValue.push('캐쉬 ' + addCommas(iNpCashUseAmt) + '원');
37451            }
37452
37453            oTxtNpUse.innerHTML = aUseNaverValue.join(' + ') + ' 사용';
37454        }
37455
37456        paymethod_display(EC$(':input:radio[name="addr_paymethod"]:checked').val());
37457
37458    } catch (e) {
37459        initNaverMileage();
37460        set_total_price();
37461    }
37462
37463}
37464
37465
37466/**
37467 * 네이버 마일리지/캐쉬 reset
37468 * @return void
37469 */
37470function resetNaverPoint()
37471{
37472    try {
37473        EC$('#np_use0').prop('checked',false);
37474        setNaverPoint();
37475        EC$('#np_use0').prop('checked',true);
37476        paymethod_display(EC$(':input:radio[name="addr_paymethod"]:checked').val());
37477    } catch (e) {}
37478}
37479
37480
37481/**
37482 * 네이버 마일리지/캐쉬 사용안함
37483 * @return void
37484 */
37485function initNaverMileage()
37486{
37487    // clear value
37488    try {
37489        document.getElementById('np_req_tx_id').value = "";
37490        document.getElementById('np_use_amt').value = 0;
37491        document.getElementById('np_mileage_use_amount').value = 0;
37492        document.getElementById('np_cash_use_amount').value = 0;
37493        document.getElementById('np_total_use_amount').value = 0;
37494        document.getElementById('np_balance_amt').value = 0;
37495        document.getElementById('np_save_rate').value = 0;
37496        document.getElementById('np_save_rate_add').value = 0;
37497        document.getElementById('np_sig').value = "";
37498    } catch (e) {}
37499
37500    // init design
37501    try {
37502        if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
37503            var oDivNvPointUse = document.getElementById('either_divNvPointUse');
37504            var oDivNvPointSave = document.getElementById('either_divNvPointSave');
37505            var oDivNvPointOpr = document.getElementById('either_divNvPointOpr');
37506            var oDivNvPointBtnAdd = document.getElementById('either_divNvPointBtnAdd');
37507            var oDivNvPointBtnMod = document.getElementById('either_divNvPointBtnMod');
37508        } else {
37509            var oDivNvPointUse = document.getElementById('divNvPointUse');
37510            var oDivNvPointSave = document.getElementById('divNvPointSave');
37511            var oDivNvPointOpr = document.getElementById('divNvPointOpr');
37512            var oDivNvPointBtnAdd = document.getElementById('divNvPointBtnAdd');
37513            var oDivNvPointBtnMod = document.getElementById('divNvPointBtnMod');
37514        }
37515        oDivNvPointUse.style.display = 'none';
37516        oDivNvPointSave.style.display = 'none';
37517        oDivNvPointOpr.style.display = 'none';
37518        oDivNvPointBtnAdd.style.display = 'inline';
37519        oDivNvPointBtnMod.style.display = 'none';
37520    } catch (e) {}
37521
37522    //  clear trasaction id
37523    try {
37524        naver_reqTxId = '';
37525    } catch (e) {}
37526}
37527
37528
37529/**
37530 * 네이버 마일리지/캐쉬 사용 여부
37531 * @return boolean
37532 */
37533function isUseNaverMileage()
37534{
37535    var bIsUse = false;
37536    try {
37537        if (EC$('#np_req_tx_id').val() != '' || EC$('#np_save_rate').val() > 0) {
37538            bIsUse = true;
37539        }
37540    } catch (e) {}
37541    return bIsUse;
37542}
37543
37544/**
37545 * 자료형 cast
37546 * @param float fData 숫자
37547 * @return mixed
37548 */
37549function castDataType(fData)
37550{
37551    if (isNaN(fData) == false) {
37552        if ((fData % 1) == 0) {
37553            return parseInt(fData);
37554        } else {
37555            return parseFloat(fData);
37556        }
37557    } else {
37558        return 0;
37559    }
37560}
37561
37562
37563/**
37564 * 모바일 마일리지 Library 초기화
37565 */
37566function initNavermileageWithWcs()
37567{
37568    try {
37569        // 네이버마일리지 관련 변수가 controller에서 assign이 안되어 있으면 아래부분 실행시도를 안한다.
37570        if (typeof(nbp) === 'object') {
37571
37572            var iMaxuseAmount = parseInt(EC$('#total_price').val().replace(/,/g, ''));
37573            var iBaseAccumRate = parseFloat(EC$('#np_save_rate_default').val());
37574            var iTimestamp = parseInt(EC$('#np_timestamp').val());
37575            var sId = '_mileage_acc';
37576            if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
37577                sId = '_either_mileage_acc';
37578            }
37579
37580            var bResult = nbp.mileage.initWithWcs({
37581                'sId': sId,
37582                'sApiId': EC$('#np_api_id').val(),
37583                'sDoneUrl': decodeURIComponent(EC$('#np_done_url').val()),
37584                'nMaxUseAmount': iMaxuseAmount,
37585                'sSig': EC$('#np_req_sig').val(),
37586                'nTimestamp': iTimestamp,
37587                'nBaseAccumRate': iBaseAccumRate,
37588                'bActive': true,
37589                'event': {
37590                    'beforeAccum': function(oEvent) { //적립/사용페이지가 뜨기 직전 호출된다.
37591                        set_total_price();
37592                        nbp.mileage.setMaxUseAmount(getNavermileageMaxAmount());
37593                        if (oEvent.bActive === false) { //마일리지 모듈이 비활성화 상태에서 적립/사용 버튼 클릭 callback 구현
37594                            alert('네이버 마일리지를 사용/적립하려면, 먼저 \'네이버 마일리지\'를 선택해야합니다. ');
37595                            return false;
37596                        }
37597                    },
37598                    'accum': function(aRetVal) {
37599                        aRetVal.resultCode = convertResultCode(aRetVal.resultCode);
37600                        enableNaverCashPanel(aRetVal.baseAccumRate, aRetVal.addAccumRate, aRetVal.mileageUseAmount, aRetVal.balanceAmount, aRetVal.reqTxId, aRetVal.sig, aRetVal.resultCode, aRetVal.mileageUseAmount, aRetVal.cashUseAmount, aRetVal.totalUseAmount);
37601                        set_total_price();
37602                    }
37603                }
37604            });
37605
37606            if (bResult) {
37607                if (isNMCanUseWithMileage() == false && isApplyDesignNMCanUseWithMileage() == true) {
37608                    nbp.mileage.inactive();
37609                }
37610            } else {
37611                if (EC$('#np_is_use').val() == 'T' && document.getElementById('_mileage_acc') != null && document.getElementById('_mileage_acc') != undefined) {
37612                    alert('네이버마일리지 적립/사용 초기화가 정상적이지 않습니다. 지속발생시 운영자에게 문의 해주세요.');
37613                }
37614            }
37615        }
37616    } catch (e) {}
37617}
37618
37619/**
37620 * pg모듈에서 리턴해주는 형식으로 변환
37621 * @param string sCode 코드
37622 * @return string
37623 */
37624function convertResultCode(sCode)
37625{
37626    if (sCode == 'OK') {
37627        return 'E1000';
37628    } else if (sCode == 'CANCEL') {
37629        return 'E1001';
37630    } else if (sCode == 'ERROR') {
37631        return 'E1002';
37632    } else {
37633        return 'E1100';
37634    }
37635}
37636
37637/**
37638 *모바일 마일리지 최대사용가능 금액(결제금액 + 마일리지 사용금액)
37639 * @return int
37640 */
37641function getNavermileageMaxAmount()
37642{
37643    var iMaxAmount = CAFE24.SHOP_PRICE.toShopPrice(EC$('#total_price').val().replace(/,/g, ''));
37644    iMaxAmount += check_parseInt(getUseNaverMileageCash());
37645
37646    return iMaxAmount;
37647}
37648
37649var COLORCHIP_FRONT = {
37650    setFrontInit: function()
37651    {
37652        EC$('.xans-product-colorchip').find('.chips').each(function() {
37653
37654            var sColor = COLORCHIP_FRONT.RGB2Color(EC$(this).css('backgroundColor'));
37655            var sCursor = '';
37656            if (COLORCHIP_FRONT.checkValidation(sColor) === true && EC_FRONT_JS_CONFIG_SHOP.aOptionColorchip[sColor] != '') {
37657                if (CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE.isDisplayImageDesign() === false) {
37658                    return;
37659                }
37660                sCursor = 'pointer';
37661                EC$(this).on('mouseover click', function() {
37662                    CAFE24.SHOP_FRONT_NEW_OPTION_EXTRA_IMAGE.setImage(EC_FRONT_JS_CONFIG_SHOP.aOptionColorchip[sColor], true);
37663                });
37664            }
37665            EC$(this).css('cursor', sCursor);
37666        });
37667    },
37668
37669    RGB2Color: function (sRgb)
37670    {
37671        try {
37672            rgb = sRgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
37673            if (rgb === null) {
37674                return sRgb.toString().toUpperCase();
37675            } else {
37676                return '#' + COLORCHIP_FRONT.byte2Hex(rgb[1]) + COLORCHIP_FRONT.byte2Hex(rgb[2]) + COLORCHIP_FRONT.byte2Hex(rgb[3]);
37677            }
37678        } catch (e) {
37679            return '';
37680        }
37681    },
37682
37683    byte2Hex: function (n)
37684    {
37685        var nybHexString = "0123456789ABCDEF";
37686        return String(nybHexString.substr((n >> 4) & 0x0F,1)) + nybHexString.substr(n & 0x0F,1);
37687    },
37688
37689    checkValidation: function(sColor)
37690    {
37691        var regex = /^#?[0-9A-F]{6}$/i;
37692        return regex.test(sColor);
37693    }
37694};
37695
37696EC$(function() {
37697    COLORCHIP_FRONT.setFrontInit();
37698});
37699
37700/**
37701 * 바로구매주문 상품모듈 라이브러리
37702 */
37703CAFE24.SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY = function() {
37704    // 장바구니 담기
37705    var setDirectBuyOrderBasket = function ()
37706    {
37707        // 바로구매 주문서 아님
37708        if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm !== true) {
37709            return;
37710        }
37711        // 비회원 구매제한
37712        if (sIsDisplayNonmemberPrice === 'T' || is_soldout_icon === 'T') {
37713            return;
37714        }
37715        // 1+N 제한
37716        if (typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE !== 'undefined' && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNo) === true) {
37717            return;
37718        }
37719        product_submit('direct_buy', '/exec/front/order/basket/');
37720    };
37721
37722    // 장바구니 리셋
37723    var resetDirectBuyOrderBasket = function ()
37724    {
37725        // reset basket
37726        CAFE24.SHOP_FRONT_ORDERFORM_DIRECTBUY.proc.setOrderForm(TotalAddSale.getDirectBuyParam());
37727    };
37728
37729    // 바로구매주문서 접속제한
37730    var setAccessRestriction = function ()
37731    {
37732        if (EC_FRONT_JS_CONFIG_SHOP.bDirectBuyOrderForm !== true) {
37733            return;
37734        }
37735        if (sIsDisplayNonmemberPrice === 'T' || sIsNonmemberLimit === 'T') {
37736            alert(__('회원만 구매 가능합니다. 비회원인 경우 회원가입 후 이용하여 주세요.'));
37737            btn_action_move_url('/member/login.html');
37738        } else if (typeof CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE !== 'undefined' && CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig.hasOwnProperty(iProductNo) === true) {
37739            // 1+N 제한
37740            alert(sprintf(__('EVENT.ITEM.ORDER.AT.MALL', 'SHOP.JS.FRONT.NEW.PRODUCT.DIRECTBUY'), CAFE24.SHOP_FRONT_PRODUCT_DETAIL_BUNDLE.oBundleConfig[iProductNo].bundle_quantity));
37741            btn_action_move_url('/');
37742        }
37743    };
37744    // 주문가능한 품목데이터가 있는지 확인
37745    var getValidOptionData = function () {
37746        var oParam = TotalAddSale.getDirectBuyParam();
37747        if (oParam['items'] === null) {
37748            return false;
37749        }
37750        return true;
37751
37752    };
37753
37754    return {
37755        setDirectBuyOrderBasket: function (iTotalCount) {
37756            setDirectBuyOrderBasket(iTotalCount);
37757        },
37758        setAccessRestriction: function () {
37759            setAccessRestriction();
37760        },
37761        resetDirectBuyOrderBasket: function() {
37762            resetDirectBuyOrderBasket();
37763        },
37764        getValidOptionData: function() {
37765            return getValidOptionData();
37766        }
37767    };
37768}();
37769
37770var EC_SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_PRODUCT_DIRECT_BUY');
37771
37772EC$(function()
37773{
37774    // 썸네일 이미지에 대한 마우스 오버 액션 (sUseAddimageAction: 추가 이미지 액션)
37775    EC$('.ThumbImage').mouseover(function() {
37776        if (ImageAction.sUseAddimageAction === 'O') {
37777            ImageAction.setThumbImageAction(EC$(this));
37778        }
37779    });
37780
37781    // 썸네일 이미지에 대한 마우스 클릭 액션 (sUseAddimageAction: 추가 이미지 액션)
37782    EC$('.ThumbImage').click(function() {
37783        if (ImageAction.sUseAddimageAction === 'C') {
37784            ImageAction.setThumbImageAction(EC$(this));
37785        }
37786    });
37787
37788    // ECHOSTING-456684 - webp이미지가 리사이징 안되었을 경우 gif이미지 노출
37789    EC$('.BigImage').on('error', function() {
37790        var sSrc = EC$('.BigImage').attr('src');
37791        if (sSrc.substring(sSrc.lastIndexOf('.')) !== '.webp') {
37792            return;
37793        }
37794
37795        sSrc = sSrc.substring(0, sSrc.lastIndexOf('.')) + '.gif';
37796        EC$('.BigImage').attr('src', sSrc);
37797    });
37798
37799    ImagePreview.eBigImgSrc = EC$('.BigImage').attr('src');
37800
37801    var bPreview = (EC$.data(document,'Preview') == 'T') ? true : false;
37802
37803    // 제일 처음 로딩시 이미지값 저장해놓음..뉴상품에서는 small == big 이지만 구상품 스킨에서는
37804   // tiny와 big의 이미지명 틀림!!
37805    ImagePreview.eBigImgSrc = EC$('.BigImage').attr('src');
37806
37807    if (bPreview === true) {
37808        ImagePreview.Init();
37809    }
37810});
37811
37812var ImageAction = {
37813    // 확대 이미지
37814    sBigSrc: EC$('.BigImage').attr('src'),
37815
37816    // 추가 이미지 액션 (기본값 - O: 마우스 오버)
37817    sUseAddimageAction: 'O',
37818
37819    // 썸네일 마우스 액션 (마우스 오버 및 클릭에 대한 중복으로 인해 분기)
37820    setThumbImageAction: function(target)
37821    {
37822        EC$('#prdDetailImg').attr('rel', EC$(this).parent().index());
37823
37824        var sSrc = target.attr('src');
37825
37826        if (sSrc.indexOf('/product/tiny/') > 0) {
37827            if (typeof this.sBigSrc === 'string' && sSrc.substring(sSrc.lastIndexOf('/')) === this.sBigSrc.substring(this.sBigSrc.lastIndexOf('/'))) {
37828                sSrc = sSrc.replace('/product/tiny/', '/product/big/');
37829            } else {
37830                sSrc = ImagePreview.eBigImgSrc;
37831            }
37832
37833            EC$('.BigImage').attr('src', sSrc);
37834
37835            // 일단 복잡한 과정은 제외하고 파일 교체만 처리
37836        } else if (sSrc.indexOf('/product/small/') > 0) {
37837            if (typeof this.sBigSrc === 'string' && sSrc.substring(sSrc.lastIndexOf('/')) === this.sBigSrc.substring(this.sBigSrc.lastIndexOf('/'))) {
37838                sSrc = sSrc.replace('/product/small/', '/product/big/');
37839            } else {
37840                sSrc = ImagePreview.eBigImgSrc;
37841            }
37842
37843            EC$('.BigImage').attr('src', sSrc);
37844        } else if (sSrc.indexOf('/thumb/') > 0) {
37845            EC$('.BigImage').attr('src', ImagePreview.eBigImgSrc);
37846        } else {
37847            // 추가 이미지
37848            sSrc = sSrc.replace('/product/extra/small/', '/product/extra/big/');
37849
37850            EC$('.BigImage').attr('src', sSrc);
37851
37852            // 단일 선택형 + 추가 이미지 액션이 C(마우스 클릭)인 경우 추가 이미지에 선택에 대한 품목 선택 처리
37853            if (oSingleSelection.isItemSelectionTypeS() === true && this.sUseAddimageAction === 'C') {
37854                // 품목 코드가 있을 경우 해당되는 UI 선택
37855                if (target.attr('item_code') !== '') {
37856                    CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValueByAddImage(target.attr('item_code'));
37857                }
37858            }
37859        }
37860    }
37861};
37862
37863var ImagePreview =
37864{
37865    bNewProduct: false,
37866    eTarget: null,
37867    eBigImgSrc: null,
37868    Init: function()
37869    {
37870        this.eTarget = EC$('.xans-product-image img.BigImage');
37871        this.eTarget.parent().addClass('cloud-zoom');
37872        this.showNotice();
37873        ImagePreview.setZoom();
37874
37875    },
37876    showNotice: function()
37877    {
37878        var sLang = SHOP.getLanguage();
37879        if (sLang == 'ja_JP') {
37880            var iImgWidth = 107;
37881        } else {
37882            var iImgWidth = 85;
37883        }
37884
37885        var sZoomImage = '//img.echosting.cafe24.com/design/skin/admin/'+sLang+'/txt_product_zoom.gif';
37886
37887        var sLeft = this.eTarget.width() / 2 - iImgWidth;
37888        EC$('<div id="zoomNotice"><img src="'+sZoomImage+'"></div>').css(
37889            {
37890                'height': '0px',
37891                'position': 'relative',
37892                'opacity': '0.75',
37893                'KHTMLOpacity': '0.75',
37894                'MozOpacity': '0.75',
37895                'filter': 'Alpha(opacity=75)',
37896                'top': '-27px',
37897                'margin-left': sLeft
37898            }).appendTo(this.eTarget.parent());
37899    },
37900    setZoom: function()
37901    {
37902        EC$('.cloud-zoom').mouseover(function()
37903        {
37904            EC$('.cloud-zoom').CloudZoom();
37905        });
37906    },
37907    //ECHOSTING-236342 preview(확대보기) 기능에서 상세페이지 연결 오류
37908    setIframeSrcReplaceProductNo: function(iProductNo)
37909    {
37910        if (typeof(iProductNo) === 'undefined' || iProductNo == 0) {
37911            return;
37912        }
37913
37914        var oTargetIframe = EC$(parent.document).find('#modalContent');
37915
37916        if (typeof(EC$(oTargetIframe).attr('src')) === 'undefined') {
37917            return;
37918        }
37919
37920        // 목록에서의 상품 확대 보기시 상위 iframe src의 파라미터 product_no 를 다음,이전 화면 이동시 해당 상품번호 받아와 변환
37921        var sUrlReplaceProductNo = EC$(oTargetIframe).attr('src').replace(/product_no=[\d]+/,'product_no=' + iProductNo);
37922
37923        EC$(oTargetIframe).attr('src', sUrlReplaceProductNo);
37924    },
37925    viewProductBtnClick: function(sActionType)
37926    {
37927        if (typeof(iProductNo) === 'undefined' || EC$.inArray(sActionType, ['next', 'prev']) < 0) {
37928            return;
37929        }
37930
37931        this.bNewProduct = true;
37932        var sParamUrl = ImagePreview.getViewProductUrl(iProductNo);
37933        var aMatchResult = ImagePreview.getLocationPathMatchResult();
37934        var sRefDoc = (aMatchResult !== null) ? 'product' : location.pathname;
37935
37936        EC$.ajax({
37937            url: '/exec/front/Product/Detailnavi'+ sParamUrl + '&refdoc='+ sRefDoc +'&navi_action='+ sActionType,
37938            type: 'GET',
37939            async: false,
37940            dataType: 'json',
37941            success: function(data) {
37942                if (data.result === true) {
37943                    location.href = ImagePreview.getViewProductUrl(data.response.product_no, data.response.seo_url_link);
37944                } else {
37945                    if (data.response.empty_msg !== null) {
37946                        alert(data.response.empty_msg);
37947                    }
37948                }
37949            }
37950        });
37951    },
37952    getLocationPathMatchResult: function()
37953    {
37954        var sPath = document.location.pathname;
37955        var sPattern = /^\/product\/(.+)\/([0-9]+)(\/.*)/;
37956        return sPath.match(sPattern);
37957    },
37958    getViewProductUrl: function(iProductNo, sSeoUrl)
37959    {
37960        var aMatchResult = ImagePreview.getLocationPathMatchResult();
37961        var bExistSeoUrl = (sSeoUrl !== '' && typeof(sSeoUrl) !== 'undefined') ? true : false;
37962        var sResultUrl = '';
37963
37964        ImagePreview.setIframeSrcReplaceProductNo(iProductNo);
37965
37966        if (aMatchResult !== null) {
37967            if (bExistSeoUrl === true) {
37968                sResultUrl = sSeoUrl;
37969            } else {
37970                sResultUrl = (this.bNewProduct === false) ? ImagePreview.getOldProductDetailUrl(iProductNo) : '?product_no=' + iProductNo + '&cate_no='+ iCategoryNo + '&display_group=' + iDisplayGroup;
37971            }
37972        } else {
37973            var sSearchRelplace = location.search.replace(/product_no=[\d]+/,'product_no=' + iProductNo);
37974            sResultUrl = (this.bNewProduct === true) ? sSearchRelplace : location.pathname + sSearchRelplace;
37975        }
37976
37977        return sResultUrl;
37978    },
37979    getOldProductDetailUrl: function(iProductNo)
37980    {
37981        var sSearchString = '';
37982
37983        if (location.search) {
37984            sSearchString = '&' + location.search.replace(/\?/,'');
37985        }
37986
37987        return '/front/php/product.php?product_no=' + iProductNo + sSearchString;
37988    }
37989};
37990
37991// 이전, 다음 상품 보기
37992function viewProduct(iProductNo, sSeoUrl)
37993{
37994    location.href = ImagePreview.getViewProductUrl(iProductNo, sSeoUrl);
37995}
37996
37997
37998// 팝업
37999function product_popup(sLink, sName, sOption, ele)
38000{
38001    var aMatchResult = ImagePreview.getLocationPathMatchResult();
38002    var sSearchQuery = location.search;
38003
38004    if (aMatchResult) {
38005        if (sSearchQuery) {
38006            sSearchQuery = sSearchQuery + '&product_no=' + aMatchResult[2];
38007        } else {
38008            sSearchQuery = '?product_no=' + aMatchResult[2];
38009        }
38010    }
38011
38012    try {
38013        var sDetailUri = '';
38014        if (ele) {
38015            var iOrder = EC$(ele).attr('rel');
38016            if (window.location.href.indexOf('/surl/P/') != -1) {
38017                sDetailUri = '?product_no=' + parseInt(window.location.href.split('/surl/P/')[1]) + '&order=' + iOrder;
38018            } else {
38019                sDetailUri = sSearchQuery + '&order=' + iOrder;
38020            }
38021        }
38022        window.open('/' + sLink + sDetailUri, sName, sOption);
38023    } catch (e) {
38024        window.open('/' + sLink + sSearchQuery, sName, sOption);
38025    }
38026}
38027
38028// window.open 메소드 인수 관련 오류 패치
38029(function() {
38030    var originWindowOpen = window.open;
38031    window.open = function() {
38032        return originWindowOpen.apply(null, Array.apply(null, arguments).slice(0, 3));
38033    };
38034})();
38035
38036/**
38037 * 목록 > 분류 좋아요.
38038 */
38039CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY = {
38040    bIsReady: false, // 좋아요 클릭준비완료 여부.
38041    bIsSetEvent: false, // 좋아요 버튼 이벤트 지정 여부.
38042    aImgSrc: [], // 좋아요(On/Off) 아이콘 경로.
38043    aMyLikeCateNo: [], // 유저가 이미 좋아요 선택한 분류번호
38044
38045    // 분류 좋아요 초기화
38046    init: function() {
38047        // 분류 좋아요 사용안함시
38048        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.aConfig.bIsUseLikeCategory !== true) {
38049            return;
38050        }
38051
38052        // ajax 유저가 이미 좋아요 선택한 분류번호 얻기 + 아이콘세팅
38053        this.setLoadData();
38054    },
38055
38056    // 유저가 이미 좋아요 선택한 분류번호 얻기 + 아이콘세팅
38057    setLoadData: function() {
38058        if (EC$('.likeCateIcon').count < 1) {
38059            return;
38060        }
38061
38062        var self = this;
38063
38064        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getMyLikeCategoryNoInList(function(aData) {
38065            self.aImgSrc = aData.imgSrc;
38066            self.aMyLikeCateNo = aData.rows;
38067
38068            // 아이콘(on) 세팅
38069            self.setMyLikeCategoryIconOn();
38070
38071            // 좋아요 클릭 이벤트핸들러 지정
38072            if (self.bIsSetEvent === false) {
38073                self.setEventHandler();
38074                self.bIsSetEvent = true;
38075            }
38076        }, function() {
38077            self.bIsReady = true;
38078        });
38079    },
38080
38081    // 페이지 로드시 유저가 좋아요한 분류 On.아이콘으로 변경
38082    setMyLikeCategoryIconOn: function() {
38083        var aData = this.aMyLikeCateNo;
38084
38085        for (var i=0; i < aData.length; i++) {
38086            // selected 스타일 적용
38087            EC$(".likeCate_" + aData[i].category_no).each(function() {
38088                EC$(this).addClass('selected');
38089            });
38090
38091            // 아이콘 이미지경로 변경
38092            EC$(".likeCateIcon[category_no='" + aData[i].category_no + "']").each(function() {
38093                EC$(this).attr({'src': CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.aImgSrc.on, 'icon_status': 'on'});
38094            });
38095        }
38096    },
38097
38098    setEventHandler: function() {
38099        try {
38100            EC$(document).on('click', '.likeCate', CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.clickLikeIcon);
38101        } catch (e) {}
38102    },
38103
38104    clickLikeIcon: function() {
38105        if (CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.bIsReady === false) {
38106            return;
38107        }
38108
38109        // 클릭한 분류 좋아요수 + 아이콘 정보 얻기
38110        var iCateNo = EC$('.likeCateIcon', this).attr('category_no');
38111        var sIconStatus= EC$('.likeCateIcon', this).attr('icon_status');
38112        // 카운트 string > int 형으로 변환 (ECHOSTING-260504)
38113        var iLikeCount = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getNumericRemoveCommas(EC$('.likeCateCount', this).text());
38114
38115        // 아이콘경로 및 좋아요수 증감처리
38116        var sNewImgSrc = sNewIconStatus = "";
38117        var iNewLikeCount = 0;
38118        var oLikeWrapNode = EC$(".likeCate_" + iCateNo);
38119
38120        if (sIconStatus === 'on') {
38121            sNewIconStatus = 'off';
38122            sNewImgSrc = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.aImgSrc.off;
38123            if (iLikeCount > 0) {
38124                iNewLikeCount = --iLikeCount;
38125            }
38126
38127            oLikeWrapNode.each(function() {
38128                EC$(this).removeClass('selected');
38129            });
38130        } else {
38131            sNewIconStatus = 'on';
38132            sNewImgSrc = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.aImgSrc.on;
38133            iNewLikeCount = ++iLikeCount;
38134
38135            // 동일상품 selected 스타일적용
38136            oLikeWrapNode.each(function() {
38137                EC$(this).addClass('selected');
38138            });
38139        }
38140
38141        // 좋아요 카운트 number_format (ECHOSTING-260504)
38142        iNewLikeCount = CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.getNumberFormat(iNewLikeCount);
38143
38144        // 동일분류 아이콘 변경
38145        EC$(".likeCateIcon[category_no='" + iCateNo + "']").each(function() {
38146            EC$(this).attr({'src': sNewImgSrc, 'icon_status': sNewIconStatus});
38147        });
38148
38149        // 동일분류 좋아요수 변경
38150        EC$('.likeCateCount_' + iCateNo).each(function() {
38151            EC$(this).text(iNewLikeCount);
38152        });
38153
38154        // ajax 호출 좋아요수(상품) + 마이쇼핑 좋아요 저장
38155        CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.submitMyLikeCategory(iCateNo, sNewIconStatus);
38156    },
38157
38158    // 분류 좋아요수 + 마이쇼핑 좋아요 저장
38159    submitMyLikeCategory: function(iCateNo, sIconStatus) {
38160        if (sIconStatus === 'on') {
38161            this.aMyLikeCateNo.push(iCateNo);
38162        } else {
38163            this.aMyLikeCateNo.pop(iCateNo);
38164        }
38165
38166        EC$.ajax({
38167            url: '/exec/front/shop/LikeCommon',
38168            type: 'get',
38169            data: {
38170                'mode': 'saveMyLikeCategory',
38171                'iCateNo': iCateNo,
38172                'sIconStatus': sIconStatus
38173            },
38174            dataType: 'json',
38175            success: function(oReturn) {
38176                if (oReturn.bResult === true) {
38177                    CAFE24.SHOP_FRONT_NEW_LIKE_COMMON.purgeMyLikeCategoryNoInList();
38178                }
38179            },
38180            complete: function() {
38181                CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.bIsReady = true;
38182            }
38183        });
38184    }
38185};
38186
38187var EC_SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY = CAFE24.getDeprecatedNamespace('EC_SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY');
38188
38189EC$(function() {
38190    CAFE24.SHOP_FRONT_NEW_LIKE_COMMON_CATEGORY.init(); // 분류 좋아요.
38191});
38192
38193var STOCKLAYER = (function() {
38194
38195    var sUrl = '/product/stocklayer.html';
38196
38197    //세트 상품 여부
38198    function isSetProdct()
38199    {
38200        if (typeof(set_option_data) === 'undefined') {
38201            return false;
38202        }
38203
38204        return true;
38205    }
38206
38207    //모든 재고 레이어 Element Get
38208    function getAllStockLayer()
38209    {
38210        return EC$('.ec-shop-detail-stock-layer');
38211    }
38212
38213    return {
38214        init: function() {
38215            try {
38216                EC$(document).on('click', 'a[name="EC-stockdesign"]', function(e) {
38217                    e.preventDefault();
38218                    var iProductNo = EC$(this).attr('product_no');
38219                    var sPageType = EC$(this).attr('page_type');
38220                    STOCKLAYER.closeStockLayer();
38221
38222                    if (EC$(this).parent().find('.ec-shop-detail-stock-layer').length == 0) {
38223                        var oParam = {};
38224
38225                        oParam['product_no'] = iProductNo;
38226                        oParam['page_type'] = sPageType;
38227
38228                        var oHtml = EC$('<div>');
38229                        oHtml.addClass('ec-shop-detail-stock-layer');
38230                        EC$(this).parent().append(oHtml);
38231                        EC$.ajax({
38232                            type: 'GET',
38233                            url: sUrl,
38234                            data: oParam,
38235                            success: function (sHtml) {
38236                                sHtml = sHtml.replace(/[<]script( [^ ]+)? src=\"[^>]*>([\s\S]*?)[<]\/script>/g, "");
38237                                oHtml.html(sHtml);
38238                            },
38239                            error: function (e) {
38240                                __('오류발생');
38241                            }
38242                        });
38243                    } else {
38244                        EC$(this).parent().find('.ec-shop-detail-stock-layer').show();
38245                    }
38246
38247                    e.preventDefault();
38248                });
38249            } catch (e) {}
38250        },
38251
38252        closeStockLayer: function() {
38253            var $oAllStockLayer = getAllStockLayer();
38254            $oAllStockLayer.hide();
38255        }
38256    };
38257})();
38258
38259EC$(function() {
38260    STOCKLAYER.init();
38261});
38262
38263//상품 옵션 id
38264var product_option_id = 'product_option_id';
38265EC$(function() {
38266    NEWPRD_ADD_OPTION.init();
38267    //ECHOSTING-77239 - 80113 : 배송준비중관리에서 특정된 두개의 기호가 포함된 옵션값만 깨져서 노출
38268
38269    //표시된 옵션 선택박스에 대해 이벤트바인드 정리
38270
38271    //추가입력 옵션 ; 제거 > ECHOSTING-77239건과 동일 이슈로 인해 역슬래시 기호 추가(ECHOSTING-182704)
38272    EC$(document).on('blur', '.input_addoption, .rel_input_addoption', function() {
38273        var regex = /[\;\\*\|]/g;
38274        if (regex.test(EC$(this).val()) === true) {
38275            alert(__('특수문자는 입력할 수 없습니다.'));
38276            EC$(this).val(EC$(this).val().replace(regex, ''));
38277        }
38278    });
38279
38280
38281    //추가옵션 글자수 체크
38282    try {
38283        EC$(document).on('keyup', '.rel_input_addoption', function() {
38284            NEWPRD_ADD_OPTION.checkProductAddOptionWord(this);
38285        });
38286    } catch (e) {}
38287});
38288
38289// 뉴상품에 뉴상품 스킨인지 확인하는 메소드 (뉴상품인데 구상품인 경우에는 false)
38290function isNewProductSkin()
38291{
38292    return EC$('#totalProducts').length > 0;
38293}
38294
38295// 구스킨을 사용할경우 총 금액 계산
38296function setOldTotalPrice()
38297{
38298
38299    if (product_price_content == true) {
38300        return;
38301    }
38302
38303    // 판매가 회원 공개인 경우 옵션 값 계산 필요없음!
38304    if (sIsDisplayNonmemberPrice === 'T') {
38305        EC$('#span_product_price_text').html(sNonmemberPrice);
38306        return;
38307    }
38308
38309    var iQuantity = 1;
38310    if (typeof(EC$(quantity_id).val()) !== 'undefined') {
38311        iQuantity = parseInt(EC$(quantity_id).val(),10);
38312    }
38313
38314    var iOptionPrice = 0;
38315    if (option_type === 'T') {
38316        iOptionPrice = CAFE24.SHOP_PRICE.toShopPrice(product_price);
38317    }
38318    var aStockData = new Array();
38319    if (typeof(option_stock_data) !== 'undefined') {
38320        aStockData = CAFE24.UTIL.parseJSON(option_stock_data);
38321    }
38322
38323    // 복합형
38324    if (option_type == 'T') {
38325        // 일체선택형
38326        if (item_listing_type == 'S') {
38327            sOptionId = ITEM.getOldProductItemCode();
38328            if (sOptionId !== false) {
38329                iOptionPrice += (aStockData[sOptionId].option_price - product_price);
38330            }
38331        } else {
38332            EC$('select[id^="product_option_id"] option:selected').filter('[value!="*"]').each(function() {
38333                var sOptionId = EC$(this).val();
38334                if (typeof(aStockData[sOptionId]) !== 'undefined' && aStockData[sOptionId].stock_price != 0) {
38335                    iOptionPrice += (aStockData[sOptionId].option_price - product_price);
38336                }
38337            });
38338        }
38339    } else if (Olnk.isLinkageType(option_type) === true) { // 저장형
38340        var iPrdPrice = CAFE24.SHOP_PRICE.toShopPrice(product_price);
38341        var iOptPrice = 0;
38342        var sPrice = '';
38343        EC$('select[id^="product_option_id"]').each(function() {
38344            var iValNo = parseInt(EC$(this).val());
38345            if (isNaN(iValNo) === true) {
38346                return;
38347            }
38348
38349            iOptPrice += CAFE24.SHOP_PRICE.toShopPrice(aStockData[iValNo].stock_price);
38350        });
38351
38352        iOptionPrice = iPrdPrice + iOptPrice;
38353    } else {
38354        // 단독형일때는 구상품과 다르게 품목단위로 계산이 필요함.
38355        EC$('select[id^="product_option_id"] option:selected').filter('[value!="*"]').each(function() {
38356            var sOptionId = EC$(this).val();
38357            if (typeof(aStockData[sOptionId]) !== 'undefined' && aStockData[sOptionId].stock_price != 0) {
38358                iOptionPrice += aStockData[sOptionId].option_price;
38359            } else {
38360                iOptionPrice += aStockData[sOptionId].option_price;
38361            }
38362        });
38363    }
38364    if (option_type === 'F' && iOptionPrice === 0) {
38365        iOptionPrice = product_price;
38366    }
38367
38368
38369    iPrice = getProductPrice(iQuantity, iOptionPrice, null, null, function(iPrice) {
38370        EC$('#span_product_price_text').html(CAFE24.SHOP_PRICE_FORMAT.toShopPrice(iPrice));
38371    });
38372
38373}
38374
38375/**
38376 * 뉴상품 프론트 옵션을 관리하는 객체
38377 * 앞으로 전역으로 함수를 선언하지 말고 여기에 선언
38378 */
38379var NEWPRD_OPTION = {
38380    DELIMITER_SEMICOLON: ';',
38381    DELIMITER_SLASH: '/',
38382    iOptionBoxSequence: 0,
38383    /**
38384     * 셀렉트 엘리먼트의 첫번째 옵션으로 변경
38385     * @param oSelect object 셀렉트 엘리먼트 객체
38386     */
38387    resetSelectElement: function(oSelect) {
38388        if (typeof(oSelect) !== 'object' || typeof(oSelect.is) !== 'function' || oSelect.is('select') !== true) {
38389            return false;
38390        }
38391
38392        if (this.setOlnkOptionReset(oSelect) !== false) {
38393            CAFE24.SHOP_FRONT_NEW_OPTION_COMMON.setValue(oSelect, '*');
38394        }
38395    },
38396
38397    /**
38398     * 옵션 셀렉트박스의 첫번째/두번째 값인지
38399     * @param  sOptionValue 선택값
38400     */
38401    isOptionSelectTitleOrDivider: function(sOptionValue) {
38402        return (EC$.inArray(sOptionValue, ['*', '**']) !== -1) ? true : false;
38403    },
38404
38405    setOlnkOptionReset: function(oSelect) {
38406        // option code가 있으면 연동형옵션
38407        // 만일을 대비해서 하단
38408        if (oSelect.attr('option_code') != undefined && oSelect.attr('option_code') !== '') {
38409
38410            var aOptionIdArray = oSelect.attr('id').split('_');
38411            var iOptionLength = aOptionIdArray.length;
38412            var sOptionIdTxt = 'product_option_id';
38413            var iOptionNum = 0;
38414            var sOptionButtonIdTxt = 'option_push_button';
38415
38416            if (iOptionLength === 3) { // product_option_idX
38417                iOptionNum = oSelect.attr('id').replace(sOptionIdTxt,'');
38418            } else if (iOptionLength === 5) { //addproduct_option_id_product_no_x
38419                sOptionIdTxt = 'addproduct_option_id_' + aOptionIdArray[3] + '_';
38420                iOptionNum = aOptionIdArray[4];
38421                sOptionButtonIdTxt = 'add_option_push_button_'+aOptionIdArray[3];
38422            }
38423
38424            // 연동형 옵션의 버튼형인 경우 리셑 처리 없이 그냥 리턴
38425            if (Olnk.getOptionPushbutton(EC$('#'+sOptionButtonIdTxt)) === true) {
38426                return false;
38427            }
38428        }
38429        return true;
38430    }
38431};
38432
38433/**
38434 * 뉴상품 프론트 추가옵션을 관리하는 객체
38435 * 앞으로 전역으로 함수를 선언하지 말고 여기에 선언
38436 */
38437var NEWPRD_ADD_OPTION = {
38438    aCustomData: [],
38439    init: function () {
38440        if (typeof add_option_input_setproduct === 'string') {
38441            window.add_option_input_setproduct = JSON.parse(add_option_input_setproduct);
38442        }
38443        if (typeof add_option_input_addproduct === 'string') {
38444            window.add_option_input_addproduct = JSON.parse(add_option_input_addproduct);
38445        }
38446    },
38447
38448    /**
38449     * 개별 입력 옵션 여부
38450     * @returns {boolean}
38451     */
38452    isUsePerAddOption: function () {
38453        if (typeof add_option_input !== 'undefined') { // 개별 입력 옵션
38454            return true;
38455        }
38456
38457        if (typeof add_option_file_input !== 'undefined') { // 개별 파일 첨부 옵션
38458            return true;
38459        }
38460
38461        if (typeof add_option_input_setproduct !== 'undefined') { // 세트 개별 입력 옵션
38462            return true;
38463        }
38464
38465        if (typeof add_option_input_addproduct !== 'undefined') { // 추가 구성 상품 개별 입력 옵션
38466            return true;
38467        }
38468
38469        return false;
38470    },
38471
38472    /**
38473     * 추가옵션 리스트 리턴 (필수, 선택모두)
38474     * @returns array 추가옵션 리스트
38475     */
38476    getCurrentAddOption: function() {
38477        var aAddOption = [];
38478
38479        EC$('.input_addoption').not('[name^=addproduct_add_option_name_]').each(function () {
38480            aAddOption.push(EC$(this).val());
38481        });
38482
38483        return aAddOption;
38484    },
38485
38486    getAddOptionValue: function(sDataAddOption) {
38487        return (oSingleSelection.isItemSelectionTypeS() === true) ? this.getCurrentAddOption().join(NEWPRD_OPTION.DELIMITER_SEMICOLON) : unescape(sDataAddOption);
38488    },
38489
38490    /**
38491     * 개별 입력 옵션 DOM 처리
38492     * @param sItemCode 품목코드
38493     * @returns {string}
38494     */
38495    getPerAddOptionTemplate: function (sItemCode) {
38496        var sHtml = '';
38497        // 개별 추가 입력 옵션
38498        sHtml += this.getAddOptionTemplate(sItemCode);
38499        // 개별  파일 첨부 옵션
38500        sHtml += this.getFileOptionTemplate(sItemCode);
38501
38502        if (sHtml !== '') {
38503            sHtml = '<tr class="option">' +
38504                '<td class="middle" colspan="3">' +
38505                '<table summary="" border="1">' +
38506                NEWPRD_ADD_OPTION.getPerAddOptionCaptionTemplate() +
38507                NEWPRD_ADD_OPTION.getPerAddOptionColgroupTemplate() +
38508                '<tbody>
38508' + sHtml + '</tbody>' +
38509                '</table>' +
38510                '</td>' +
38511                '</tr>' +
38512                '</tbody>' +
38513                '</table>';
38514        }
38515        return sHtml;
38516    },
38517    /**
38518     * 개별 입력 옵션 DOM 처리 by div
38519     * @param sItemCode 품목코드
38520     * @returns {string}
38521     */
38522    getPerAddOptionDivTemplate: function (sItemCode) {
38523        var sHtml = '';
38524
38525        // 개별 추가 입력 옵션
38526        sHtml += this.getAddOptionDivTemplate(sItemCode);
38527        // 개별  파일 첨부 옵션
38528        sHtml += this.getFileOptionDivTemplate(sItemCode);
38529
38530        return sHtml;
38531    },
38532    getPerAddOptionColgroupTemplate: function()
38533    {
38534        var aReturn = [
38535            '<colgroup>',
38536            '<col style="width:28%;">',
38537            '<col style="width:auto;">',
38538            '</colgroup>'
38539        ];
38540        return aReturn.join('');
38541    },
38542    getPerAddOptionCaptionTemplate: function()
38543    {
38544        var aReturn = [
38545            '<caption>',
38546            __('옵션 정보'), // 이 내용이 변경되어야하면 파라미터등을 추가하세요.
38547            '</caption>'
38548        ];
38549        return aReturn.join('');
38550    },
38551
38552    /**
38553     * 품목별 입력 옵션 템플릿 생성
38554     * @returns {string}
38555     */
38556    getAddOptionTemplate: function(sItemCode) {
38557        var sHtml = '';
38558        if (typeof add_option_input !== 'undefined') {
38559            EC$.each(add_option_input, function (iKey, oValue) {
38560                var sValue = '';
38561                // 부모창 입력값 레이어로 복사
38562                if (EC$('#product_detail_option_layer').is(':visible') === true && EC$(window.parent.document.body).find('#' + oValue.id + '[add_product_code="' + sItemCode + '"]').length > 0) {
38563                    sValue = EC$(window.parent.document.body).find('#' + oValue.id + '[add_product_code="' + sItemCode + '"]').val();
38564                }
38565                sHtml += '<tr class="xans-element- xans-product xans-product-addoption xans-record-"><th scope="row">' + oValue.title + '</th>' +
38566                    '<td colspan="2">' +
38567                    '<input name="' + oValue.id + '" value="' + oValue.info + '" type="hidden">' +
38568                    '<input id="' + oValue.id + '" name="' + oValue.name + '" require="' + oValue.require + '" maxlength="' + oValue.maxlength + '" class="' + oValue.class + '" value="' + sValue + '" type="text" add_product_code="' + sItemCode + '">' +
38569                    '<span class="txtByte" title="' + __("현재글자수/최대글자수") + '">(<strong class="length">0</strong>/' + oValue.maxlength + ')</span></td></tr>';
38570            });
38571        }
38572
38573        return sHtml;
38574    },
38575
38576    /**
38577     * 품목별 입력 옵션 템플릿 생성 by div
38578     * @param sItemCode item code
38579     * @returns string
38580     */
38581    getAddOptionDivTemplate: function(sItemCode) {
38582        var sHtml = '';
38583        if (typeof add_option_input !== 'undefined') {
38584            EC$.each(add_option_input, function (iKey, oValue) {
38585                var sValue = '';
38586
38587                _required_class = (oValue.require == 'T') ? 'required' : '';
38588                let _required_text = (oValue.require == 'T') ? __('필수') : __('OPTIONAL', 'SHOP.PRODUCT.OPTION');
38589
38590                sHtml += '' +
38591                    '<div class="xans-element- xans-product xans-product-addoption xans-record- row '+ _required_class+ '">' +
38592                        '<div class="th">' +
38593                            '<strong class="tit_option_name">' + oValue.info + '</strong>' +
38594                            '<span class="txt_value">(' +_required_text + ')</span>' +
38595                        '</div>' +
38596                        '<div class="td">' +
38597                            '<div class="ec-addoption-input option">' +
38598                                '<div class="ec-input-count">' +
38599                                    '<input name="' + oValue.id + '" value="' + oValue.info + '" type="hidden">' +
38600                                    '<input id="' + oValue.id + '" name="' + oValue.name + '" require="' + oValue.require + '" maxlength="' + oValue.maxlength + '" class="' + oValue.class + '" value="' + sValue + '" type="text" add_product_code="' + sItemCode + '" placeholder="' + __('내용을 입력하세요.') + '">' +
38601                                    '<div class="byte" title="' + __('현재글자수/최대글자수') + '">[ <strong class="length">0</strong> / <span class="maxCount">' + oValue.maxlength + '</span> ]</div>' +
38602                                '</div>' +
38603                            '</div>' +
38604                        '</div>' +
38605                    '</div>';
38606            });
38607        }
38608
38609        return sHtml;
38610    },
38611
38612    /**
38613     * 품목별 파일 첨부 옵션 템플릿 생성
38614     * @param sItemCode
38615     * @returns {string}
38616     */
38617    getFileOptionTemplate: function(sItemCode) {
38618        var sHtml = '';
38619        if (typeof add_option_file_input !== 'undefined') {
38620            var sFormTag = '';
38621            // 품목별 고유키 id를 가질 수 있도록 처리(id 기준으로 fileManager에 property 추가됨)
38622            EC$(add_option_file_input['form.file_option']).each(function () {
38623                var eSelf = EC$(this);
38624                eSelf.attr('id', eSelf.attr('id') + '_' + sItemCode);
38625                sFormTag += eSelf.prop('outerHTML');
38626            });
38627            sHtml += '<tr class="xans-element- xans-product xans-product-fileoption xans-record-"><th scope="row">' + add_option_file_input.file_option_name + '</th>' +
38628                '<td class="fileInfo" colspan="2">' +
38629                sFormTag +
38630                '<ul class="infoDesc">' +
38631                '<li>- ' + sprintf(__('파일은 최대 5개까지 %sM 이하로 개별업로드 가능합니다.'), add_option_file_input.file_option_limit) + '</li>' +
38632                '</ul>' +
38633                '<ul id="ul_file_option_' + sItemCode + '"></ul>' +
38634                '</td>' +
38635                '</tr>';
38636        }
38637        return sHtml;
38638    },
38639
38640    /**
38641     * 품목별 파일 첨부 옵션 템플릿 생성 by div
38642     * @param sItemCode
38643     * @returns string
38644     */
38645    getFileOptionDivTemplate: function(sItemCode) {
38646        var sHtml = '';
38647        if (typeof add_option_file_input !== 'undefined') {
38648            var sFormTag = '';
38649            // 품목별 고유키 id를 가질 수 있도록 처리(id 기준으로 fileManager에 property 추가됨)
38650            EC$(add_option_file_input['form.file_option']).each(function () {
38651                var eSelf = EC$(this);
38652                eSelf.attr('id', eSelf.attr('id') + '_' + sItemCode);
38653                sFormTag += eSelf.prop('outerHTML');
38654            });
38655
38656            _required_class = (add_option_file_input.necessary == 'T') ? 'required' : '';
38657            _required_text = (add_option_file_input.necessary == 'T') ? __('필수') : __('선택');
38658
38659            sHtml += '' +
38660                '<div class="xans-element- xans-product xans-product-fileoption xans-record- row ' + _required_class + '">' +
38661                    '<div class="th">' +
38662                        '<strong class="tit_option_name">' + add_option_file_input.option.name + '</strong>' +
38663                        '<span class="txt_value">(' +_required_text + ')</span>' +
38664                    '</div>' +
38665                    '<div class="td">' +
38666                        '<div class="fileInfo">' +
38667                            '<div class="ec-product-file">' +
38668                                sFormTag +
38669                                '<span class="btn_option_select">' + __('파일첨부') + '</span>' +
38670                                '<p class="txt_file_add">' + sprintf(__('최대 5개 파일, 각 %sMB까지 첨부'), add_option_file_input.file_option_limit) + '</p>' +
38671                            '</div>' +
38672                            '<ul id="ul_file_option_' + sItemCode + '" class="list_file_option"></ul>' +
38673                            '</ul>' +
38674                        '</div>' +
38675                    '</div>' +
38676                '</div>';
38677        }
38678        return sHtml;
38679    },
38680    /**
38681     * 현재 작성되어있는 추가옵션으로 품목에 표시할 타이틀 리턴
38682     * @param aAddOption array 추가옵션 리스트
38683     * @returns string 현재 작성된 추가옵션 타이틀
38684     */
38685    getCurrentAddOptionTitle: function(aAddOption) {
38686        var aAddOptionTitle = [];
38687
38688        EC$.each(aAddOption, function(iIdx, sValue) {
38689
38690            if (!sValue) {
38691                return true;
38692            }
38693
38694            var sOptionName = add_option_name[iIdx];
38695            if (sOptionName !== undefined) {
38696                var sAddOptionTitle = sOptionName+NEWPRD_OPTION.DELIMITER_SLASH+sValue;
38697                aAddOptionTitle.push(sAddOptionTitle);
38698            }
38699
38700        });
38701
38702        var delimeter = ', ';
38703        return (aAddOptionTitle.length > 0) ? aAddOptionTitle.join(delimeter)+delimeter : '';
38704    },
38705
38706    /**
38707     * 셀렉트 엘리먼트의 첫번째 옵션으로 변경
38708     * @param oSelect object 셀렉트 엘리먼트 객체
38709     */
38710    resetSelectElement: function(oSelect) {
38711        return NEWPRD_OPTION.resetSelectElement(oSelect);
38712    },
38713
38714    /**
38715     * 품목별 추가옵션 처리를위한 모든 추가옵션항목을 폼에 셋팅
38716     */
38717    setItemAddOptionName: function(frm) {
38718        if (!add_option_name) {
38719            return;
38720        }
38721
38722        frm.append(getInputHidden('item_add_option_name', add_option_name.join(NEWPRD_OPTION.DELIMITER_SEMICOLON)));
38723    },
38724
38725    /**
38726     * 개별 입력시 DOM을 기준으로 품주별 추가 입력옵션 데이터 생성
38727     * @param sItemCode
38728     * @param ePerAddOption
38729     * @param frm
38730     */
38731    setItemPerAddOptionData: function (sItemCode, ePerAddOption, frm) {
38732        var aAddOption = ePerAddOption.not('[name^=addproduct_add_option_name_]').map(function() {
38733            return this.value;
38734        }).get();
38735
38736        var iLength = aAddOption.length;
38737
38738        if (iLength < 1) {
38739            return;
38740        }
38741
38742        var iAddOptionIndex = this.addItem(sItemCode);
38743        for (var iIdx = 0; iIdx < iLength; iIdx++) {
38744            frm.prepend(getInputHidden('item_option_add[' + sItemCode + '][' + iIdx + ']', aAddOption[iIdx]));
38745            this.addCustomOption(iAddOptionIndex, {
38746                type: 'text',
38747                value: aAddOption[iIdx],
38748                info: add_option_name[iIdx]
38749            }, 'input');
38750        }
38751    },
38752
38753    /**
38754     * Form에 품주별 추가입력옵션 필드 추가
38755     * @param oForm
38756     */
38757    setItemPerAddOptionForm: function (oForm) {
38758        if (this.isUsePerAddOption() === true && this.aCustomData.length > 0) {
38759            oForm.prepend(getInputHidden('custom_data', JSON.stringify(this.aCustomData)));
38760        }
38761        // reset custom data
38762        this.aCustomData = [];
38763    },
38764
38765    /**
38766     * 품목별 추가옵션을 셋팅
38767     * @param sItemCode string 품목코드
38768     * @param sItemAddOption string 품목별 추가옵션 입력값
38769     */
38770    setItemAddOption: function(sItemCode, sItemAddOption, frm) {
38771
38772        if (!add_option_name || !sItemAddOption) {
38773            return;
38774        }
38775
38776        var aAddOption = sItemAddOption.split(NEWPRD_OPTION.DELIMITER_SEMICOLON);
38777        var iLength = aAddOption.length;
38778
38779        if (iLength < 1) {
38780            return;
38781        }
38782
38783        var iAddOptionIndex = this.addItem(sItemCode);
38784        for (var iIdx=0; iIdx<iLength; iIdx++) {
38785            frm.prepend(getInputHidden('item_option_add['+sItemCode+']['+iIdx+']', aAddOption[iIdx]));
38786            this.addCustomOption(iAddOptionIndex, {
38787                type: 'text',
38788                value: aAddOption[iIdx],
38789                info: add_option_name[iIdx]
38790            }, 'input');
38791        }
38792    },
38793
38794    /**
38795     * customData 데이터 초기화
38796     */
38797    initCustomData: function () {
38798        this.aCustomData = [];
38799    },
38800
38801    /**
38802     * 사용자추가옵션 상품이 포함되어있는지 확인
38803     * @param sItemCode
38804     * @returns {boolean}
38805     */
38806    getActiveCustomOption: function (sItemCode)
38807    {
38808        if (typeof add_option_data !== 'undefined') { // 추가구성상품
38809            var sProductCode = sItemCode.substr(0,8);
38810            var aAddOptData = CAFE24.UTIL.parseJSON(add_option_data);
38811            for (var iAddProductNo in aAddOptData) {
38812                if (aAddOptData[iAddProductNo].product_code === sProductCode) {
38813                    if (typeof add_option_input_addproduct === 'undefined') { // 개별입력 추가옵션 상품이 없을 경우
38814                        return false
38815                    } else if (typeof add_option_input_addproduct[iAddProductNo] === 'undefined') {
38816                        return false;
38817                    } else if (typeof add_option_input_addproduct[iAddProductNo] !== 'undefined') {
38818                        return true;
38819                    }
38820                }
38821            }
38822        }
38823
38824        if (typeof add_option_name !== 'undefined' && add_option_name.length > 0 ) { // 상품별 개별 입력 옵션
38825            return true;
38826        }
38827
38828        if (typeof add_option_input !== 'undefined') { // 품목 개별 입력 옵션
38829            return true;
38830        }
38831
38832        if (typeof add_option_file_input !== 'undefined') { // 품목 개별파일 첨부 옵션
38833            return true;
38834        }
38835        if (typeof add_option_input_setproduct !== 'undefined') { // 세트상품
38836            return true;
38837        }
38838
38839
38840        return false;
38841    },
38842    /**
38843     * customData에 품목 구분을 위한 품목 코드 추가 후, 인덱스 리턴
38844     * @param {string} sItemCode
38845     */
38846    addItem: function (sItemCode) {
38847        var bHasData = false;
38848        var iKey = 0;
38849        if (this.aCustomData.length > 0) {
38850            for (var x in this.aCustomData) {
38851                if (this.aCustomData.hasOwnProperty(x) === true && this.aCustomData[x].item_code === sItemCode) {
38852                    bHasData = true;
38853                    iKey = x;
38854                    break;
38855                }
38856            }
38857        }
38858        if (bHasData === false && this.getActiveCustomOption(sItemCode) === true) {
38859            this.aCustomData.push({
38860                item_code: sItemCode
38861            });
38862            // last index
38863            iKey = this.aCustomData.length - 1;
38864        }
38865
38866        return iKey;
38867    },
38868
38869    /**
38870     * aCustomData에 품목별 추가입력 / 파일 첨부 옵션 정보 추가 하는 영역
38871     * @param {number} iKey 배열 인덱스
38872     * @param {object} oParam 전송 데이터 정보
38873     * @param {string} sType 타입 구분(file/input)
38874     * @returns {boolean}
38875     */
38876    addCustomOption: function (iKey, oParam, sType) {
38877        if (oParam.value === null) {
38878            return true;
38879        }
38880        if (this.aCustomData.length < 1) {
38881            return true;
38882        }
38883
38884        // object 타입이 아니거나 custom_option 키가 없을때 custom option을 넣지 않도록 처리
38885        if (typeof this.aCustomData[iKey] !== 'object' && this.aCustomData[iKey].hasOwnProperty('custom_option') === false) {
38886            return true;
38887        }
38888
38889        // 타입 구분
38890        var sKey = sType === 'file' ? 'file_option' : 'item_option_add';
38891
38892        var oData = {
38893            key: sKey,
38894            type: oParam.type,
38895            value: oParam.value,
38896            info: oParam.info,
38897        };
38898
38899        if (oParam.item_code !== null && oParam.item_code !== '') {
38900            oData.item_code = oParam.item_code;
38901        }
38902
38903        if (this.aCustomData[iKey].hasOwnProperty('custom_option') === false) {
38904            this.aCustomData[iKey].custom_option = [];
38905        }
38906
38907        this.aCustomData[iKey].custom_option.push(oData);
38908    },
38909
38910    /**
38911     * 품목별 파일 첨부 옵션 정보 추가
38912     * @param aFileList
38913     * @param sTitle
38914     * @param sItemCode
38915     */
38916    addCustomFile: function (aFileList, sTitle, sItemCode) {
38917        if (aFileList.length === 0) return;
38918
38919        var aValue = [];
38920
38921        // 품목 추가
38922        var iAddOptionIndex = this.addItem(sItemCode);
38923        EC$.each(aFileList, function (iKey, oValue) {
38924            aValue.push({
38925                path: oValue.path,
38926                name: oValue.name,
38927            });
38928        });
38929
38930        // 해당 품목에 파일 첨부 옵션 항목 추가
38931        this.addCustomOption(iAddOptionIndex, {
38932            type: 'path',
38933            value: aValue,
38934            info: sTitle
38935        }, 'file');
38936    },
38937
38938    pushFileList: function (sId, oData) {
38939        // 상품별 파일첨부옵션 상품의 경우 기존로직으로 option_attached_file_info_json 사용하도록
38940        if (typeof add_option_file_input === 'undefined') {
38941            return true;
38942        }
38943        var eOptionBox = EC$('.option_box_id');
38944        var iOptionBoxLength = eOptionBox.length > 0 ? eOptionBox.length - 1 : 0;
38945        // 품목별 파일 업로드
38946        if (typeof add_option_file_input !== 'undefined' && has_option === 'T') {
38947            var sItemCode = sId.replace('file_option_', '');
38948            if (Olnk.isLinkageType(sOptionType) === true) {
38949                sItemCode = Olnk.getCustomOptionItemCode(sProductCode, iOptionBoxLength, sItemCode.split('_').pop());
38950            }
38951            NEWPRD_ADD_OPTION.addCustomFile(oData[sId].files, oData[sId].title, sItemCode);
38952            return true;
38953        }
38954
38955        // 연동형 옵션일때(품목수만큼 파일 복사 처리)
38956        if (Olnk.isLinkageType(sOptionType) === true) {
38957            eOptionBox.each(function (i) {
38958                var sItemCode = sProductCode + '000A_' + (i + 1);
38959                NEWPRD_ADD_OPTION.addCustomFile(oData[sId].files, oData[sId].title, sItemCode);
38960            });
38961            return true;
38962        }
38963        // 옵션이 없을때
38964        var aItemCode = ITEM.getItemCode();
38965        for (var iKey in aItemCode) {
38966            NEWPRD_ADD_OPTION.addCustomFile(oData[sId].files, oData[sId].title, aItemCode[iKey]);
38967        }
38968    },
38969
38970    /**
38971     * 품목별 추가입력옵션/파일첨부 옵션을 넣기 위해 최종 인덱스 조회
38972     * @returns {number}
38973     */
38974    getLastIndex: function () {
38975        return this.aCustomData.length > 0 ? this.aCustomData.length - 1 : 0;
38976    },
38977
38978    /**
38979     * 품목기반의 추가옵션타입을 사용해야하는지
38980     * @returns bool 품목기반의 추가옵션이면 true 아니면 false
38981     */
38982    isItemBasedAddOptionType: function() {
38983        // 옵션이 없을때
38984        if (has_option !== 'T') {
38985            return false;
38986        }
38987
38988        // 뉴스킨이 아닐때
38989        if (isNewProductSkin() !== true) {
38990            return false;
38991        }
38992
38993        // 연동형 옵션일때 (전역:sOptionType)
38994        if (Olnk.isLinkageType(sOptionType) === true) {
38995            return false;
38996        }
38997
38998        return true;
38999    },
39000
39001    isValidAddOptionSelect: function(frm, bIsSetProduct) {
39002        var bReturn = true;
39003        var iCount = 0;
39004        var sMsg = '';
39005        var oObject = null;
39006
39007        EC$('input[class^="option_add_box_"][name="basket_add_product[]"]').each(function() {
39008            var sAddOptionId = EC$(this).attr('id').replace('_id','');
39009            var iAddProductNo = parseInt(EC$(this).attr('class').substr(EC$(this).attr('class').lastIndexOf('_')+1));
39010            var iQuantity = EC$('#'+sAddOptionId+'_quantity').val();
39011            var sItemCode = EC$(this).val();
39012            EC$('select[name="addproduct_option_name_'+iAddProductNo+'"][required="true"]').filter(':visible').each(function() {
39013                if (EC$(this).val() === '*' || EC$(this).val() === '**') {
39014                    sMsg = __('필수 옵션을 선택해주세요.');
39015                    oObject = EC$(this);
39016                    bReturn = false;
39017                    return false;
39018                }
39019            });
39020            if (bReturn === false) {
39021                return false;
39022            }
39023
39024            if (bIsSetProduct === true) {
39025                bResult = ProductSetAction.checkAddProductAddOption('addproduct_add_option_id_'+iAddProductNo);
39026            } else {
39027                bResult = checkAddOption('addproduct_add_option_id_'+iAddProductNo);
39028            }
39029            if (bReturn === false) {
39030                return false;
39031            }
39032
39033            var addProductCode = sItemCode.split("||")[0].replace("#$%", "|");
39034            var iAddOptionIndex = NEWPRD_ADD_OPTION.addItem(addProductCode);
39035            var sSelectedAddItem = iQuantity+'||'+sItemCode;
39036            var oElement = EC$('input[name="addproduct_add_option_name_' + iAddProductNo + '"]').filter(':visible');
39037
39038            if (oElement.length > 0) {
39039                if (oSingleSelection.isItemSelectionTypeS() === false) {
39040                    oElement = oElement.filter('[add_product_code="' + addProductCode + '"]');
39041                }
39042
39043                oElement.each(function (key) {
39044                    var sTitle = EC$('input[name=addproduct_add_option_id_' + iAddProductNo + '_' + (key + 1) + ']').val();
39045                    var oSelf = EC$(this);
39046                    var sInputValue = oSelf.val();
39047                    var sAddProductCode = oSelf.attr('add_product_code');
39048                    NEWPRD_ADD_OPTION.addCustomOption(iAddOptionIndex, {
39049                        type: 'text',
39050                        value: sInputValue,
39051                        info: sTitle,
39052                        item_code: sAddProductCode
39053                    }, 'input');
39054                });
39055                sSelectedAddItem = iQuantity + '||' + sItemCode;
39056            }
39057            frm.append(getInputHidden('selected_add_item[]', sSelectedAddItem));
39058
39059            iCount++;
39060        });
39061
39062        return {'result': bReturn, 'count': iCount, 'message': sMsg, 'object': oObject};
39063    },
39064
39065    isValidRelationProductSelect: function(frm, oObj, bIsMainProductCheck) {
39066        var bReturn = true;
39067        var iCount = 0;
39068        var sMsg = '';
39069        var oObject = null;
39070        var sFailType = '';
39071
39072        EC$('input[name="basket_info[]"]:checked').each(function() {
39073            var iRelationProductNum = EC$(this).val().substr(0, EC$(this).val().indexOf('|'));
39074            var eQuantity = EC$('#quantity_' + iRelationProductNum);
39075            var eOption = EC$('select[name="option_' + iRelationProductNum + '[]"]');
39076
39077            var aValue = EC$(this).val().split('|');
39078            var sOptionType = aValue[6]; // appShopUtilNewProductFetchRelation::getCheckboxForm참조
39079            var sIsAddOptionName = aValue[8]; //관련상품 추가옵션 여부
39080            var sRelationProductName = decodeURIComponent(aValue[4]); //관련상품명
39081            var sIsProductPriceContent = aValue[9]; //관련상품 판매가 대체문구
39082            var user_option_id = 'user_option_'; //관련상품 추가옵션 id
39083
39084            if (sIsProductPriceContent === 'T') {
39085                sMsg = sprintf(__('%s 상품은 구매할 수 있는 상품이 아닙니다.'), sRelationProductName);
39086                NEWPRD_ADD_OPTION.checkVaildRelationProductObject(oObj, sMsg, bIsMainProductCheck, this);
39087                sFailType = 'bProductPriceContent';
39088                oObject = EC$(this);
39089                iCount++;
39090                bReturn = false;
39091                return false;
39092            }
39093
39094            if (NEWPRD_ADD_OPTION.checkVaildRelationProductQuantity(iRelationProductNum, this) === false) {
39095                sFailType = 'bRelationQuantity';
39096                oObject = EC$(this);
39097                iCount++;
39098                bReturn = false;
39099                return false;
39100            }
39101
39102            var addOptionItemCode = '';
39103            if (eQuantity.attr('item_code')) {
39104                // 단품인가
39105                frm.append(getInputHidden('relation_item[' + iCount + ']', eQuantity.val()+'||'+eQuantity.attr('item_code')));
39106                addOptionItemCode = eQuantity.attr('item_code');
39107                iCount++;
39108            } else {
39109                // 품목이 있는가
39110                bReturn = true;
39111                // 조합/분리 형의 경우 value_mapper가 있어야한다. 있으면 가서 쓰고 없어서 undefined가 뜨면 catch를 실행 - 억지코드임.
39112                try {
39113                    var aOptionMapper;
39114                    var rawData = window["sOptionValueMapper" + iRelationProductNum];
39115                    if (rawData !== undefined) {
39116                        aOptionMapper = CAFE24.UTIL.parseJSON(rawData);
39117                    }
39118
39119                    var aOptionValue = new Array();
39120                    eOption.each(function() {
39121                        if (EC$(this).is('[required="true"]') === true && (EC$(this).val() == '*' || EC$(this).val() == '**')) {
39122                            sMsg = __('필수 옵션을 선택해주세요.');
39123                            NEWPRD_ADD_OPTION.checkVaildRelationProductObject(oObj, sMsg, bIsMainProductCheck, this);
39124                            sFailType = 'sRequiredVaild';
39125                            oObject = EC$(this);
39126                            iCount++;
39127                            bReturn = false;
39128                            return false;
39129                        } else {
39130                            aOptionValue.push(EC$(this).val());
39131                        }
39132                    });
39133                    sOptionValue = aOptionValue.join('#$%');
39134                    var sItemCode = aOptionMapper[sOptionValue];
39135                } catch (e) {
39136                    eOption.each(function() {
39137                        if (EC$(this).is('[required="true"]') === true && (EC$(this).val() == '*' || EC$(this).val() == '**')) {
39138                            sMsg = __('필수 옵션을 선택해주세요.');
39139                            NEWPRD_ADD_OPTION.checkVaildRelationProductObject(oObj, sMsg, bIsMainProductCheck, this);
39140                            sFailType = 'sRequiredVaild';
39141                            oObject = EC$(this);
39142                            iCount++;
39143                            bReturn = false;
39144                            return false;
39145                        }
39146                    });
39147                    var sItemCode = eOption.val();
39148                }
39149                if (bReturn === true) {
39150
39151                    if (Olnk.isLinkageType(eQuantity.attr('option_type')) === false) {
39152                        if (sOptionType === 'F') {
39153                            // 독립형
39154                            var aIndividualItemCode = [];
39155                            eOption.each(function() {
39156                                var _sIndividualItemCode = EC$(this).val();
39157                                frm.append(getInputHidden('relation_item[' + iCount + ']', eQuantity.val() + '||' + _sIndividualItemCode));
39158                                aIndividualItemCode.push(_sIndividualItemCode);
39159                                iCount++;
39160                            });
39161                            addOptionItemCode = aIndividualItemCode.join('|');
39162                        } else {
39163                            // 조합형
39164                            frm.append(getInputHidden('relation_item[' + iCount + ']', eQuantity.val()+'||'+sItemCode));
39165                            addOptionItemCode = sItemCode;
39166                            iCount++;
39167                        }
39168                    } else {
39169                        // 연동형
39170                        var _sProductCode = eQuantity.attr('product_code');
39171                        var _iQuantity = eQuantity.val();
39172
39173                        var _sItemCode = _sProductCode + '000A';
39174                        var _aItemValueNo = Olnk.getSelectedItemForBasket(_sProductCode, eOption, _iQuantity);
39175
39176                        frm.append(getInputHidden('relation_item[' + iCount + ']', _iQuantity+'||'+_sItemCode));
39177                        frm.append(getInputHidden('relation_item_by_etype[' + iCount + ']', EC$.toJSON(_aItemValueNo)));
39178
39179                        addOptionItemCode = _sItemCode;
39180                        iCount++;
39181                    }
39182                } else {
39183                    return false;
39184                }
39185            }
39186
39187            if (typeof(rel_add_option_data) !== 'undefined' && CAFE24.UTIL.trim(rel_add_option_data) !== '') {
39188                var aRelAddOptData = CAFE24.UTIL.parseJSON(rel_add_option_data);
39189                var sRelAddOptName = '' + aRelAddOptData[iRelationProductNum] + '';
39190                var aRelAddOptNameData = sRelAddOptName.split('#$%');
39191            }
39192
39193            if (sIsAddOptionName === 'T' && EC$(aRelAddOptNameData).length > 0) {
39194                var iAddOptionIndex = NEWPRD_ADD_OPTION.addItem(addOptionItemCode);
39195                EC$(aRelAddOptNameData).each(function(iRelationIndex) {
39196                    var sAddOptionKey = iRelationProductNum + '_' + iRelationIndex;
39197                    var sRelAddOptionId = '#' + user_option_id + sAddOptionKey;
39198
39199                    var eRelAddOption = EC$(sRelAddOptionId);
39200                    if (CAFE24.UTIL.trim(eRelAddOption.val()) === '') {
39201                        if (eRelAddOption.attr('require') === 'T') {
39202                            sMsg = __('추가 옵션을 입력해주세요.');
39203                            NEWPRD_ADD_OPTION.checkVaildRelationProductObject(oObj, sMsg, bIsMainProductCheck, sRelAddOptionId);
39204                            oObject = eRelAddOption;
39205                            sFailType = 'sRelAddOptionValid';
39206                            bReturn = false;
39207                            return false;
39208                        }
39209                    }
39210
39211                    NEWPRD_ADD_OPTION.addCustomOption(iAddOptionIndex, {
39212                        type: 'text',
39213                        value: eRelAddOption.val(),
39214                        info: aRelAddOptNameData[iRelationIndex]
39215                    }, 'input');
39216                    frm.append(getInputHidden('rel_option_add[' + sAddOptionKey + ']', eRelAddOption.val()));
39217                    frm.append(getInputHidden('rel_add_option_name[' + sAddOptionKey + ']',aRelAddOptNameData[iRelationIndex]));
39218                });
39219                if (bReturn === false) {
39220                    return false;
39221                }
39222            }
39223        });
39224
39225        if (EC$('input[name="basket_info[]"]:checked').length >= 0) {
39226            frm.append(getInputHidden('relation_product', 'yes'));
39227        }
39228
39229        return {'result': bReturn, 'count': iCount, 'message': sMsg, 'object': oObject, 'sFailType': sFailType};
39230    },
39231
39232    /**
39233     * 단독 구매 관련 유효성 검증
39234     */
39235    checkVaildIndividualMsg: function(oValidResultData, sBuyType, oObject)
39236    {
39237        var bReturn = true;
39238        var sBuyValidMsg = '본상품의 옵션이 선택되지 않았습니다. \n 선택한 상품만 구매하시겠습니까?';
39239        var sCartValidMsg = '본상품의 옵션이 선택되지 않았습니다. \n 선택한 상품만 장바구니에 담으시겠습니까?';
39240        var sBuyTypeMessage = (sBuyType == true) ? sBuyValidMsg : sCartValidMsg;
39241
39242        if (this.checkRelationProduct(oObject) === false) {
39243            bReturn = false;
39244            return false;
39245        }
39246
39247        if (oValidResultData.sFailType !== '') {
39248            bReturn = false;
39249            return false;
39250        }
39251
39252        if (confirm(__('' + sBuyTypeMessage + '')) === false) {
39253            bReturn = false;
39254            return false;
39255        }
39256
39257        return bReturn;
39258    },
39259
39260    /**
39261     * 단독 구매 관련 데이터 검증
39262     */
39263    getIndividualValidCheckData: function(oValidRelationProduct, oValidAddProduct, bIsMainProductEmpty, frm)
39264    {
39265        var bIsCheckRelationProduct = (oValidRelationProduct.count > 0) ? true : false;
39266        var bIsCheckAddProduct = (oValidAddProduct.count > 0) ? true : false;
39267        var bIsIndividual = false;
39268        // 메인상품의 존재여부
39269        if (isNewProductSkin() === true && bIsMainProductEmpty === true) {
39270            if (is_individual_buy === 'T') {
39271                bIsIndividual = (bIsCheckAddProduct === true || bIsCheckRelationProduct === true) ? true : false;
39272            } else {
39273                if (bIsCheckAddProduct === false) {
39274                    bIsIndividual = bIsCheckRelationProduct;
39275                }
39276            }
39277        }
39278        var bIndividualBuyResult = (bIsIndividual === true) ? 'T' : 'F';
39279        frm.append(getInputHidden('is_individual', bIndividualBuyResult));
39280
39281        return {
39282            'isValidInidual': bIsIndividual,
39283            'isVaildRelationProduct': bIsCheckRelationProduct,
39284            'isVaildAddProduct': bIsCheckAddProduct,
39285            'sFailType': oValidRelationProduct.sFailType
39286        };
39287    },
39288
39289    /**
39290     * 관련상품 선택여부 확인
39291     */
39292    checkRelationProduct: function(oObj, sType)
39293    {
39294        var aActionType = [1, 2];
39295
39296        if (EC$.inArray(sType, aActionType) === -1) {
39297            return true;
39298        }
39299
39300        // @see ECHOSTING-358854
39301        // 관련상품 구매형 모듈에서 관련상품이 선택되지 않더라도 본상품이 단품이라면 구매(장바구니)가 가능해야 함
39302        if (typeof(oObj) === 'undefined' && EC$('input[name="basket_info[]"]:checkbox:checked').length <= 0 && has_option !== 'F') {
39303            alert(__('상품을 선택해주세요.'));
39304            return false;
39305        }
39306
39307        return true;
39308    },
39309
39310    /**
39311     * 관련상품 추가옵션 글자수 제한 체크
39312     */
39313    checkProductAddOptionWord: function (oObj)
39314    {
39315        var iLimit = EC$(oObj).attr('maxlength');
39316        var sId = EC$(oObj).attr('id');
39317        var sVal = EC$(oObj).val();
39318        var iStrLen = sVal.length;
39319
39320        if (iStrLen > iLimit) {
39321            alert(sprintf(__('메세지는 %s자 이하로 입력해주세요.'), iLimit));
39322            EC$('#'+sId).val(sVal.substr(0, sVal.length-1));
39323            return;
39324        }
39325
39326        EC$('#'+sId).parent().find('.txtLength').text(iStrLen);
39327    },
39328
39329    /**
39330     * 메인상품 여부확인에 따른 얼럿메시지 노출 처리
39331     */
39332    checkVaildRelationProductObject: function(oObj, sMessage, bIsMainProductCheck, oSelected)
39333    {
39334        if (isNewProductSkin() === true && this.checkRelationProduct(oObj) === true && (bIsMainProductCheck === true || this.isSoldOutMainProduct() === true)) {
39335            alert(sMessage);
39336            EC$(oSelected).focus();
39337        }
39338    },
39339
39340    /**
39341     * 본상품의 품절 아이콘이 존재하고 추가구성상품의 단독구매 여부 및 관련상품
39342     */
39343    checkSoldOutProductValid: function(oObj)
39344    {
39345        if (NEWPRD_ADD_OPTION.isSoldOutMainProduct() === true) {
39346            if (EC$('input[class^="option_add_box_"][name="basket_add_product[]"]').length > 0 || EC$('input[name="basket_info[]"]:checkbox:checked').length > 0) {
39347                return true;
39348            } else {
39349                return false;
39350            }
39351        } else if (isNewProductSkin() === true && is_soldout_icon === 'T' && this.checkRelationProduct(oObj) === true) {
39352            return true;
39353        }
39354
39355        return false;
39356    },
39357
39358    /**
39359     * 본상품의 품절여부 (판매가 대체문구 및 판매안함 상품)
39360     */
39361    isSoldOutMainProduct: function()
39362    {
39363        if (isNewProductSkin() === true && (is_soldout_icon === 'T' || product_price_content == true)) {
39364            return true;
39365        }
39366
39367        return false;
39368    },
39369
39370    /**
39371     * 관련상품 수량 체크 유효성 검증
39372     */
39373    checkVaildRelationProductQuantity: function(iRelationProductNum)
39374    {
39375        var bReturn = true;
39376        var aQuantityInfo = CAFE24.UTIL.parseJSON(relation_product);
39377        var sRelationQuantityId = 'quantity_' + iRelationProductNum;
39378        var oProductQuantity = EC$('input[id^= "'+ sRelationQuantityId +'"]');
39379        var iRelationQuantity = oProductQuantity.val();
39380
39381        var iProductMinimum = parseInt(aQuantityInfo[iRelationProductNum].product_min, 10);
39382        var iProductMaximum = parseInt(aQuantityInfo[iRelationProductNum].product_max, 10);
39383
39384        if (iRelationQuantity > iProductMaximum && iProductMaximum > 0) {
39385            alert(sprintf(__('최대 주문수량은 %s개 입니다.'), iProductMaximum));
39386            oProductQuantity.val(iProductMaximum);
39387            EC$(oProductQuantity).focus();
39388            return false;
39389        }
39390
39391        if (iRelationQuantity < iProductMinimum) {
39392            alert(sprintf(__('최소 주문수량은 %s개 입니다.'), iProductMinimum));
39393            oProductQuantity.val(iProductMinimum);
39394            EC$(oProductQuantity).focus();
39395            return false;
39396        }
39397
39398        if (bReturn === false) {
39399            return false;
39400        }
39401
39402        return bReturn;
39403    },
39404
39405    /**
39406     * 구스킨 > 관련상품 및 추가 구성상품용 유효성 검증 메시지
39407     */
39408    checkExistingValidMessage: function(oObj, oAddProductCount)
39409    {
39410        var sValidMsg = false;
39411
39412        // 뉴스킨은 관계 없음
39413        if (isNewProductSkin() === true) {
39414            return sValidMsg;
39415        }
39416
39417        if (typeof(oObj) === 'undefined') {
39418            sValidMsg = __('본상품과 함께 구매가 가능합니다. \n 본상품의 필수 옵션을 선택해 주세요.');
39419        } else if (oAddProductCount.count > 0) {
39420            //추가구성상품의 선택되어있으면서 본상품의 옵션이 선택 안되었을때
39421            sValidMsg = __('본상품의 필수 옵션을 선택해 주세요');
39422        }
39423
39424        return sValidMsg;
39425    },
39426
39427    /**
39428     * 관련상품 및 단독기능 사용 추가구성 상품시 유효성 검증에 해당하는 메시지의 노출여부 결정
39429     */
39430    checkIndividualValidAction: function(oRelationProductCount, oAddProductCount)
39431    {
39432        var bIsCheckValid = true;
39433        // 구스킨은 관계 없음
39434        if (isNewProductSkin() === false) {
39435            return bIsCheckValid;
39436        }
39437
39438        if (is_individual_buy === 'T') {
39439            bIsCheckValid = (oAddProductCount.result === false || oRelationProductCount.result === false) ? false : true;
39440            if (bIsCheckValid === false && oAddProductCount.message !== '') {
39441                alert(oAddProductCount.message);
39442                return false;
39443            }
39444        } else {
39445            bIsCheckValid = (oRelationProductCount.result === false) ? false : true;
39446        }
39447
39448        return bIsCheckValid;
39449    },
39450
39451    checkPerAddInputOption: function () {
39452        if (EC$('.input_peraddoption').filter(':visible').length === 0) {
39453            return true;
39454        }
39455
39456        return this.validateAddOptionForm(EC$('.input_peraddoption'));
39457    },
39458
39459    validateAddOptionForm: function(oTargetElement) {
39460        var bResult = true;
39461        oTargetElement.filter(':visible').each(function()
39462        {
39463            var eSelf = EC$(this);
39464            if (eSelf.attr('require') !== false && eSelf.attr('require') === 'T') {
39465                if (eSelf.val().replace(/^[\s]+|[\s]+$/g, '').length === 0) {
39466                    alert(__('추가 옵션을 입력해주세요.'));
39467                    eSelf.focus();
39468                    bResult = false;
39469                    return false;
39470                }
39471            }
39472        });
39473
39474        return bResult;
39475    },
39476
39477    getPerItemCode: function(iIndex, sItemCode)
39478    {
39479        return Olnk.isLinkageType(sOptionType) === true ? sProductCode + '000A_' + (iIndex - 1) : sItemCode;
39480    },
39481};
39482EC$(function() {
39483    // 파일첨부옵션 초기화
39484    try {
39485        FileOptionManager.init();
39486    } catch (e) {}
39487});
39488
39489
39490/**
39491 * JSON.stringify
39492 * @param object aData JSON.stringify 할 데이터
39493 * @return string JSON.stringify 된 데이터 반환
39494 */
39495function JSON_stringify(aData)
39496{
39497    if (!EC$.stringify) {
39498        // https://gist.github.com/chicagoworks/754454
39499        EC$.extend({
39500            stringify: function stringify(obj) {
39501                if ("JSON" in window) {
39502                    return JSON.stringify(obj);
39503                }
39504
39505                var t = typeof (obj);
39506                if (t != "object" || obj === null) {
39507                    // simple data type
39508                    if (t == "string") obj = '"' + obj + '"';
39509
39510                    return String(obj);
39511                } else {
39512                    // recurse array or object
39513                    var n, v, json = [], arr = (obj && obj.constructor == Array);
39514
39515                    for (n in obj) {
39516                        v = obj[n];
39517                        t = typeof(v);
39518                        if (obj.hasOwnProperty(n)) {
39519                            if (t == "string") {
39520                                v = '"' + v + '"';
39521                            } else if (t == "object" && v !== null) {
39522                                v = EC$.stringify(v);
39523                            }
39524
39525                            json.push((arr ? "" : '"' + n + '":') + String(v));
39526                        }
39527                    }
39528
39529                    return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
39530                }
39531            }
39532        });
39533    }
39534
39535    return EC$.stringify(aData);
39536}
39537
39538/**
39539 * FileOptionManager
39540 * 파일옵션 객체를 관리하는 class - 페이지 내의 파일첨부 옵션 전체를 관장
39541 * @author 백충덕 <[email protected]>
39542 */
39543var FileOptionManager = {
39544    bIsInputFileSupport: null,
39545    /**
39546     * FileOption 객체 리스트
39547     * @var object
39548     */
39549    aList: {},
39550
39551    /**
39552     * 초기화
39553     *   - FileOptionManager.add()를 통해 추가된 FileOption 객체 초기화 처리
39554     */
39555    init: function()
39556    {
39557        // 품목별 파일 첨부시 기본 파일첨부 옵션 제거
39558        if (typeof add_option_file_input !== 'undefined' && has_option === 'T') {
39559            if (FileOptionManager.aList.hasOwnProperty('file_option') === true) {
39560                delete FileOptionManager.aList['file_option'];
39561            }
39562        }
39563
39564        // 모바일 옵션 없는 상품에서 디자인에 파일첨부 HTML이 없을 때 동적 생성
39565        if (typeof EC_MOBILE !== 'undefined' && EC_MOBILE === true && typeof add_option_file_input !== 'undefined' && has_option === 'F') {
39566            if (EC$('#file_option').length === 0) {
39567                var sHtml = '<tr class="xans-element- xans-product xans-product-fileoption xans-record-">' +
39568                    '<th scope="row">' + add_option_file_input.file_option_name + '</th>' +
39569                    '<td class="fileInfo">' +
39570                        add_option_file_input['form.file_option'] +
39571                        '<ul class="ec-base-help typeDash">' +
39572                            '<li>' + sprintf(__('파일은 최대 5개까지 %sM 이하로 개별업로드 가능합니다.'), add_option_file_input.file_option_limit) + '</li>' +
39573                        '</ul>' +
39574                        '<ul id="ul_file_option"></ul>' +
39575                    '</td>' +
39576                '</tr>';
39577
39578                var eQuantityTr = EC$('tr').has('[name="quantity_opt[]"]').first();
39579                if (eQuantityTr.length > 0) {
39580                    eQuantityTr.before(sHtml);
39581                } else {
39582                    EC$('#totalProducts table tbody').append(sHtml);
39583                }
39584            }
39585        }
39586
39587        for (var sId in this.aList) {
39588            if (this.aList.hasOwnProperty(sId)===false) continue;
39589
39590            // 초기화 과정에 문제가 생긴 객체는 리스트에서 제거
39591            if (this.aList[sId].init() === false) delete this.aList[sId];
39592        }
39593    },
39594
39595    /**
39596     * 파일업로드용 input:file의 change 이벤트 핸들러
39597     * @param object eFileInput change 이벤트가 발생한 input:file
39598     */
39599    onChange: function(eFileInput)
39600    {
39601        var sId = eFileInput.id;
39602        this.aList[sId].onChange(eFileInput);
39603    },
39604
39605    /**
39606     * 리스트에 sInputId, aOpt 파라메터로 생성한 FileOption 객체 추가
39607     * @param string sId 고유 ID (input:file의 id로도 쓰임)
39608     * @param object aOpt 생성 파라메터
39609     */
39610    add: function(sId, aOpt)
39611    {
39612        this.aList[sId] = new FileOption(sId, aOpt);
39613    },
39614
39615    /**
39616     * 리스트에 sInputId, aOpt 로 FileOption 객체 생성 및 초기화
39617     * @param {string} sId 고유 ID (input:file의 id로도 쓰임)
39618     * @param {object} aOpt 생성 파라미터
39619     */
39620    put: function(sId, aOpt)
39621    {
39622        // 동일한 객체가 있을 경우 삭제
39623        this.remove(sId);
39624        this.add(sId, aOpt);
39625        if (this.aList[sId].init() === false) delete this.aList[sId];
39626    },
39627
39628    /**
39629     * 업로드해야 할 input:file이 있는지 체크
39630     * @param mixed mId 업로드 해야할 파일이 있는지 체크할 FileOption id. 없거나 하나 혹은 여러개.
39631     * @return bool 파일업로드가 있으면 true, 아니면 false
39632     */
39633    existsFileUpload: function(mId)
39634    {
39635        var aId = this._getList(mId);
39636
39637        for (var i=0; i<aId.length; i++) {
39638            var sId = aId[i];
39639
39640            // 업로드해야 할 파일 있음
39641            if (this.aList[sId].existsFileUpload() === true) return true;
39642        }
39643
39644        return false;
39645    },
39646
39647    /**
39648     * 유효성 체크
39649     * @param mixed mId 유효성 체크할 FileOption id. 없거나 하나 혹은 여러개.
39650     * @return bool 유효하면 true, 아니면 false
39651     */
39652    checkValidation: function(mId)
39653    {
39654        var aId = this._getList(mId);
39655
39656        // 유효성 체크
39657        for (var i=0; i<aId.length; i++) {
39658            var sId = aId[i];
39659
39660            if (this.aList[sId].checkValidation() === false) return false;
39661        }
39662
39663        return true;
39664    },
39665
39666    /**
39667     * 파일첨부 옵션 업로드 실행
39668     * @param mixed mId 파일업로드를 실행할 FileOption id. 없거나 하나 혹은 여러개.
39669     * @param function callback 파일업로드 완료 후 실행할 callback
39670     */
39671    upload: function(mId, callback)
39672    {
39673        var self = this;
39674
39675        // mId 지정하지 않음
39676        if (typeof mId === 'function') {
39677            callback = mId;
39678            mId = null;
39679        }
39680        var aId = this._getList(mId);
39681
39682        // 업로드 해야할 input:file 추출
39683        var aFile = [];
39684        var aMaxSize = {};
39685        for (var i=0; i<aId.length; i++) {
39686            var sId = aId[i];
39687            aMaxSize[sId] = this.aList[sId].aOpt.maxSize;
39688
39689            this.aList[sId].getInputFileUpload().each(function(idx) {
39690                var sVal = CAFE24.UTIL.trim(EC$(this).val());
39691                if (sVal.length < 1) return;
39692
39693                aFile.push({
39694                    eFile: EC$(this),
39695                    eParent: EC$(this).parent()
39696                });
39697            });
39698        }
39699
39700        // 업로드 할 파일이 없을 경우 중지 (업로드는 성공했다고 반환)
39701        if (aFile.length < 1) {
39702            callback(true);
39703            return true;
39704        }
39705
39706        var sTargetName = 'iframe_add_option_file_upload';
39707        var sAction = '/api/product/fileupload/';
39708
39709        // form
39710        var form = EC$('<form action="'+sAction+'" method="post" enctype="multipart/form-data" style="display:none;" target="'+sTargetName+'"></form>');
39711        EC$('body').append(form);
39712        // 업로드할 input:file append
39713        for (var i=0; i<aFile.length; i++) {
39714            aFile[i].eFile.appendTo(form);
39715        }
39716
39717        // 커맨드 지정
39718        EC$('<input type="hidden" name="cmd" value="upload" />').prependTo(form);
39719        // 파일 업로드 사이즈 한계
39720        EC$('<input type="hidden" name="max_size" value="'+encodeURIComponent(JSON_stringify(aMaxSize))+'" />').prependTo(form);
39721
39722        // iframe
39723        var iframe = EC$('<iframe src="javascript:false;" name="'+sTargetName+'" style="display:none;"></iframe>');
39724        EC$('body').append(iframe);
39725
39726        // iframe onload(form.submit response) 이벤트 핸들러
39727        iframe.on('load', function() {
39728            var doc = this.contentWindow ? this.contentWindow.document : (this.contentDocument ? this.contentDocument : this.document);
39729            var root = doc.documentElement ? doc.documentElement : doc.body;
39730            var sResult = root.textContent ? root.textContent : root.innerText;
39731            var aResult = CAFE24.UTIL.parseJSON(sResult);
39732            var mReturn = false;
39733
39734            if (typeof aResult==='object') {
39735                // 업로드 성공
39736                if (aResult.err=='') {
39737                    // 업로드 성공한 파일정보를 가져와 input:hidden의 value로 저장
39738                    for (var sId in aResult.files) {
39739                        var eInputHidden = EC$('#'+sId+'_hidden');
39740                        var aVal = {
39741                            title: self.aList[sId].aOpt.name,
39742                            files: []
39743                        };
39744                        for (var i=0; i<aResult.files[sId].length; i++) {
39745                            aVal.files.push({
39746                                path: aResult.files[sId][i].path,
39747                                name: aResult.files[sId][i].name
39748                            });
39749                        }
39750
39751                        eInputHidden.val(encodeURIComponent(JSON_stringify(aVal)));
39752
39753                        // 반환값 세팅
39754                        if (mReturn===false) mReturn = {};
39755                        mReturn[sId] = aVal;
39756                    }
39757                // 업로드 실패
39758                } else {
39759                    alert(aResult.err);
39760                }
39761            }
39762
39763            // file element 원래 위치로 이동
39764            for (var i=0; i<aFile.length; i++) {
39765                aFile[i].eFile.appendTo(aFile[i].eParent);
39766            }
39767
39768            // 임시 element 삭제
39769            form.remove();
39770            iframe.remove();
39771
39772            callback(mReturn);
39773        });
39774
39775        // 파일전송
39776        form.submit();
39777    },
39778
39779    /**
39780     * 브라우저가 input file 지원여부 반환
39781     * @return bool input file 지원시 true, 아니면 false
39782     */
39783    isInputFileSupport: function()
39784    {
39785        if (this.bIsInputFileSupport===null) {
39786            this.bIsInputFileSupport = true;
39787
39788            try {
39789                var eInputFile = document.createElement('input');
39790                eInputFile.type = 'file';
39791                eInputFile.style.display = 'none';
39792                document.getElementsByTagName('body')[0].appendChild(eInputFile);
39793
39794                if (eInputFile.disabled) this.bIsInputFileSupport = false;
39795            } catch (e) {
39796                this.bIsInputFileSupport = false;
39797            } finally {
39798                if (eInputFile) eInputFile.parentNode.removeChild(eInputFile);
39799            }
39800        }
39801
39802        return this.bIsInputFileSupport;
39803    },
39804
39805    // 파라메터로 넘기기 위해 인코딩
39806    encode: function(sVal)
39807    {
39808        return encodeURIComponent(JSON_stringify(sVal)).replace(/'/g, "%27");
39809    },
39810
39811    /**
39812     * 넘겨받은 id에 해당하는 유효한 FileOption id 리스트 반환
39813     * @param mixed mId 리스트로 추출할 FileOption id. 없거나 하나 혹은 여러개.
39814     * @return array 유효한 FileOption id 리스트
39815     */
39816    _getList: function(mId)
39817    {
39818        var aId = [];
39819
39820        // 지정한 id가 없다면 전체대상
39821        if (!mId) {
39822            for (var sId in this.aList) {
39823                if (this.aList.hasOwnProperty(sId)===false) continue;
39824
39825                aId.push(sId);
39826            }
39827        // 지정한 id가 문자열 하나
39828        } else if (typeof mId === 'string') {
39829            aId.push(mId);
39830        // 지정한 id가 Array(object)
39831        } else {
39832            aId = mId;
39833        }
39834
39835        // 뭔가 문제가 있을 경우 빈 배열 반환
39836        if (Array.isArray(aId)===false || aId.length<1) return [];
39837
39838        // 유효한 id만 추출
39839        var sId = '';
39840        var aResult = [];
39841        for (var i=0; i<aId.length; i++) {
39842            sId = aId[i];
39843            if (!(sId in this.aList)) continue;
39844
39845            aResult.push(sId);
39846        }
39847
39848        return aResult;
39849    },
39850
39851    /**
39852     * 동일한 객체가 있을 경우 FileOptionManager.aList에서 객체 삭제
39853     * @param sId
39854     */
39855    remove: function(sId)
39856    {
39857        // 동일한 객체가 있을 경우 삭제
39858        if (this.aList.hasOwnProperty(sId) === true) {
39859            delete this.aList[sId];
39860        }
39861    },
39862
39863    /**
39864     * 부모창 - 자식창 파일 리스트 복사
39865     */
39866    sync: function(sId, target)
39867    {
39868        this.aList[sId].sync(sId, target);
39869    }
39870};
39871
39872/**
39873 * FileOption
39874 * 파일옵션 class - 파일첨부 옵션 하나당 하나씩
39875 * @author 백충덕 <[email protected]>
39876 */
39877var FileOption = function(sInputId, aParam)
39878{
39879    this.aOpt = {
39880        inputId: sInputId,
39881        name: null,
39882        maxLen: null,
39883        maxSize: null,
39884        btnDel: '<a href="#none"><img src="//img.echosting.cafe24.com/skin/base_ko_KR/common/btn_attach_close.gif" /></a>',
39885        btnDelSelector: 'a',
39886        eInputFile: null
39887    };
39888
39889    EC$.extend(this.aOpt, aParam);
39890
39891    var self = this;
39892
39893    /**
39894     * 초기화
39895     */
39896    this.init = function()
39897    {
39898        self.aOpt.eInputFile = EC$('#'+self.aOpt.inputId);
39899
39900        // 지정된 id를 가진 input file이 없을 경우
39901        if (!self.aOpt.eInputFile) return false;
39902
39903        // 파일리스트 목록 초기화
39904        var aFileListContainer = self._getFileListContainer(self.aOpt.inputId);
39905        if (aFileListContainer.length < 1) {
39906            self.aOpt.eInputFile.parent().append('<ul id="'+self._getFileListContainerId(self.aOpt.inputId)+'"></ul>');
39907            aFileListContainer = self._getFileListContainer(self.aOpt.inputId);
39908        }
39909
39910        // 모바일의 경우 삭제버튼 변경
39911        if (self._isMobileBrowser()===true) {
39912            self.aOpt.btnDel = '<button type="button" class="btnDelete">' + __('삭제') + '</button></li>';
39913            self.aOpt.btnDelSelector = 'button.btnDelete';
39914        }
39915
39916        // 삭제버튼 이벤트 핸들러 세팅
39917        aFileListContainer.on('click', this.aOpt.btnDelSelector, function() {
39918            EC$(this).parent().remove();
39919            return false;
39920        });
39921    };
39922
39923    /**
39924     * 파일 입력폼을 초기화
39925     * @param jQuery eFile 파일 입력폼
39926     */
39927    this.resetFileInput = function(eFile)
39928    {
39929        // MSIE
39930        if (navigator.appVersion.indexOf('MSIE') > -1) {
39931            eFile.replaceWith(eFile = eFile.clone(true));
39932        } else {
39933            eFile.val('');
39934        }
39935    };
39936
39937    /**
39938     * input:file change 이벤트 핸들러
39939     * @param object eFileInput change이벤트가 발생한 input:file
39940     */
39941    this.onChange = function(eFileInput)
39942    {
39943        var eFile = EC$(eFileInput);
39944
39945        // 업로드 파일명
39946        var sFileName = this._getFileName(eFile.val());
39947        if (sFileName.length<1) return false;
39948
39949        var eFileList = this._getFileListContainer(eFile.attr('id'));
39950
39951        // 첨부파일 최대 갯수 제한
39952        var iCntFile = eFileList.find('li').length;
39953        if (iCntFile >= this.aOpt.maxLen) {
39954            if (eFile.val().length>0) alert(sprintf(__('첨부파일은 최대 %s개까지만 업로드 가능합니다.'), self.aOpt.maxLen));
39955            this.resetFileInput(eFile);
39956            return false;
39957        }
39958
39959        // 업로드 파일리스트 추가
39960        var eFileItem = EC$('<li>'+sFileName+' '+this.aOpt.btnDel+'</li>');
39961        var sId = eFile.attr('id');
39962        var sRequire = eFile.attr('require');
39963        var sAccept = eFile.attr('accept');
39964
39965        // IE8 이하에서는 display가 바뀌어도 onChange가 trigger되므로 onChange 제거
39966        eFile.get(0).onchange = null;
39967
39968        eFile.css('display', 'none');
39969        eFile.attr({
39970            id: '',
39971            name: this.aOpt.inputId+'[]'
39972        });
39973        eFileItem.append(eFile);
39974        eFileList.append(eFileItem);
39975
39976        // 새 파일업로드 input 배치
39977        var eFileNew = EC$('<input type="file" onchange="FileOptionManager.onChange(this)"/>');
39978        eFileNew.attr({
39979            id: sId,
39980            name: sId,
39981            require: sRequire,
39982            accept: sAccept
39983        });
39984        eFileList.parent().prepend(eFileNew);
39985
39986        // 업로드 가능한 파일인지를 비동기로 확인
39987        this.checkUpload(sFileName, eFileItem, String(sAccept));
39988    };
39989
39990    /**
39991     * 파일업로드 전 체크
39992     * @param string sFileName 파일명
39993     * @param jQuery eFileItem 파일 첨부
39994     * @param string sAccept accept 속성값 (.jpg,.jpeg,.gif)
39995     */
39996    this.checkUpload = function(sFileName, eFileItem, sAccept)
39997    {
39998        var self = this;
39999        var sFileExtension = sFileName.replace(/^.+\.([^.]+)$/, '$1');
40000        if (EC$.inArray('.' + sFileExtension, sAccept.split(',')) > -1) {
40001            // accept 속성에 포함된 확장자인 경우 확인 안함
40002            return;
40003        }
40004
40005        EC$.ajax({
40006            url: "/api/product/fileupload/",
40007            method: "GET",
40008            data: {
40009                cmd: "check_upload",
40010                file_extension: sFileExtension
40011            },
40012            dataType: "json",
40013            success: function(result) {
40014                if (result && result.err) {
40015                    eFileItem.find(self.aOpt.btnDelSelector).click();
40016                    alert(result.err);
40017                }
40018            }
40019        });
40020    };
40021
40022    /**
40023     * 유효성 체크
40024     * @return bool 유효하면 true, 아니면 false
40025     */
40026    this.checkValidation = function()
40027    {
40028        // 파일첨부 옵션이 '필수'가 아닐 경우 OK
40029        if (self.aOpt.eInputFile.attr('require') !== 'T') return true;
40030
40031        // 파일첨부 옵션이 '필수'인데 업로드 선택 파일이 없을 경우
40032        if (self.existsFileUpload()===false) {
40033            alert(self.aOpt.name+' '+__('파일을 업로드 해주세요.'));
40034            self.aOpt.eInputFile.focus();
40035            return false;
40036        }
40037
40038        return true;
40039    };
40040
40041    /**
40042     * 업로드 해야할 input:file 리스트 반환
40043     * @return array 업로드 해야할 input:file 리스트
40044     */
40045    this.getInputFileUpload = function()
40046    {
40047        return self._getFileListContainer(self.aOpt.inputId).find('input:file:hidden');
40048    };
40049
40050    /**
40051     * 업로드 해야할 input:file이 있는지 여부 체크
40052     * @return bool 업로드 해야할 input:file이 있으면 true, 없으면 false
40053     */
40054    this.existsFileUpload = function()
40055    {
40056        return self.getInputFileUpload().length > 0;
40057    };
40058
40059    /*
40060     * 파일업로드 리스트를 담을 노드 반환
40061     * @param string sSuffix
40062     * @return element
40063     */
40064    this._getFileListContainer = function(sSuffix)
40065    {
40066        var sFileListId = self._getFileListContainerId(sSuffix);
40067
40068        return EC$('ul[id="'+sFileListId+'"]');
40069    };
40070
40071    /**
40072     * 파일업로드 리스트를 담을 노드의 ID 반환
40073     * @param string sSuffix id로 사용할 suffix
40074     * @return string 노드의 ID
40075     */
40076    this._getFileListContainerId = function(sSuffix)
40077    {
40078        return 'ul_'+sSuffix;
40079    };
40080
40081    /**
40082     * 파일 경로에서 파일명만 추출
40083     * @param string sFilePath 파일 경로
40084     * @return mixed 추출된 파일명 반환, 실패시 false 반환
40085     */
40086    this._getFileName = function(sFilePath)
40087    {
40088        sFilePath = CAFE24.UTIL.trim(sFilePath);
40089        if (sFilePath.length<1) return false;
40090
40091        return CAFE24.UTIL.trim(sFilePath.split('/').pop().split('\\').pop());
40092    };
40093
40094    /**
40095     * 모바일 브라우저인지 체크
40096     * @return bool 모바일 브라우저이면 true, 아니면 false 반환
40097     */
40098    this._isMobileBrowser = function()
40099    {
40100        // 전역 isMobile 변수가 세팅되어있을 경우 isMobile 변수값 반환
40101        if (typeof isMobile !== 'undefined') {
40102            return isMobile;
40103        // 전역 isMobile 변수가 없을 경우 location.hostname으로 판별
40104        } else {
40105            return location.hostname.indexOf('m.')===0;
40106        }
40107    };
40108
40109    /**
40110     * 부모창 - 자식창 파일 리스트 복사
40111     */
40112    this.sync = function(inputId, targetUl)
40113    {
40114        self.aOpt.eInputFile = EC$('#'+inputId);
40115        // 파일리스트 목록
40116        var aFileListContainer = self._getFileListContainer(inputId);
40117        // 추가된 파일 리스트 없을 경우 처리안함
40118        if (aFileListContainer.find('li').length < 1) return false;
40119        // 파일리스트 복사
40120        targetUl.append(aFileListContainer.find('li'));
40121
40122
40123    };
40124};
40125
40126EC$(function() {
40127    // 최근 본 상품 쿠키 세팅하기
40128    var sPath = document.location.pathname;
40129    var sPattern = /[\/a-zA-Z\-01]{0,7}\/product\/(.+?)\/([0-9]+)(\/.*|)/;
40130    var aMatchResult = sPath.match(sPattern);
40131
40132    if (aMatchResult) {
40133        var iProductNo = aMatchResult[2];
40134    } else {
40135        var iProductNo = NEWPRODUCT_Recent.getParameterByName('product_no');
40136    }
40137
40138    var sCookieName = 'recent_plist' + (SHOP.isDefaultShop() ? '' : CAFE24.SDE_SHOP_NUM);
40139    var sCookieVal = EC$.cookie(sCookieName);
40140
40141    EC$.cookie(sCookieName, NEWPRODUCT_Recent.getRecentUnique(iProductNo , sCookieVal), {
40142        'path': '/',
40143        'expires': NEWPRODUCT_Recent.getExpirePeriod()
40144    });
40145
40146    // ie하위 버젼에서는 로컬 스토리지 동작 안함으로 인해서 시도도 안함!
40147    // 기존 쿠키 방식 그대로 씀
40148    if (NEWPRODUCT_Recent.getIsLocalStorageAble() === true) {
40149        NEWPRODUCT_Recent.setProductRecentInfo(parseInt(iProductNo, 10));
40150    }
40151});
40152
40153var NEWPRODUCT_Recent =
40154    {
40155        iMaxLength: 50,
40156        iDefaultExpirePeriod: 365,
40157        sStorageKey: 'localRecentProduct' + CAFE24.SDE_SHOP_NUM,
40158        /**
40159         * 최근 본 상품 쿠키 유지기간 가져오기 [ECHOSTING-359005]
40160         * 서버(appShopFrontDispProductDetailAction)가 주입한 설정값을 사용하며,
40161         * 주입되지 않았거나 허용범위(1~365일)를 벗어나면 기존 동작인 365일을 유지한다.
40162         * @return int 쿠키 유지기간(일)
40163         */
40164        getExpirePeriod: function () {
40165            var iPeriod = 0;
40166
40167            if (typeof EC_FRONT_JS_CONFIG_SHOP !== 'undefined' && EC_FRONT_JS_CONFIG_SHOP !== null) {
40168                iPeriod = parseInt(EC_FRONT_JS_CONFIG_SHOP.recent_period, 10);
40169            }
40170
40171            if (isNaN(iPeriod) === true || iPeriod < 1 || iPeriod > this.iDefaultExpirePeriod) {
40172                return this.iDefaultExpirePeriod;
40173            }
40174
40175            return iPeriod;
40176        },
40177        /**
40178         * url에서 파라미터 가져오기
40179         * @param string name 파라미터명
40180         * @return string 파라미터 값
40181         */
40182        getParameterByName: function (name) {
40183            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
40184            var regexS = "[\\?&]" + name + "=([^&#]*)";
40185            var regex = new RegExp(regexS);
40186            var results = regex.exec(window.location.href);
40187
40188            if (results == null) {
40189                return '';
40190            } else {
40191                return decodeURIComponent(results[1].replace(/\+/g, " "));
40192            }
40193        },
40194
40195        /**
40196         * SEO URL 에서 name 파라메터 값 가져오기, SEO URL 이 아니면  getParameterByName 에서 요청
40197         * @param string name 파라미터명
40198         * @param string sRegexPattern seo url 에서 category 값 가져오기 패턴
40199         * @return string 파라미터 값
40200         */
40201        getParameterFromSeoUrl: function (name, sRegexPattern) {
40202            var regex = new RegExp(sRegexPattern);
40203            var results = regex.exec(window.location.href);
40204
40205            if (results == null) {
40206                return NEWPRODUCT_Recent.getParameterByName(name);
40207            } else {
40208                return decodeURIComponent(results[2].replace(/\+/g, " "));
40209            }
40210        },
40211
40212        /**
40213         * 최근상품번호 리스트 가져오기
40214         * @param int iProductNo product_no
40215         * @return string 기존 쿠키값에 현재 상품리스트 추가한 쿠키값
40216         */
40217        getRecentUnique: function (iProductNo, sCookieVal)
40218        {
40219            var newList = [];
40220            var aList = sCookieVal ? sCookieVal.split('|') : [];
40221
40222            for (var i = 0; i < aList.length; i++) {
40223                var sNo = CAFE24.UTIL.trim(aList[i]);
40224                if (sNo == '' || sNo == iProductNo) {
40225                    continue; // 이미 있으면 skip...
40226                }
40227                newList.push(sNo);
40228            }
40229            newList.push(iProductNo);
40230
40231            if (newList.length >= this.iMaxLength) {
40232                newList = newList.slice(newList.length - this.iMaxLength);
40233            }
40234            return newList.join('|');
40235        },
40236        /**
40237         * 최근상품 상품명 저장시 상품명 자르기
40238         * @return string 상품명
40239         */
40240        getCutProductName: function() {
40241            var iByte = 0;
40242            var sProductNameTmp = product_name.replace(/(<([^>]+)>)/ig,'');
40243            var iStrLength = product_name.length;
40244            var iMaxItem = 10;
40245            var sProductName = '';
40246            var iMaxLimit = 10;
40247
40248            // 상품명에 태그가 포함되어 있지 않은 경우
40249            if (sProductNameTmp === '') {
40250                sProductNameTmp = product_name;
40251            }
40252
40253            for (var i=0; i < iStrLength; i++) {
40254                if (escape(sProductNameTmp.charCodeAt(i)).length > 4) {
40255                    iByte +=2; //한글이면 2를 더한다
40256                    iMaxItem -= 1;
40257                }
40258                if (iByte > iMaxItem) {
40259                    sProductName = sProductNameTmp.slice(0,iMaxItem);
40260                    break;
40261                }
40262            }
40263
40264            if (sProductName === '') {
40265                sProductName = sProductNameTmp.slice(0,iMaxLimit);
40266            }
40267            return sProductName;
40268        },
40269
40270        /*
40271         * sessionStorage 사용
40272         */
40273        setProductRecentInfo: function (iProductNo)
40274        {
40275            var oJsonData = this.getSessionStorageData(this.sStorageKey);
40276            var iObjectKeyCount = 0;
40277            var sRegexCategoryNumberBySeoUrl = '(\/product\/.+?\/[0-9]+\/category\/)([0-9]+)(\/.*|)';
40278            var sRegexDisplayNumberBySeoUrl = '(\/product\/.+?\/[0-9]+\/category\/[0-9]+\/display\/)([0-9]+)(\/.*|)';
40279
40280            var iCateNum = parseInt(NEWPRODUCT_Recent.getParameterFromSeoUrl('cate_no', sRegexCategoryNumberBySeoUrl), 10);
40281            var iDisplayGroup = parseInt(NEWPRODUCT_Recent.getParameterFromSeoUrl('display_group', sRegexDisplayNumberBySeoUrl), 10);
40282            var sProductName = NEWPRODUCT_Recent.getCutProductName();
40283
40284            var oNewStorageData = new Object();
40285            var iDelProductNum = 0;
40286
40287            var aParam = {
40288                product_no: iProductNo,
40289                cate_no: iCateNum,
40290                display_group: iDisplayGroup
40291            };
40292            var sParam = '?' + EC$.param(aParam);
40293            var aNewStorageData = {
40294                'iProductNo': iProductNo,
40295                'sProductName': sProductName,
40296                'sImgSrc': product_image_tiny,
40297                'isAdultProduct': is_adult_product,
40298                'link_product_detail': link_product_detail,
40299                'sParam': sParam
40300            };
40301
40302            oNewStorageData[iObjectKeyCount] = aNewStorageData;
40303            if (oJsonData !== null) {
40304                var aStorageData = CAFE24.UTIL.parseJSON(oJsonData);
40305                for (var iKey in aStorageData) {
40306                    if (isFinite(iKey) === false) {
40307                        continue;
40308                    }
40309                    if (aStorageData[iKey].iProductNo !== iProductNo) {
40310                        iObjectKeyCount++;
40311                        oNewStorageData[iObjectKeyCount] = aStorageData[iKey];
40312                        iDelProductNum = aStorageData[iKey].iProductNo;
40313                    }
40314                }
40315            }
40316            this.setSessionStorageData(this.sStorageKey , oNewStorageData);
40317
40318            if (iObjectKeyCount >= this.iMaxLength) {
40319                this.setUpdateStorageData(CAFE24.UTIL.trim(iDelProductNum));
40320            }
40321        },
40322        /*
40323         * 삭제될 스토리지 범위가 벗어났을 경우 처리 필요해서
40324         */
40325        setUpdateStorageData: function (iProductNo) {
40326            var oJsonData = this.getSessionStorageData(this.sStorageKey);
40327
40328            if (oJsonData === null) {
40329                return;
40330            }
40331            var iCount = 0;
40332            var oNewStorageData = new Object();
40333            var aStorageData = CAFE24.UTIL.parseJSON(oJsonData);
40334            var iStorageLength = aStorageData.length;
40335
40336            var sDeleteKey = this.iMaxLength + '';
40337            // 마지막에 추가되어 있던 상품을 지운다.
40338            delete aStorageData[sDeleteKey];
40339            this.setSessionStorageData(this.sStorageKey , aStorageData);
40340
40341        },
40342
40343        /**
40344         * 중복된 상품번호가 있는가 확인 하는 메소드
40345         */
40346        isDulicateCheck: function (iProductNo , oJsonData) {
40347            var bDulicate = false;
40348
40349            if (oJsonData === null) {
40350                return false;
40351            }
40352            iProductNo = CAFE24.UTIL.trim(iProductNo);
40353            var aStorageData = CAFE24.UTIL.parseJSON(oJsonData);
40354            for (var iKey in aStorageData) {
40355                if (CAFE24.UTIL.trim(aStorageData[iKey].iProductNo) === iProductNo) {
40356                    bDulicate = true;
40357                    break;
40358                }
40359            }
40360            return bDulicate;
40361        },
40362        /**
40363         * get SessionStorage
40364         * @param sStorageKey SessionStorage에 저장되어 있는 key값
40365         */
40366        getSessionStorageData: function (sStorageKey)
40367        {
40368            return sessionStorage.getItem(sStorageKey);
40369        },
40370        /**
40371         * set SessionStorage
40372         * @param sStorageKey SessionStorage에 저장할 key값
40373         * @param sStorageValue SessionStorage에 저장할 value값
40374         */
40375        setSessionStorageData: function (sStorageKey , sStorageValue)
40376        {
40377            return sessionStorage.setItem(sStorageKey , EC$.toJSON(sStorageValue));
40378        },
40379
40380        /**
40381         * 세션스토리지가 사용가능한지 확인
40382         */
40383        getIsLocalStorageAble: function() {
40384            var sTestKey = 'CAPP_TMP_KEY';
40385            try {
40386                window.localStorage.setItem(sTestKey, 1);
40387                window.localStorage.removeItem(sTestKey);
40388                return true;
40389            } catch (e) {
40390                return false;
40391            }
40392        }
40393};
40394CAFE24.FRONT_NEW_PRODUCT_LAZYLOAD = {
40395        resetDetailContent: function() 
40396        {
40397            var oProductDetailContent = null;
40398            if (EC$('.xans-product-additional').find('#prdDetailContent').html() !== null) {
40399                oProductDetailContent = EC$('.xans-product-additional').find('#prdDetailContent');
40400            } else if (EC$('.xans-product-additional').find('div.prdDetailView') !== null) {
40401                oProductDetailContent = EC$('.xans-product-additional').find('div.prdDetailView');
40402                EC$('div.moreBtn').hide();
40403            }
40404            if (oProductDetailContent !== null && oProductDetailContent.html() !== '') {
40405                var sDetailContent = oProductDetailContent.html();
40406                 oProductDetailContent.html('').hide();
40407                 var sDetailForm = '<div id=\"prdDetailContentLazy\">'+ sDetailContent + '</div>';
40408                 oProductDetailContent.after(sDetailForm);
40409            }
40410        }
40411};
40412
40413var EC_FRONT_NEW_PRODUCT_LAZYLOAD = CAFE24.getDeprecatedNamespace('EC_FRONT_NEW_PRODUCT_LAZYLOAD');
40414
40415/**
40416 *
40417 */
40418
40419EC$(function() {
40420	EC$('.btn_review').click(function() {
40421		var cont_id = EC$(this).attr('rel');
40422
40423		EC$('#review_'+cont_id).toggle();
40424	});
40425
40426	EC_PRODUCT_FRONT_BOARD_REVIEW.init();
40427});
40428
40429var EC_PRODUCT_FRONT_BOARD_REVIEW = {
40430	bInit : false,
40431	init : function() {
40432		if (this.bInit === true) {
40433			return;
40434		}
40435		this.bInit = true;
40436		this.board_link_alert();
40437	},
40438
40439	board_link_alert: function() {
40440		EC$('.xans-product-review').on('click', 'a', function(event) {
40441			// URL 생성 시 유효성 검사 추가
40442			try {
40443				var link = event.target.href;
40444				var linkDomain = new URL(link).hostname;
40445			} catch (e) {
40446				return;
40447			}
40448
40449			var currentDomain = window.location.hostname;
40450
40451			if (linkDomain != '' && linkDomain !== currentDomain) {
40452				if (confirm(__('PAGE.ARE.TRYING.ACCESS', 'BOARD.JS.APP.BOARD.READ')) === false) {
40453					event.preventDefault();
40454					return false;
40455				}
40456			}
40457		});
40458	},
40459	modify: function (iBulletinNo, iProductNo) {
40460		if (typeof CAFE24.FRONT_EXTERNAL_SCRIPT_VARIABLE_DATA.common_member_id_crypt !== 'undefined'
40461			&& CAFE24.FRONT_EXTERNAL_SCRIPT_VARIABLE_DATA.common_member_id_crypt.length > 0) {
40462			var sUrl = '/board/product/modify.html?board_act=edit&no=' + iBulletinNo + '&board_no=4&link_product_no=' + iProductNo;
40463
40464			var oEncryptedStr = document.createElement('input');
40465			oEncryptedStr.setAttribute('type', 'hidden');
40466			oEncryptedStr.setAttribute('name', 'encrypted_str');
40467			oEncryptedStr.setAttribute('value', 'dummy'); // 회원 비밀번호 검증 로직을 태우기 위한 필수 변수이므로 dummy 값을 실어 보냄
40468
40469			var oForm = document.createElement('form');
40470			oForm.action = sUrl;
40471			oForm.method = 'post';
40472
40473			oForm.appendChild(oEncryptedStr);
40474
40475			document.body.appendChild(oForm);
40476			oForm.submit();
40477		} else {
40478			var sMessage = __('PLEASE.ENTER.PASSWORD', 'JS.FRONT.PRODUCT.QNA');
40479
40480			if (confirm(sMessage)) {
40481				location.href = '/board/product/read.html?no=' + iBulletinNo + '&board_no=4';
40482			}
40483		}
40484	}
40485};
40486var iSecretFormNo = '';
40487var sSecretFormAction = '';
40488
40489var PRODUCT_COMMENT = {
40490    //댓글 저장 요청 URL
40491    sCommentInsertUrl: false,
40492    //댓글의 댓글 저장 요청 URL
40493    sCommentReplyInsertUrl: false,
40494    //비밀댓글 패스워드 확인 URL
40495    sCommentSecretUrl: false,
40496    //댓글 저장시 현재 바라보는 게시판 번호
40497    iCommentInsertBoardNo: false,
40498    //댓글의 댓글 저장시 현재 바라보는 게시판 번호
40499    iCommentReplyInsertBoardNo: false,
40500
40501    /**
40502     * 키보드 입력시 체크하기
40503     */
40504    comment_byte: function(iBoardNo, iKey, sFormName)
40505    {
40506        var iBoardNo = iBoardNo + iKey;
40507        if (!sFormName) {
40508            sFormName ='commentWriteForm_'+iBoardNo;
40509        } else {
40510            sFormName =sFormName+'_'+iBoardNo;
40511        }
40512
40513        var targetByte = EC$('#'+sFormName).find('#comment_byte');
40514        var comment_size = CAFE24.UTIL.trim(targetByte.attr('title'));
40515        var content = 'comment';
40516        if (comment_size == '') return false;
40517        if (comment_size > 0) {
40518            EC$('#'+sFormName).find('#'+content).off('keyup', function() {
40519                PRODUCT_COMMENT.limitWord(this, comment_size, sFormName);
40520            });
40521        }
40522    },
40523
40524    /**
40525     * 글자 제한하기
40526     * @param txt
40527     * @param limit
40528     */
40529    limitWord: function(txt, limit, sFormName)
40530    {
40531        var strLen = this.stringByteSize(txt.value);
40532        if (strLen > limit) {
40533            alert(sprintf(__('메시지는 %s Byte 이하로 입력해주세요.'), limit));
40534            txt.value = txt.value.substring(0, limit);
40535            return;
40536        }
40537        EC$('#'+sFormName).find("#comment_byte").text(strLen);
40538    },
40539
40540    /**
40541     * 문자열을 UTF-8로 변환했을 경우 차지하게 되는 byte 수를 리턴한다.
40542     */
40543    stringByteSize: function(str)
40544    {
40545        if (str == null || str.length == 0) return 0;
40546        var size = 0;
40547        for (var i = 0; i < str.length; i++) {
40548          size += this.charByteSize(str.charAt(i));
40549        }
40550        return size;
40551    },
40552
40553    /**
40554     * 글자수 체크
40555     * @param ch
40556     * @returns {Number}
40557     */
40558    charByteSize: function(ch)
40559    {
40560        if (ch == null || ch.length == 0) return 0;
40561        var charCode = ch.charCodeAt(0);
40562        if (escape(charCode).length > 4) {
40563            return 2;
40564        } else {
40565            return 1;
40566        }
40567    },
40568
40569    /**
40570     * 댓글의 댓글 입력폼 출력
40571     * @param bbs_no
40572     * @param comment_no
40573     * @param iBoardNo
40574     * @param e
40575     */
40576    comment_reply_write: function(iBoardNo, iCommentNo, e)
40577    {
40578        var $form = EC$("#commentReplyWriteForm_"+iBoardNo);
40579        $form.css('display', 'block');
40580        $form.get(0).reset();
40581        if ($form.find('#comment_no').length < 1) {
40582            $form.append('<input type="hidden" name="comment_no" value="'+iCommentNo+'" />');
40583        } else {
40584            alert('update');
40585            //$form.find('#comment_no').val(iCommentNo);
40586        }
40587
40588        var $p = EC$(e).parent();
40589        //if ( $p.parent().find('#commentReplyWriteForm_'+iBoardNo).length < 1 ) {
40590            $p.after($form);
40591        //}
40592    },
40593
40594    /**
40595     * 댓글의 댓글 모바일 신규스킨 입력폼 출력
40596     * @param comment_no
40597     * @param iBoardNo
40598     * @param e
40599     */
40600    comment_reply_write_new: function(iBoardNo, iCommentNo, e)
40601    {
40602        var $form = EC$("#commentReplyWriteForm_"+iBoardNo);
40603        if ($form.css('display') == 'none') {
40604            $form.css('display', 'block');
40605            $form.get(0).reset();
40606            if ($form.find('#comment_no').length < 1) {
40607                $form.append('<input type="hidden" name="comment_no" value="'+iCommentNo+'" />');
40608            } else {
40609                alert('update');
40610            }
40611            EC$(e).parent().parent().after($form);
40612         } else {
40613             $form.css('display', 'none');
40614         }
40615    },
40616
40617    /**
40618     * 댓글 저장
40619     * @param action_url
40620     * @param form_name
40621     * @returns {Boolean}
40622     */
40623    comment_insert: function(action_url, iBoardNo)
40624    {
40625        this.sCommentInsertUrl = action_url;
40626        this.iCommentInsertBoardNo = iBoardNo;
40627
40628         var label = EC$('#comment_password').attr('fw-label');
40629
40630        try {
40631            label = decodeURIComponent(label);
40632        } catch (err) {
40633
40634        }
40635
40636        EC$('#comment_password').attr('fw-label', label);
40637
40638        var form = EC$('#commentWriteForm_'+iBoardNo);
40639        var result = FwValidator.inspection('commentWriteForm_'+iBoardNo);
40640        if (result.passed) {
40641
40642            //SSL 처리
40643            var aEleId = [EC$("#commentWriteForm_"+iBoardNo+" #comment_name"),
40644                          EC$("#commentWriteForm_"+iBoardNo+" #comment_password")];
40645
40646            AuthSSLManager.weave({
40647                'auth_mode': 'encrypt',
40648                'aEleId': aEleId,
40649                'auth_callbackName': 'PRODUCT_COMMENT.comment_insert_ajax'
40650            });
40651        }
40652
40653        return false;
40654    },
40655
40656    /**
40657     * 댓글 저장 콜백함수.
40658     * 댓글을 저장하는 요청을 함.
40659     *
40660     * @param callbackParam
40661     */
40662    comment_insert_ajax: function(output)
40663    {
40664        //SSL 실패확인
40665        var output = decodeURIComponent(output);
40666        if (AuthSSLManager.isError(output) == true) {
40667            return;
40668        }
40669
40670        var iBoardNo = this.iCommentInsertBoardNo;
40671        var action_url = this.sCommentInsertUrl;
40672
40673        this.sCommentInsertUrl = false;
40674        this.iCommentInsertBoardNo = false;
40675
40676        var form = EC$('#commentWriteForm_'+iBoardNo);
40677
40678        //암호화된 필드 내 값 제거
40679        var sTempCommentName = '';
40680        sTempCommentName = EC$("#commentWriteForm_"+iBoardNo+" #comment_name").val();
40681
40682        EC$("#commentWriteForm_"+iBoardNo+" #comment_name").val('');
40683        EC$("#commentWriteForm_"+iBoardNo+" #comment_password").val('');
40684
40685        //암호화 문자열을 전송하기위해 input 삽입
40686        var oInput = document.createElement('input');
40687        oInput.type = 'hidden';
40688        oInput.name = oInput.id = AuthSSL.sEncryptId;
40689        oInput.value = output;
40690        form.append(oInput);
40691
40692        var formData = form.serializeArray() || [];
40693        // 비밀글 선택되어 있고, disabled된 경우
40694        if (EC$('[name=secure]:disabled', form).val() == 'T') {
40695            formData.push({name: 'secure', value: 'T'});
40696        }
40697        EC$.post(action_url+iBoardNo, EC$.param(formData), function(req) {
40698            if (!req.failed) {
40699                self.location.reload();
40700            } else {
40701                EC$("#commentWriteForm_"+iBoardNo+" #comment_name").val(sTempCommentName);
40702                alert(decodeURIComponent(req.msg));
40703                return false;
40704            }
40705        },'json');
40706    },
40707
40708    /**
40709     * 댓글의 댓글 저장
40710     * @param action_url
40711     * @param form_name
40712     * @returns {Boolean}
40713     */
40714    comment_reply_insert: function(action_url, iBoardNo)
40715    {
40716        this.sCommentReplyInsertUrl = action_url;
40717        this.iCommentReplyInsertBoardNo = iBoardNo;
40718
40719        var form = EC$('#commentReplyWriteForm_'+iBoardNo);
40720        var result = FwValidator.inspection('commentReplyWriteForm_'+iBoardNo);
40721        if (result.passed) {
40722
40723            //SSL 처리
40724            var aEleId = [EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_name"),
40725                          EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_password")];
40726
40727            AuthSSLManager.weave({
40728                'auth_mode': 'encrypt',
40729                'aEleId': aEleId,
40730                'auth_callbackName': 'PRODUCT_COMMENT.comment_reply_insert_ajax'
40731            });
40732        }
40733
40734        return false;
40735    },
40736
40737    /**
40738     * 댓글의 댓글 저장 콜백함수.
40739     * 댓글의 댓글을 저장하는 요청을 함.
40740     *
40741     * @param callbackParam
40742     */
40743    comment_reply_insert_ajax: function(output)
40744    {
40745        //SSL 실패확인
40746        var output = decodeURIComponent(output);
40747        if (AuthSSLManager.isError(output) == true) {
40748            return;
40749        }
40750
40751        var iBoardNo = this.iCommentReplyInsertBoardNo;
40752        var action_url = this.sCommentReplyInsertUrl;
40753
40754        this.iCommentReplyInsertBoardNo = false;
40755        this.sCommentReplyInsertUrl = false;
40756
40757        var form = EC$('#commentReplyWriteForm_'+iBoardNo);
40758
40759        //암호화된 필드 내 값 제거
40760        var sTempCommentName = '';
40761        sTempCommentName = EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_name").val();
40762
40763        EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_name").val('');
40764        EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_password").val('');
40765
40766        //암호화 문자열을 전송하기위해 input 삽입
40767        var oInput = document.createElement('input');
40768        oInput.type = 'hidden';
40769        oInput.name = oInput.id = AuthSSL.sEncryptId;
40770        oInput.value = output;
40771        form.append(oInput);
40772
40773        var formData = form.serializeArray() || [];
40774        // 비밀글 선택되어 있고, disabled된 경우
40775        if (EC$('[name=secure]:disabled', form).val() == 'T') {
40776            formData.push({name: 'secure', value: 'T'});
40777        }
40778        EC$.post(action_url+iBoardNo, EC$.param(formData), function(req) {
40779            if (!req.failed) {
40780                self.location.reload();
40781            } else {
40782                EC$("#commentReplyWriteForm_"+iBoardNo+" #comment_name").val(sTempCommentName);
40783                alert(decodeURIComponent(req.msg));
40784                return false;
40785            }
40786        },'json');
40787
40788
40789        return false;
40790    },
40791
40792    /**
40793     * 댓글의댓글 보기
40794     * @param comment_no
40795     */
40796    comment_reply_view: function (iCommentNo)
40797    {
40798        EC$('[id^="replyArea_'+iCommentNo+'_"]').each(function(e) {
40799            if (EC$(this).css('display') == 'none') {
40800                EC$(this).show();
40801            } else {
40802                EC$(this).hide();
40803            }
40804        });
40805    },
40806
40807    form_submit: function(sFormName, iNo, sAction)
40808    {
40809        var aId = new Array();
40810        var iId = 0;
40811        iSecretFormNo = iNo;
40812        sSecretFormAction = sAction;
40813
40814        if (EC$('#'+sFormName+' [id="secure_password"]').val()) {
40815            aId[iId] = sFormName+'::secure_password';
40816        }
40817
40818        AuthSSL.init(sFormName, aId);
40819
40820        // 암호화 된 값을 받을 input_hidden 생성
40821        var oInput = document.createElement('input');
40822        oInput.type = 'hidden';
40823        oInput.name = oInput.id = AuthSSL.sEncryptId;
40824        AuthSSL.oFormSubmit.append(oInput);
40825
40826        AuthSSL.encrypt(AuthSSL.aEleId, 'PRODUCT_COMMENT.form_submit_go');
40827    },
40828
40829    form_submit_go: function(sOutput)
40830    {
40831        // 암호화 값 삭제
40832        var sFormName = AuthSSL.sFormId;
40833        AuthSSL.delInputValue();
40834        EC$('#'+sFormName).find('[id="'+AuthSSL.sEncryptId+'"]').val(sOutput);
40835
40836        var oNoInput = document.createElement('input');
40837        oNoInput.type = 'hidden';
40838        oNoInput.name = 'no';
40839        oNoInput.value = iSecretFormNo;
40840        AuthSSL.oFormSubmit.append(oNoInput);
40841
40842        EC$.post(sSecretFormAction, EC$('#'+sFormName).serialize(), function(req) {
40843            if (req.failed) {
40844                 alert(req.msg);
40845                 EC$('#' + sFormName + ' [id="secure_password"]').focus();
40846                 return;
40847            } else {
40848                if (sFormName == 'SecretForm_4') {
40849                    REVIEW.getReadData();
40850                } else if (sFormName == 'SecretForm_6') {
40851                    QNA.getReadData();
40852                }
40853            }
40854        }, 'json');
40855    },
40856
40857    /**
40858     * 상품상세페이지내의 상품사용후기나 Q&A 게시판의 평점기능 사용 안함일때
40859     * display되어있는 td갯수에 따라 상세내용의 td의 colspan을 수정함
40860     *
40861     * @param tr 선택된 게시물의 제목이 있는 tr
40862     */
40863    comment_colspan: function(tr)
40864    {
40865        var $tr = EC$(tr);
40866        var iColspan = $tr.children('td:not(.displaynone)').length;
40867
40868        var $comment = $tr.next('tr');
40869        $comment.hide();
40870        if ($comment.children('td').first().attr('colspan') != iColspan) {
40871            $comment.children('td').first().attr('colspan', iColspan);
40872            var aTds = [];
40873            for (var i = 0; i < $tr.children('td').length-iColspan; i++) {
40874                aTds.push('<td class="displaynone"></td>');
40875            }
40876            $comment.children('td').first().after(aTds.join(''));
40877        }
40878        $comment.show();
40879     },
40880
40881    /**
40882     * 비밀댓글 비밀번호 확인 폼 출력
40883     *
40884     * @param sBoardNo
40885     * @param iCommentNo
40886     * @param e
40887     */
40888    show_secret_comment_form: function(sBoardNo, iCommentNo, e)
40889    {
40890        var $form = EC$('#commentSecretForm_'+sBoardNo);
40891        if ($form.length > 0) {
40892            $form.css('display', 'block');
40893            $form[0].reset();
40894            var $comment_no = EC$('[name=comment_no]', $form);
40895            if ($comment_no.length < 1) {
40896                $comment_no = EC$('<input type="hidden" name="comment_no"/>');
40897                $form.append($comment_no);
40898            }
40899            $comment_no.val(iCommentNo);
40900
40901            EC$(e).parent().after($form);
40902        }
40903        return false;
40904    },
40905
40906    /**
40907     * 비밀댓글 확인
40908     *
40909     * @param sActionUrl
40910     * @param sBoardNo
40911     */
40912    show_secret_comment: function(sActionUrl, sBoardNo)
40913    {
40914        this.sCommentSecretUrl = sActionUrl;
40915        this.iCommentInsertBoardNo = sBoardNo;
40916
40917        var $form = EC$('#commentSecretForm_'+sBoardNo);
40918        var result = FwValidator.inspection('commentSecretForm_'+sBoardNo);
40919        if (result.passed) {
40920            //SSL 처리
40921            var aEleId = [EC$('#secure_password', $form)];
40922
40923            AuthSSLManager.weave({
40924                'auth_mode': 'encrypt',
40925                'aEleId': aEleId,
40926                'auth_callbackName': 'PRODUCT_COMMENT.show_secret_comment_ajax'
40927            });
40928        }
40929        return false;
40930    },
40931
40932    /**
40933     * 비밀댓글 확인 암호화 콜백함수
40934     *
40935     * @param sOutput
40936     */
40937    show_secret_comment_ajax: function(sOutput)
40938    {
40939       //SSL 실패확인
40940        var sOutput = decodeURIComponent(sOutput);
40941        if (AuthSSLManager.isError(sOutput) == true) {
40942            return;
40943        }
40944
40945        var sBoardNo = this.iCommentInsertBoardNo;
40946        var sActionUrl = this.sCommentSecretUrl;
40947
40948        this.sCommentSecretUrl = false;
40949        this.iCommentInsertBoardNo = false;
40950
40951        var $form = EC$('#commentSecretForm_'+sBoardNo);
40952
40953        //암호화된 필드 내 값 제거
40954        EC$('#secure_password', $form).val('');
40955        var oEncryptElement = EC$('<input/>', {
40956            type: 'hidden',
40957            name: AuthSSL.sEncryptId,
40958            id: AuthSSL.sEncryptId,
40959            value: sOutput
40960        });
40961        $form.append(oEncryptElement);
40962        EC$.post(sActionUrl+sBoardNo, $form.serialize(), function(req) {
40963            if (req.failed) {
40964                alert(req.msg);
40965                 EC$("input[name='"+ AuthSSL.sEncryptId +"']", $form).remove();
40966                 EC$('#secure_password', $form).focus();
40967                return false;
40968            }
40969
40970            var aData = req.data;
40971            EC$('#comment_contents' + aData.comment_no).html(aData.comment);
40972            PRODUCT_COMMENT.hide_secret_comment_form(sBoardNo);
40973        },'json');
40974    },
40975
40976    /**
40977     * 비밀댓글 비밀번호 확인 폼 숨김
40978     *
40979     * @param sBoardNo
40980     */
40981    hide_secret_comment_form: function(sBoardNo)
40982    {
40983        var $form = EC$('#commentSecretForm_'+sBoardNo);
40984        $form.css('display', 'none');
40985
40986        return false;
40987    },
40988
40989    END: function() {}
40990};
40991
40992var APP_BOARD_UCC = {
40993    bInit: false,
40994    oRegex: /(http:|https:|)\/\/(player\.|www\.|embed\.|media\.)?((vimeo\.com|youtu(be\.com|\.be|be\.googleapis\.com)|dailymotion\.com|dai\.ly|google.com\/maps|gettyimages\.com\/embed|gettyimages\.com\/videos|gettyimages.com\/detail|video|instagram\.com|facebook\.com)\/(news-photo\/[^\/]+\/|video\/[^\/]+\/|photo\/[^\/]+\/|embed\/video\/|shorts\/|video\/|embed\/|watch\?v=|v\/|embed\?pb=|p\/|plugins\/video\.php\?href=|plugins\/post\.php\?href=|[a-z0-9.]+\/posts\/|[a-z0-9]+\/videos\/)?([^\&\#\"\'\/<\s]*)|([^\&\#\"\'<\s]+)(\.avi|\.mpg|\.mpeg|\.wmv|\.dat|\.k3g|\.ogm|\.m2v|\.mov|\.3gp|\.mp4)+)/i,
40995    oTemplate: {
40996        iframe: '<iframe src="%1$s" frameborder="0" style="border:0" webkitAllowFullScreen mozallowfullscreen allowfullscreen></iframe>',
40997        instagram: [
40998            '<blockquote class="instagram-media" data-instgrm-permalink="%1$s" data-instgrm-version="12"></blockquote>'
40999        ].join("\n"),
41000        facebook: [
41001            '<div class="fb-%1$s" data-href="%2$s"></div>'
41002        ].join("\n"),
41003        mp4: [
41004            '<video width="100%" height="100%" controls>',
41005            '<source src="" type="video/mp4">',
41006            '</video>'
41007        ].join(''),
41008        img: [
41009            '<img src="%s">'
41010        ].join('')
41011    },
41012    sUrl: '',
41013    iWidth: 0,
41014    iHeight: 0,
41015    init: function ()
41016    {
41017        var self = APP_BOARD_UCC;
41018        if (self.bInit === true) {
41019            return;
41020        }
41021        self.bInit = true;
41022        self.setEvent();
41023        self.setPreview();
41024    },
41025    setEvent: function () {
41026        var self = APP_BOARD_UCC;
41027        if (self.isExist() === false) {
41028            return;
41029        }
41030        self.getUccInput().keyup(function () {
41031            if (self.sUrl != self.getUccText()) {
41032                self.sUrl = self.getUccText();
41033                self.setWritePreview();
41034            }
41035        }).focusout(function () {
41036            self.setUccText(self.getEmbedUrl());
41037        });
41038    },
41039    setPreview: function ()
41040    {
41041        var self = APP_BOARD_UCC;
41042
41043        self.setWritePreview();
41044        self.setReadPreview();
41045    },
41046    isFrontRead: function ()
41047    {
41048        return typeof EC_FRONT_JS_ARTICLES !== 'undefined';
41049    },
41050    isFrontWrite: function ()
41051    {
41052        var self = APP_BOARD_UCC;
41053        return self.getUccInput().length > 0;
41054    },
41055    setReadPreview: function()
41056    {
41057        var self = APP_BOARD_UCC;
41058        if (self.isFrontRead()) {
41059            EC$.each(EC_FRONT_JS_ARTICLES, function (iNo, oArticle) {
41060                var $oPreviewElement = self.getPreviewElement(oArticle.ucc_url);
41061                if ($oPreviewElement) {
41062                    $oPreviewElement.attr('class', 'ec-ucc-media-box-' + iNo);
41063                    EC$('.ec-ucc-media-box-' + iNo).replaceWith($oPreviewElement);
41064                }
41065            });
41066        }
41067    },
41068    setWritePreview: function()
41069    {
41070        var self = APP_BOARD_UCC;
41071        if (self.isFrontWrite()) {
41072            var sType = self.getUrlType();
41073            if (sType != 'NONE') {
41074                var $oPreviewElement = self._getPreviewElement();
41075                if (self.getUccInput().length > 0) { // 추가/수정 페이지
41076                    self.removePreviewElement();
41077                    self.getUccInput().parent().append($oPreviewElement);
41078                }
41079            } else {
41080                self.removePreviewElement();
41081            }
41082        }
41083    },
41084    removePreviewElement: function()
41085    {
41086        EC$('.ec-ucc-media-box').fadeOut(200).remove();
41087    },
41088    getPreviewElement: function (sUccText)
41089    {
41090        var self = APP_BOARD_UCC;
41091        var sOldUccText = self.getUccText();
41092        self.setUccText(sUccText);
41093        var $oPreviewElement = self._getPreviewElement();
41094        self.setUccText(sOldUccText);
41095
41096        return $oPreviewElement;
41097    },
41098    _getPreviewElement: function ()
41099    {
41100        var self = APP_BOARD_UCC;
41101
41102        var sType = self.getUrlType();
41103        var $oMediaBox = null;
41104        var $oElement = null;
41105        switch (sType) {
41106            case 'VIMEO' :
41107            case 'YOUTUBE' :
41108            case 'DAILYMOTION' :
41109            case 'GOOGLE_MAP' :
41110                $oElement = EC$(sprintf(self.oTemplate.iframe, self.getEmbedUrl()));
41111                break;
41112            case 'MP4' :
41113                $oElement = EC$(self.oTemplate.mp4);
41114                $oElement.find('source').attr('src', self.getEmbedUrl());
41115                $oElement[0].load();
41116                break;
41117            default :
41118                break;
41119        }
41120        if ($oElement) {
41121            $oElement.css({
41122                position: 'absolute',
41123                top: 0,
41124                left: 0,
41125                width: '100%',
41126                height: '100%'
41127            });
41128            $oMediaBox = EC$('<div class="ec-ucc-media-box">');
41129            $oMediaBox.css({
41130                'position': 'relative',
41131                'max-height': '100%',
41132                'padding-bottom': '56.25%',
41133                'overflow': 'hidden',
41134                'margin-bottom': '14px'
41135            }).append($oElement);
41136        }
41137        return $oMediaBox;
41138    },
41139    getUrlType: function () {
41140        var self = APP_BOARD_UCC;
41141        var aUrl = self.getUccText().match(self.oRegex);
41142        var sType = 'NONE';
41143        if (aUrl && aUrl[0]) {
41144            switch (aUrl[4]) {
41145                case 'vimeo.com' :
41146                    sType = 'VIMEO';
41147                    break;
41148                case 'youtube.com' :
41149                case 'youtube.googleapis.com' :
41150                case 'youtu.be' :
41151                    sType = 'YOUTUBE';
41152                    break;
41153                case 'dai.ly' :
41154                case 'dailymotion.com' :
41155                    sType = 'DAILYMOTION';
41156                    break;
41157                case 'google.com/maps' :
41158                case 'goo.gl/maps' :
41159                    sType = 'GOOGLE_MAP';
41160                    break;
41161                default :
41162                    if (aUrl[9] && aUrl[9].length > 0) {
41163                        sType = 'MP4';
41164                    }
41165                    break;
41166            }
41167        }
41168        return sType;
41169    },
41170    getEmbedUrl: function () {
41171        var self = APP_BOARD_UCC;
41172        var aUrl = self.getUccText().match(self.oRegex);
41173        var sUrl = '';
41174        if (aUrl && aUrl[0]) {
41175            var sType = self.getUrlType();
41176            switch (sType) {
41177                case 'YOUTUBE' :
41178                    sUrl = sprintf('https://www.youtube.com/embed/%s', aUrl[7]);
41179                    break;
41180                case 'VIMEO' :
41181                    sUrl = sprintf('https://player.vimeo.com/video/%s', aUrl[7]);
41182                    break;
41183                case 'DAILYMOTION' :
41184                    sUrl = sprintf('https://www.dailymotion.com/embed/video/%s', aUrl[7]);
41185                    break;
41186                case 'GOOGLE_MAP' :
41187                    sUrl = sprintf('https://www.google.com/maps/embed?pb=%s', aUrl[7]);
41188                    break;
41189                case 'MP4' :
41190                    sUrl = aUrl[0];
41191                    break;
41192                default :
41193                    break;
41194            }
41195        }
41196        return sUrl;
41197    },
41198    getUccText: function ()
41199    {
41200        try {
41201            if (this.getUccInput().length > 0) {
41202                return this.getUccInput().val();
41203            } else if (this.sUrl.length > 0) {
41204                return this.sUrl;
41205            }
41206        } catch (e) {}
41207
41208        return '';
41209    },
41210    setUccText: function (sText)
41211    {
41212        this.sUrl = sText;
41213        this.getUccInput().val(sText);
41214    },
41215    getUccInput: function ()
41216    {
41217        return EC$('input#ucc');
41218    },
41219    isExist: function()
41220    {
41221        var self = APP_BOARD_UCC;
41222        if (self.getUccInput().length > 0) {
41223            return true;
41224        }
41225        return false;
41226    }
41227};
41228
41229EC$(function () {
41230    APP_BOARD_UCC.init();
41231});
41232
41233var APP_BOARD_REPORT = {
41234    bInit: false,
41235    STORAGE_KEY: 'APP_BOARD_REPORT_' + CAFE24.SHOP.getMallID() + '_' + CAFE24.SDE_SHOP_NUM,
41236    aBlockList: null,
41237    bAction: false,
41238    iMax: 1000,
41239    init: function ()
41240    {
41241        var self = APP_BOARD_REPORT;
41242        if (self.bInit === true) {
41243            return;
41244        }
41245        self.bInit = true;
41246
41247        if (this.isRun() === false) {
41248            return;
41249        }
41250        //게시판 스팩과 동일하게 비회원 상태일 경우 처리가 동일
41251        // if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
41252        //     return;
41253        // }
41254        // this.setEvent();
41255        // this.setBlockList();
41256    },
41257    setDefaultUI: function ()
41258    {
41259        EC$('.ec-report-target').hide();
41260    },
41261    useReport: function (iBoardNo)
41262    {
41263        if (iBoardNo > 0
41264            && typeof CAFE24.BOARD['config_' + String(iBoardNo)] !== 'undefined'
41265            && CAFE24.BOARD['config_' + String(iBoardNo)].use_report === 'T') {
41266            return true;
41267        }
41268        return false;
41269    },
41270    /**
41271     * 동작 여부를 결정
41272     * @returns {boolean}
41273     */
41274    isRun: function ()
41275    {
41276        if (typeof CAFE24.BOARD === 'undefined') {
41277            return false;
41278        }
41279        var iBoardNo = 0;
41280        for (var sConfigKey in CAFE24.BOARD) {
41281            if (sConfigKey.indexOf('config_') !== -1) {
41282                iBoardNo = parseInt(sConfigKey.replace('config_', ''), 10);
41283                if (this.useReport(iBoardNo) === true) {
41284                    return true;
41285                }
41286            }
41287        }
41288        return false;
41289    },
41290    getBoardNo: function (actionName)
41291    {
41292        var aMatched = actionName.match(/APP_BOARD_REPORT\.(setReport)\('(\S+)','(\d+)'\);/);
41293        if (aMatched !== false) {
41294            var aSplitMatched = aMatched[2].split('/');
41295            return parseInt(aSplitMatched[aSplitMatched.length - 1], 10);
41296        }
41297
41298        return 0;
41299    },
41300    setReportLayerActions: function (reportAction, reportCloseAction, write_auth)
41301    {
41302        APP_BOARD_REPORT.setDefaultUI();
41303        if (APP_BOARD_REPORT.useReport(APP_BOARD_REPORT.getBoardNo(reportAction)) === false || write_auth) {
41304            EC$('.ec-report-target').hide();
41305        } else {
41306            EC$('.ec-report-target').attr("style", "display:inline-block !important;");
41307        }
41308        EC$('.boardReport .ecReportAction').attr('onclick', reportAction);
41309        EC$('.boardReport .ecReportCloseLayer').attr('onclick', reportCloseAction);
41310
41311
41312    },
41313    setReport: function (actionUrl, bulletin_no)
41314    {
41315        var report_reason = EC$("input[name='report_reason']:checked").val();
41316        var aData = {
41317            'no': bulletin_no,
41318            'report_reason': report_reason
41319        };
41320
41321        var aActionUrl = actionUrl.split('/');
41322        var iBoardNo = aActionUrl[aActionUrl.length - 1];
41323
41324        if (APP_BOARD_REPORT.isUserCanReport(iBoardNo, bulletin_no) === false) {
41325            return false;
41326        }
41327
41328        actionUrl += "?shop_no=" + CAFE24.SDE_SHOP_NUM;
41329
41330        EC$.post(actionUrl, aData, function(req) {
41331            alert(req.alertMSG);
41332            self.location.reload();
41333        }, 'json');
41334    },
41335    isUserCanReport: function (iBoardNo, iNo)
41336    {
41337        var bIsLogin = (document.cookie.match(/(?:^| |;)iscache=F/) ? true : false);
41338        if (bIsLogin === false) {
41339            alert(__('YOU.NEED.SHOPPING.MALL', 'B.BOARD.BULLETIN.REPORT.L'));
41340
41341            if (EC_ROUTE.getIsEasyUrl()) { // 쉬운 주소
41342                location.replace("/member/login.html?returnUrl=" + window.location.pathname);
41343            } else {
41344                location.replace("/member/login.html?returnUrl=" + encodeURIComponent(window.location.pathname + "?board_no=" + iBoardNo + "&no=" + iNo));
41345            }
41346
41347            return false;
41348        }
41349        return true;
41350    },
41351    openReportLayer: function (iBoardNo, iNo)
41352    {
41353        if (APP_BOARD_REPORT.isUserCanReport(iBoardNo, iNo) === false) {
41354            return false;
41355        }
41356        EC$('.boardReport').removeClass('displaynone');
41357    },
41358    closeReportLayer: function ()
41359    {
41360        EC$("input[name='report_reason'][value='1']").prop('checked', true);
41361        EC$('.boardReport').addClass('displaynone');
41362    }
41363};
41364
41365EC$(function () {
41366    try {
41367        APP_BOARD_REPORT.init();
41368    } catch (e) {
41369        console.log(e); // 프론트에 영향가지 않도록 처리
41370    }
41371});
41372var APP_BOARD_BLOCK = {
41373    bInit: false,
41374    STORAGE_KEY: 'APP_BOARD_BLOCK_' + CAFE24.SHOP.getMallID() + '_' + CAFE24.SDE_SHOP_NUM,
41375    aBlockList: null,
41376    bAction: false,
41377    iMax: 1000,
41378    init: function ()
41379    {
41380        var self = APP_BOARD_BLOCK;
41381        if (self.bInit === true) {
41382            return ;
41383        }
41384        self.bInit = true;
41385        this.setDefaultUI();
41386        if (this.isRun() === false) {
41387            return ;
41388        }
41389        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
41390            self.setDefaultUINoneMember();
41391            self.deleteBlockListCache();
41392            return;
41393        }
41394        this.setEvent();
41395        this.setBlockList();
41396    },
41397    setEvent: function ()
41398    {
41399
41400    },
41401    setDefaultUI: function ()
41402    {
41403        EC$('.ec-block-target-request-btn').each(function () {
41404            if (APP_BOARD_BLOCK.useBlock(APP_BOARD_BLOCK.getRequestBtnBoardNo(this)) === false) {
41405                EC$(this).remove();
41406            } else {
41407                EC$(this).hide();
41408            }
41409        });
41410        EC$('.ec-unblock-target-request-btn').each(function () {
41411            if (APP_BOARD_BLOCK.useBlock(APP_BOARD_BLOCK.getRequestBtnBoardNo(this)) === false) {
41412                EC$(this).remove();
41413            } else {
41414                EC$(this).hide();
41415            }
41416        });
41417    },
41418    useBlock : function (iBoardNo)
41419    {
41420        if (iBoardNo > 0
41421            && typeof CAFE24.BOARD['config_' + String(iBoardNo)] !== 'undefined'
41422            && CAFE24.BOARD['config_' + String(iBoardNo)].use_block === 'T') {
41423            return true;
41424        }
41425        return false;
41426    },
41427    /**
41428     * 동작 여부를 결정
41429     * @returns {boolean}
41430     */
41431    isRun : function ()
41432    {
41433        if (typeof CAFE24.BOARD === 'undefined') {
41434            return false;
41435        }
41436        var iBoardNo = 0;
41437        for (var sConfigKey in CAFE24.BOARD) {
41438            if (sConfigKey.indexOf('config_') !== -1) {
41439                iBoardNo = parseInt(sConfigKey.replace('config_', ''), 10);
41440                if (this.useBlock(iBoardNo) === true) {
41441                    return true;
41442                }
41443            }
41444        }
41445        return false;
41446    },
41447    getRequestBtnBoardNo : function (oBtn)
41448    {
41449        var aMatched = EC$(oBtn).attr('onclick').match(/APP_BOARD_BLOCK\.(setBlock|unBlock)\('(\d+)','(\d+)','(\S+)'\);/);
41450        return aMatched !== false ? parseInt(aMatched[2], 10) : 0;
41451    },
41452    setDefaultUINoneMember : function ()
41453    {
41454        EC$('.ec-block-target-request-btn').attr("style", "display:inline-block !important;");
41455        EC$('.ec-unblock-target-request-btn').hide();
41456    },
41457    setDisplayListBlock: function ()
41458    {
41459        APP_BOARD_BLOCK.setDefaultUI();
41460        EC$('.ec-block-target').each(function (iIndex, oItem) {
41461            var sBlockData = EC$(oItem).data('ec-block-data');
41462            if (typeof sBlockData == 'undefined') {
41463                return;
41464            }
41465            var sBlockType = APP_BOARD_BLOCK.findBlockList(sBlockData);
41466            if (sBlockType === false) {
41467                if (sBlockData !== APP_BOARD_BLOCK.getSelfBlockData()) {// 내 글이 아닐 때만 차단 버튼을 노출한다.
41468                    EC$(oItem).find('.ec-block-target-request-btn').attr("style", "display:inline-block !important;");
41469                }
41470                EC$(oItem).find('.ec-block-target-content').show();
41471                return;
41472            }
41473            EC$(oItem).find('.ec-unblock-target-request-btn').attr("style", "display:inline-block !important;");
41474            EC$(oItem).find('.ec-block-target-content').each(function(iSubIndex, oContentItem){
41475                var sNewDisplayStr = (sBlockType === 'NO_M_BULLETIN')? __('THIS.IS.BLOCKED.POST', 'APP.BOARD.BLOCK.JS') : __('POST.FROM.BLOCKED.AUTHOR', 'APP.BOARD.BLOCK.JS');
41476
41477                if (EC$(oContentItem).prop('tagName') !== "DIV") {
41478                    EC$(oContentItem).html(sNewDisplayStr);
41479                } else {
41480                    EC$(oContentItem).find("> :not(.ec-base-button)").remove();
41481                    EC$(oContentItem).prepend(sNewDisplayStr);
41482                }
41483                EC$(oContentItem).show();
41484            });
41485        });
41486
41487        // UI 가 변환되면 action 종료로 판단.
41488        APP_BOARD_BLOCK.bAction = false;
41489    },
41490    getSelfBlockData: function ()
41491    {
41492        if (this.aBlockList != null && typeof this.aBlockList.data !== 'undefined') {
41493            return this.aBlockList.data.block_data;
41494        }
41495        return '';
41496    },
41497    findBlockList: function (sBlockKey)
41498    {
41499        if (this.aBlockList == null || this.aBlockList.length < 1) {
41500            return false;
41501        }
41502        var aBlockKeyList = Object.keys(this.aBlockList.data.list);
41503        var iFindIndex = aBlockKeyList.indexOf(sBlockKey);
41504        if (iFindIndex === -1) {
41505            return false;
41506        }
41507        return aBlockKeyList[iFindIndex];
41508    },
41509    setBlockList: function ()
41510    {
41511        this.loadBlockListCache();
41512        if (this.aBlockList === null) {
41513            this.setBlockListAjax(this.setDisplayListBlock);
41514        } else {
41515            this.setDisplayListBlock();
41516        }
41517    },
41518    setBlockListCache: function (oStorageData)
41519    {
41520        this.aBlockList = oStorageData;
41521        // sessionStorage 지원 여부 확인
41522        if (!window.localStorage) {
41523            return false;
41524        }
41525        window.localStorage.setItem(this.STORAGE_KEY, JSON.stringify(oStorageData));
41526    },
41527    loadBlockListCache: function ()
41528    {
41529        // sessionStorage 지원 여부 확인
41530        if (!window.localStorage) {
41531            return false;
41532        }
41533        try {
41534            var sStorageData = window.localStorage.getItem(this.STORAGE_KEY);
41535            var oStorageData = JSON.parse(sStorageData);
41536
41537            // 데이터 체크
41538            if (typeof oStorageData.code === 'undefined' || typeof oStorageData.data === 'undefined') {
41539                throw 'Invalid cache data.';
41540            }
41541
41542            if (oStorageData.data.expire_time < (Date.now() / 1000)) {
41543                throw 'expired time.';
41544            }
41545
41546            if (oStorageData.data.member_id != CAPP_ASYNC_METHODS.member.getData().member_id) {
41547                throw 'Failed to match member information.';
41548            }
41549            this.aBlockList = oStorageData;
41550        } catch (e) {
41551            this.deleteBlockListCache();
41552        }
41553    },
41554    deleteBlockListCache: function ()
41555    {
41556        // sessionStorage 지원 여부 확인
41557        if (!window.localStorage) {
41558            return;
41559        }
41560        // 캐시 삭제
41561        this.aBlockList = null;
41562        window.localStorage.removeItem(this.STORAGE_KEY);
41563    },
41564    setBlockListAjax: function (oCallback)
41565    {
41566        EC$.ajax({
41567            type: 'get',
41568            dataType: 'json',
41569            url: '/exec/front/shop' + CAFE24.SDE_SHOP_NUM + '/board/blockGet',
41570            data: { },
41571            success: function(oResult) {
41572                switch (oResult.code) {
41573                    case '0000' :
41574                        APP_BOARD_BLOCK.setBlockListCache(oResult);
41575                        oCallback();
41576                        break;
41577                    case '1001' : //상품 상세페이지 비로그인 유저 버튼 노출
41578                        if (APP_BOARD_BLOCK.isRun() === false) {
41579                            APP_BOARD_BLOCK.setDefaultUI();
41580                            return ;
41581                        }
41582                        APP_BOARD_BLOCK.setDefaultUINoneMember();
41583                        break;
41584                    default :
41585                        break;
41586                }
41587            }
41588        });
41589    },
41590    setBlock: function (iBoardNo, iNo, sTargetType)
41591    {
41592        if (APP_BOARD_BLOCK.bAction) {
41593            return ;
41594        }
41595        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
41596            alert(__('YOU.NEED.SHOPPING.MALL', 'APP.BOARD.BLOCK.JS'));
41597
41598            if (EC_ROUTE.getIsEasyUrl()) { // 쉬운 주소
41599                location.replace("/member/login.html?returnUrl=" + window.location.pathname);
41600            } else {
41601                location.replace("/member/login.html?returnUrl=" + encodeURIComponent(window.location.pathname + "?board_no=" + iBoardNo + "&no=" + iNo));
41602            }
41603
41604            return ;
41605        }
41606        if (Object.keys(APP_BOARD_BLOCK.aBlockList.data.list).length >= APP_BOARD_BLOCK.iMax) {
41607            alert(__('CAN.BLOCKED.EXCEEDED', 'APP.BOARD.BLOCK.JS'));
41608            return ;
41609        }
41610        var iBoardNo = parseInt(iBoardNo, 10);
41611        var iNo = parseInt(iNo, 10);
41612        if (iNo < 1 || iBoardNo < 1) {
41613            return ;
41614        }
41615
41616        var sQuestion = '';
41617        if (sTargetType === 'NO_M_BULLETIN') {
41618            sQuestion = __('ARE.SURE.THE.POST', 'APP.BOARD.BLOCK.JS');
41619        } else {
41620            sQuestion = __('ARE.SURE.THE.AUTHOR', 'APP.BOARD.BLOCK.JS');
41621        }
41622        var bAnswer =confirm(sQuestion);
41623        if (bAnswer === false) {
41624            return ;
41625        }
41626        APP_BOARD_BLOCK.bAction = true;
41627        this.setBlockCore(iBoardNo, iNo);
41628    },
41629    setBlockCore: function (iBoardNo, iNo)
41630    {
41631        var self = APP_BOARD_BLOCK;
41632        EC$.ajax({
41633            type: 'get',
41634            dataType: 'json',
41635            url: '/exec/front/shop' + CAFE24.SDE_SHOP_NUM + '/board/blockPost',
41636            data: {
41637                'board_no': iBoardNo,
41638                'no': iNo
41639            },
41640            success: function(oResult) {
41641                switch (oResult.code) {
41642                    case '0000' :
41643                        self.deleteBlockListCache();
41644                        self.setBlockList();
41645                        self.setBlockAfterUI();
41646                        break;
41647                    default :
41648                        break;
41649                }
41650            }
41651        });
41652    },
41653    setBlockAfterUI: function ()
41654    {
41655        alert(__('AUTHOR.BLOCKED', 'APP.BOARD.BLOCK.JS'));
41656    },
41657    unBlock: function (iBoardNo, iNo, sTargetType)
41658    {
41659        if (APP_BOARD_BLOCK.bAction) {
41660            return;
41661        }
41662        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
41663            alert(__('YOU.NEED.SHOPPING.MALL', 'APP.BOARD.BLOCK.JS'));
41664            location.replace("/member/login.html?returnUrl=" + window.location.pathname);
41665            return;
41666        }
41667        var iBoardNo = parseInt(iBoardNo, 10);
41668        var iNo = parseInt(iNo, 10);
41669        if (iNo < 1 || iBoardNo < 1) {
41670            return;
41671        }
41672        var sQuestion = '';
41673        if (sTargetType === 'NO_M_BULLETIN') {
41674            sQuestion = __('ARE.SURE.POST', 'APP.BOARD.BLOCK.JS');
41675        } else {
41676            sQuestion = __('ARE.SURE.THE.AUTHOR.UNBLOCK', 'APP.BOARD.BLOCK.JS');
41677        }
41678        var bAnswer =confirm(sQuestion);
41679        if (bAnswer === false) {
41680            return;
41681        }
41682        APP_BOARD_BLOCK.bAction = true;
41683        this.unBlockCore(iBoardNo, iNo);
41684    },
41685    unBlockCore: function (iBoardNo, iNo)
41686    {
41687        var self = APP_BOARD_BLOCK;
41688        EC$.ajax({
41689            type: 'get',
41690            dataType: 'json',
41691            url: '/exec/front/shop' + CAFE24.SDE_SHOP_NUM + '/board/blockDelete',
41692            data: {
41693                'board_no': iBoardNo,
41694                'no': iNo
41695            },
41696            success: function(oResult) {
41697                switch (oResult.code) {
41698                    case '0000':
41699                        self.deleteBlockListCache();
41700                        location.reload(); // 화면을 노출시키기 위해 새로고침
41701                        break;
41702                    default:
41703                        break;
41704                }
41705            }
41706        });
41707    },
41708};
41709
41710EC$(function () {
41711    try {
41712        APP_BOARD_BLOCK.init();
41713    } catch (e) {
41714        console.log(e); // 프론트에 영향가지 않도록 처리
41715    }
41716});
41717
41718/**
41719 * 상품상세 게시판 캡챠 관리
41720 */
41721var APP_BOARD_CAPTCHA = {
41722    /**
41723     * 초기화
41724     */
41725    init: function () {
41726        if (!CAFE24 && !CAFE24.BOARD) {
41727            return;
41728        }
41729
41730        this.initCaptchaObserver(CAFE24.BOARD.captcha_config_review, 'review');
41731        this.initCaptchaObserver(CAFE24.BOARD.captcha_config_qna, 'qna');
41732    },
41733
41734    /**
41735     * 캡챠 관리
41736     * @param {object} oConfig 
41737     * @param {string} sType 
41738     */
41739    initCaptchaObserver: function (oConfig, sType) {
41740        // config가 정상적으로 설정되지 않았거나, 댓글을 사용하지 않거나, 캡챠 사용 안함 설정이면 종료
41741        if (!oConfig || oConfig.use_comment !== 'T' || oConfig.use_captcha_comment !== 'T') {
41742            return;
41743        }
41744
41745        // CAPP_ASYNC_METHODS가 정의되지 않았으면 종료
41746        if (typeof CAPP_ASYNC_METHODS === 'undefined') {
41747            return;
41748        }
41749
41750        // 비회원이나 회원 캡챠 사용 여부 확인
41751        var bShouldUseCaptcha = (CAPP_ASYNC_METHODS.IS_LOGIN === false && oConfig.use_captcha_non_member === 'T') ||
41752                               (CAPP_ASYNC_METHODS.IS_LOGIN === true && oConfig.use_captcha_member === 'T');
41753
41754        if (!bShouldUseCaptcha) {
41755            return;
41756        }
41757
41758        // MutationObserver 지원 확인
41759        if (window.MutationObserver) {
41760            this.observeWithMutation(sType);
41761        } else {
41762            // fallback: MutationObserver를 지원하지 않는 경우 interval 사용
41763            setInterval(() => this.setCaptchaVisible(sType), 500);
41764        }
41765    },
41766
41767    /**
41768     * MutationObserver 사용
41769     * @param {string} sType 
41770     */
41771    observeWithMutation: function (sType) {
41772        var observer = new MutationObserver(() => {
41773            this.setCaptchaVisible(sType);
41774        });
41775
41776        var targetNode = document.querySelector('.xans-product-' + sType);
41777        if (targetNode) {
41778            observer.observe(targetNode, {
41779                childList: true,
41780                subtree: true
41781            });
41782            // 초기 상태 체크
41783            this.setCaptchaVisible(sType);
41784        }
41785    },
41786
41787    /**
41788     * 캡챠 노출 처리
41789     * @param {string} sType 
41790     */
41791    setCaptchaVisible: function (sType) {
41792        var aCaptchaElements = document.querySelectorAll('.xans-product-' + sType + ' .captcha');
41793
41794        if (aCaptchaElements.length < 1) {
41795            return;
41796        }
41797
41798        aCaptchaElements.forEach(function (oCaptchaElement) {
41799            var oCaptchaInput = oCaptchaElement.querySelector('input[name="captcha"]');
41800            if (oCaptchaInput) {
41801                // validation 속성 추가
41802                oCaptchaInput.setAttribute('fw-filter', 'isFill');
41803                // 노출 처리
41804                oCaptchaElement.classList.remove('displaynone');
41805            }
41806        });
41807    }
41808};
41809
41810window.addEventListener('load', function() {
41811    APP_BOARD_CAPTCHA.init();
41812});
41813
41814/**
41815 * 엘리먼트 종류별 값 가져오기 form 에 의한 동일한 name 값 구별
41816 *
41817 * - 오브젝트를 받아서 사용할 수 있게함.
41818 *
41819 * @param String id
41820 * @return
41821 * @author 박난하 <[email protected]>, 백충덕 <[email protected]>, 이재욱 <[email protected]>
41822 */
41823AuthSSLManager.getValue = function(id) {
41824    //id 가 string인 경우
41825    if (typeof id === 'string') {
41826        var divide, o, type;
41827
41828        divide = id.split('::');
41829        if (divide.length == 1) {
41830            o = document.getElementsByName(id);
41831        } else {
41832            var frm = divide[0], id = divide[1];
41833
41834            // radio, checkbox
41835            if (EC$('#'+ EC$.escapeSelector(id)).length==0) {
41836                val = this.checkbox({'name': id, 'mode': 'val'});
41837                return val;
41838            }
41839            o = document.forms[frm][id];
41840        }
41841
41842        if (o == null || o == undefined || o.value == null || o.value == undefined) {
41843            o = document.getElementsByName(id);
41844            // 전체 html 에선 id 값이 있지만 form 밖에 있을수 있으므로 조건추가 (ECHOSTING-265537)
41845            val = (o[0] == undefined) ? '' : o[0].value;
41846        } else {
41847            val = o.value;
41848        }
41849
41850        return val;
41851
41852    } else if (typeof id === 'object') {
41853        //id가 object인 경우
41854
41855        //오직 하나의 오브젝트에 대해서만 처리
41856        if (EC$(id).length == 1) {
41857            return EC$(id).val();
41858        } else {
41859            return '';
41860        }
41861
41862    } else {
41863        // id가 string 또는 object가 아닐 경우 빈 값 리턴
41864        return '';
41865    }
41866};
41867
41868/**
41869 * 엘리먼트 종류별 값 가져오기 form 에 의한 동일한 name 값 구별
41870 * @param String id
41871 * @return
41872 * @author 박난하 <[email protected]>, 백충덕 <[email protected]>
41873 */
41874AuthSSLManager.getValuePay = function(id) {
41875    var divide, o, type;
41876
41877    // id가 string이 아닐 경우 빈 값 리턴
41878    if (typeof id !== 'string') return '';
41879
41880    divide = id.split('::');
41881    var frm = divide[0], id = divide[1];
41882
41883    // radio, checkbox
41884    if (EC$('#'+id).length==0) {
41885        val = this.checkbox({'name': id, 'mode': 'val'});
41886        return val;
41887    }
41888
41889    o = document.forms[frm][id];
41890
41891    if (o == null || o == undefined || o.value == null || o.value == undefined) {
41892        o = document.getElementsByName(id);
41893        val = o[0].value;
41894    } else {
41895        val = o.value;
41896    }
41897
41898    return val;
41899};
41900
41901/**
41902 * 암호화 param 데이터 세팅
41903 * @param array param 암호화 관련
41904 * @return string p 암호화 param
41905 * @author 박난하 <[email protected]>
41906 * */
41907AuthSSLManager.setParam = function(param) {
41908    var p = [];
41909        if (param['auth_mode'] == 'encrypt1.9') {
41910            p.push('auth_mode=encrypt');
41911        } else {
41912            p.push('auth_mode=' + param['auth_mode']);
41913        }
41914        p.push('auth_callbackName=' + param['auth_callbackName']);
41915    switch (param['auth_mode']) {
41916        case 'encrypt1.9':
41917            var aEle = param['aEleId'], o, p2 = {}, v;
41918            var divide = '';
41919            var id = '';
41920            for (var i in aEle) {
41921                if (aEle.hasOwnProperty(i) == false) continue;
41922                v = this.getValuePay(aEle[i]);
41923
41924                if (v == -1) continue;
41925
41926                divide = aEle[i].split('::');
41927                id = divide[1];
41928
41929                p2[id] = this.getValuePay(aEle[i]);
41930            }
41931            p.push('auth_string=' + encodeURIComponent(__JSON.stringify(p2)));
41932            break;
41933        case 'encrypt':
41934            var aEle = param['aEleId'], o, p2 = {}, v;
41935            for (var i in aEle) {
41936                if (aEle.hasOwnProperty(i) == false) continue;
41937                v = this.getValue(aEle[i]);
41938
41939                if (v == -1) continue;
41940
41941                //암호화 대상이 오브젝트인경우 id값이 key가 된다.
41942                if (typeof aEle[i] === 'object') {
41943                    p2[EC$(aEle[i]).attr('id')] = this.getValue(aEle[i]);
41944                } else {
41945                    p2[aEle[i]] = this.getValue(aEle[i]);
41946                }
41947            }
41948            p.push('auth_string=' + encodeURIComponent(__JSON.stringify(p2)));
41949            break;
41950        case 'decrypt':
41951        case 'decryptClient':
41952            p.push('auth_string=' + encodeURIComponent(param['auth_string']));
41953            break;
41954    }
41955
41956    return p;
41957};
41958
41959
41960/**
41961 * radio, checkbox 값 가져오기
41962 * @param object options 옵션
41963 * @return string radio 또는 checkbox value 반환
41964 * @author 박난하 <[email protected]>, 백충덕 <[email protected]>
41965 * */
41966AuthSSLManager.checkbox = function(options)
41967{
41968    var o = document.getElementsByName(options.name);
41969    if (o == null) return;
41970
41971    // element 없음
41972    if (o.length<1) {
41973        var chk = false;
41974        var o = document.getElementById(options.name);
41975        if (o == null) return '';
41976        if (o.checked == true) var chk = true;
41977        return chk == true ? o.value : '';
41978    }
41979
41980    var bChecked = false;
41981    var aChk = new Array();
41982    for (var i = 0; i < o.length; i++) {
41983        var el = EC$('#'+o[i].id);
41984
41985        if (el.prop('checked') == true) {
41986            // RADIO
41987            if (el.prop('type') == 'radio') return el.val();
41988            // CHECKBOX
41989            else if (el.prop('type') == 'checkbox') {
41990                aChk.push(el.val());
41991                bChecked = true;
41992            }
41993        }
41994    }
41995
41996    if (options.mode == 'val') {
41997        if (bChecked == false) return '';
41998
41999        if (aChk.length>0) return aChk.join('|');
42000    }
42001};
42002
42003
42004/**
42005 * AuthSSL을 통해 submit을 할 폼 클래스
42006 * @author 백충덕 <[email protected]>
42007 * @since 2011. 6. 16
42008 * */
42009var FormSSL = function()
42010{
42011    /**
42012     * 폼 아이디
42013     * @var string
42014     * */
42015    this.sFormId = null;
42016    /**
42017     * 암호화 시킬 엘리먼트 id 배열
42018     * @var array
42019     * */
42020    this.aEleId = null;
42021
42022    /**
42023     * onsubmit bind
42024     * @param string sFormId bind 할 폼 아이디
42025     * @param array  aEleId  암호화할 엘리먼트 id 배열
42026     * */
42027    this.bind = function(sFormId, aEleId)
42028    {
42029        var self = this;
42030
42031        this.sFormId = sFormId;
42032        this.aEleId = aEleId;
42033
42034        var oForm = EC$('#'+sFormId);
42035        oForm.off('submit');
42036        oForm.on('submit', function() {
42037            AuthSSL.Submit(self.sFormId, self.aEleId);
42038
42039            return false;
42040        });
42041    };
42042
42043    /**
42044     * AuthSSL submit 실행
42045     * */
42046    this.submit = function()
42047    {
42048        AuthSSL.Submit(this.sFormId, this.aEleId);
42049        return false;
42050    };
42051};
42052
42053
42054/**
42055 * AuthSSL 폼 객체 리스트 관리
42056 * @author 백충덕 <[email protected]>
42057 * @since 2011. 6. 16
42058 * */
42059var FormSSLContainer = {
42060    /**
42061     * 폼 객체 리스트
42062     * @var object
42063     * */
42064    aFormSSL: {},
42065
42066    /**
42067     * 폼 객체 생성 및 리스트에 추가
42068     * @param string sFormId 객체로 생성할 폼 아이디
42069     * @param array  aEleId  암호화 할 엘리먼트 아이디
42070     * */
42071    create: function (sFormId, aEleId)
42072    {
42073        if (this.formExists(sFormId)==false) {
42074            var oFormSSL = new FormSSL();
42075            oFormSSL.bind(sFormId, aEleId);
42076            this.aFormSSL[sFormId] = oFormSSL;
42077        }
42078    },
42079
42080    /**
42081     * 폼 아이디로 AuthSSL submit 실행
42082     * @param string sFormId 폼 아이디
42083     * */
42084    submit: function (sFormId)
42085    {
42086        if (this.formExists(sFormId)==false) return;
42087
42088        this.aFormSSL[sFormId].submit();
42089    },
42090
42091    /**
42092     * 폼 아이디로 FormSSLContainer에 해당 폼이 있는지 체크
42093     * @param string sFormId 체크할 폼 아이디
42094     * @return bool 폼이 있으면 true, 없으면 false
42095     * */
42096    formExists: function (sFormId)
42097    {
42098        if (!this.aFormSSL[sFormId]) return false;
42099        else return true;
42100    }
42101};
42102
42103
42104/**
42105 * AuthSSL 클래스
42106 * @author 백충덕 <[email protected]>
42107 * @since 2011. 6. 16
42108 * */
42109var AuthSSL = {
42110    /**
42111     * SSL on/off
42112     * @var bool
42113     * */
42114    bIsSsl: true,
42115    /**
42116     * 폼 아이디
42117     * @var string
42118     * */
42119    sFormId: null,
42120    /**
42121     * 엘리먼트 아이디
42122     * @var array
42123     * */
42124    aEleId: null,
42125    /**
42126     * 폼 객체 (jQuery)
42127     * @var object
42128     * */
42129    oFormSubmit: null,
42130    /**
42131     * 암호화 된 문자열이 저장될 input hidden id
42132     * @var string
42133     * */
42134    sEncryptId: 'encrypted_str',
42135    /**
42136     * callback 함수 이름
42137     * @var string
42138     * */
42139    sCallbackName: 'AuthSSL.encryptSubmit_Complete',
42140
42141    /**
42142     * 멤버변수 세팅
42143     * @param string sFormId 폼 아이디
42144     * @param array  aEleId  엘리먼트 아이디
42145     * */
42146    init: function(sFormId, aEleId)
42147    {
42148        this.sFormId = sFormId;
42149        this.aEleId = aEleId;
42150        this.oFormSubmit = EC$('#' + sFormId);
42151    },
42152
42153    /**
42154     * AuthSSLManager 존재여부 체크
42155     * @return bool 존재하면 true, 아니면 false 반환
42156     * */
42157    checkAvailable: function()
42158    {
42159        // AuthSSLManager가 없음
42160        if (typeof AuthSSLManager!=='object') {
42161            alert('[Error]\nneed SSL Manager');
42162            return false;
42163        }
42164
42165        return true;
42166    },
42167
42168    /**
42169     * onsubmit bind
42170     * @param string sFormId 폼 아이디
42171     * @param array  aEleId  암호화하고자 하는 필드의 id
42172     * */
42173    Bind: function(sFormId, aEleId)
42174    {
42175        FormSSLContainer.create(sFormId, aEleId);
42176    },
42177
42178    /**
42179     * 암호화 요청 함수 - submit
42180     * @param string sFormId 폼 아이디
42181     * @param array  aEleId  엘리먼트 아이디
42182     * */
42183    Submit: function(sFormId, aEleId) {
42184        // AuthSSLManager 존재여부 체크
42185        if (this.checkAvailable()==false) return false;
42186
42187        // 폼 아이디, 엘리먼트 아이디 세팅
42188        this.init(sFormId, aEleId);
42189
42190        // 암호화 요청이 아닐 경우 그냥 submit
42191        if (this.bIsSsl == false) {
42192            this.disabledSslSubmit();
42193            return false;
42194        }
42195
42196        // 암호화 된 값을 받을 input_hidden 생성
42197        var oInput = document.createElement('input');
42198        oInput.type = 'hidden';
42199        oInput.name = oInput.id = this.sEncryptId;
42200        this.oFormSubmit.append(oInput);
42201
42202        // 암호화 요청
42203        this.encrypt(this.aEleId, this.sCallbackName);
42204    },
42205
42206    /**
42207     * 암호화 요청
42208     * @param array aEleId 암호화할 엘리먼트 id
42209     * @param string sCallbackName 콜백함수 이름
42210     * */
42211    encrypt: function(aEleId, sCallbackName) {
42212        AuthSSLManager.weave({
42213            'auth_mode': 'encrypt',
42214            'aEleId': aEleId,
42215            'auth_callbackName': sCallbackName
42216        });
42217    },
42218
42219    /**
42220     * 암호화 처리결과 callback 함수
42221     * @param string sOutput 암호화 된 처리결과
42222     * */
42223    encryptSubmit_Complete: function(sOutput) {
42224        // Error
42225        if (AuthSSLManager.isError(sOutput) == true) {
42226            alert('[Error]\n'+sOutput);
42227            return;
42228        }
42229
42230        // 암호화 처리된 엘리먼트의 value 제거
42231        this.delInputValue();
42232
42233        // input_hidden에 암호화 된 결과값 대입
42234        this.oFormSubmit.find('[id="'+this.sEncryptId+'"]').val(sOutput);
42235
42236        // Form Submit
42237        this.oFormSubmit.off('submit');
42238
42239        this.delInputValue();
42240
42241        this.oFormSubmit.submit();
42242    },
42243
42244    /**
42245     * INPUT.RADIO, INPUT.CHECKBOX의 value 지움
42246     * @param string sName 값을 지우고자 하는 element의 name
42247     * */
42248    delRadioValue: function(sName) {
42249        var oEle = document.getElementsByName(sName);
42250        if (oEle.length>0) {
42251
42252            for (var i = 0; i < oEle.length; i++) {
42253
42254                oEle[i].value = '';
42255
42256                if (oEle[i].defaultValue) {
42257
42258                    oEle[i].defaultValue = '';
42259                }
42260            }
42261        }
42262    },
42263
42264    /**
42265     * 암호화 될 폼 요소들의 값을 지움
42266     */
42267    delInputValue: function() {
42268        for (var i=0; i<this.aEleId.length; i++) {
42269
42270            // 값을 지울 element의 id 가져오기
42271            var sID = AuthSSL.getEleId(this.aEleId[i]);
42272            var oEle = this.oFormSubmit.find('[id="' + sID + '"]');
42273
42274            // id를 표기하지 않고 name만 표기한 radio, checkbox
42275            if (oEle.length == 0) {
42276
42277                this.delRadioValue(sID);
42278                continue;
42279            }
42280
42281            // SELECT
42282            if (oEle.is('SELECT')) {
42283
42284                var oSelect = oEle.children('option:selected');
42285                oSelect.val('');
42286                oSelect.prop('value', '');
42287                oSelect.prop('defaultValue', '');
42288            }
42289            // INPUT.TEXT, INPUT.PASSWORD, TEXTAREA
42290            else {
42291
42292                oEle.val('');
42293                oEle.prop('value', '');
42294                oEle.prop('defaultValue', '');
42295            }
42296        } // for
42297    },
42298
42299    /**
42300     * 넘겨받은 id에서 폼 아이디와 구분자를 제거하여 가져오기
42301     * @param string sOrgID 원본 폼 아이디
42302     * @return string 폼 아이디와 구분자가 제거된 아이디 반환
42303     * */
42304    getEleId: function(sOrgID)
42305    {
42306        var sID = sOrgID;
42307        if (/::/.test(sID)==true) {
42308            var aTmp = sID.split('::');
42309            sID = aTmp[1];
42310        }
42311
42312        return sID;
42313    },
42314
42315    /**
42316     * bIsSsl이 false 일때 실행
42317     */
42318    disabledSslSubmit: function() {
42319        this.oFormSubmit.off('submit');
42320        this.oFormSubmit.submit();
42321    }
42322};
42323
42324
42325// validator submit hook
42326EC$(function() {
42327    if (typeof FwValidator === 'undefined') return;
42328
42329    FwValidator.Handler.setBeforeSubmit(function(elmForm) {
42330        // AuthSSL 사용폼
42331        if (FormSSLContainer.formExists(elmForm.attr('id'))==true) {
42332            if (!FormSSLContainer) return true;
42333
42334            FormSSLContainer.submit(elmForm.attr('id'));
42335            return false;
42336        }
42337
42338        // AuthSSL 사용폼이 아닐 경우 그냥 submit
42339        return true;
42340    });
42341});
42342
42343(function(window) {
42344    window.htmlentities = {
42345        /**
42346         * Converts a string to its html characters completely.
42347         *
42348         * @param {String} str String with unescaped HTML characters
42349         **/
42350        encode: function(str) {
42351            var buf = [];
42352
42353            for (var i=str.length-1; i>=0; i--) {
42354                buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
42355            }
42356
42357            return buf.join('');
42358        },
42359        /**
42360         * Converts an html characterSet into its original character.
42361         *
42362         * @param {String} str htmlSet entities
42363         **/
42364        decode: function(str) {
42365            return str.replace(/&#(\d+);/g, function(match, dec) {
42366                return String.fromCharCode(dec);
42367            });
42368        }
42369    };
42370})(window);
42371
42372CAFE24.CRYPTOKEY = (function () {
42373    const algorithm = {
42374        name: "AES-CBC",
42375        length: 256
42376    };
42377
42378    const DB_NAME = "d1";
42379    const DB_VERSION = 1;
42380    const STORE_NAME = "s1";
42381    const STORE_KEY = "eto3";
42382    const KEY_MAX_AGE_MS = 24 * 60 * 60 * 1000; // 1 day
42383
42384    function openDB() {
42385        return new Promise((resolve, reject) => {
42386            const request = window.indexedDB.open(DB_NAME, DB_VERSION);
42387
42388            request.onupgradeneeded = function (event) {
42389                const db = event.target.result;
42390                if (!db.objectStoreNames.contains(STORE_NAME)) {
42391                    db.createObjectStore(STORE_NAME);
42392                }
42393            };
42394
42395            request.onsuccess = function () {
42396                resolve(request.result);
42397            };
42398
42399            request.onerror = function () {
42400                reject(request.error);
42401            };
42402        });
42403    }
42404
42405    async function saveKey(key) {
42406        const db = await openDB();
42407
42408        return new Promise((resolve, reject) => {
42409            const tx = db.transaction(STORE_NAME, "readwrite");
42410            const store = tx.objectStore(STORE_NAME);
42411            const request = store.put({ ts: Date.now(), key: key }, STORE_KEY);
42412
42413            request.onsuccess = function () {
42414                resolve(true);
42415            };
42416
42417            request.onerror = function () {
42418                reject(request.error);
42419            };
42420
42421            tx.oncomplete = function () {
42422                db.close();
42423            };
42424        });
42425    }
42426
42427    async function loadKey() {
42428        const db = await openDB();
42429
42430        return new Promise((resolve, reject) => {
42431            const tx = db.transaction(STORE_NAME, "readonly");
42432            const store = tx.objectStore(STORE_NAME);
42433            const request = store.get(STORE_KEY);
42434
42435            request.onsuccess = async function () {
42436                const record = request.result;
42437
42438                if (!record || !record.key) {
42439                    resolve(null);
42440                    return;
42441                }
42442
42443                if (!record.ts || (Date.now() - record.ts) > KEY_MAX_AGE_MS) {
42444                    tx.oncomplete = function () {
42445                        db.close();
42446                    };
42447
42448                    try {
42449                        await CAFE24.CRYPTOKEY.deleteKey();
42450                    } catch (e) {
42451                        // ignore delete failure
42452                    }
42453
42454                    resolve(null);
42455                    return;
42456                }
42457
42458                resolve(record.key);
42459            };
42460
42461            request.onerror = function () {
42462                reject(request.error);
42463            };
42464
42465            tx.oncomplete = function () {
42466                db.close();
42467            };
42468        });
42469    }
42470
42471    async function deleteKey() {
42472        const db = await openDB();
42473
42474        return new Promise((resolve, reject) => {
42475            const tx = db.transaction(STORE_NAME, "readwrite");
42476            const store = tx.objectStore(STORE_NAME);
42477            const request = store.delete(STORE_KEY);
42478
42479            request.onsuccess = function () {
42480                resolve(true);
42481            };
42482
42483            request.onerror = function () {
42484                reject(request.error);
42485            };
42486
42487            tx.oncomplete = function () {
42488                db.close();
42489            };
42490        });
42491    }
42492
42493    async function generateKey() {
42494        const key = await window.crypto.subtle.generateKey(
42495            algorithm,
42496            false,
42497            ["encrypt", "decrypt"]
42498        );
42499        return key;
42500    }
42501
42502    async function encryptData(data, key) {
42503        const encodedData = new TextEncoder().encode(data);
42504        const iv = window.crypto.getRandomValues(new Uint8Array(16));
42505        const encryptedData = await window.crypto.subtle.encrypt(
42506            { name: "AES-CBC", iv: iv },
42507            key,
42508            encodedData
42509        );
42510        return { encryptedData, iv };
42511    }
42512
42513    async function decryptData(encryptedData, iv, key) {
42514        const decryptedData = await window.crypto.subtle.decrypt(
42515            { name: "AES-CBC", iv: iv },
42516            key,
42517            encryptedData
42518        );
42519        return new TextDecoder().decode(decryptedData);
42520    }
42521
42522    return {
42523        generateKey,
42524        saveKey,
42525        loadKey,
42526        deleteKey,
42527        encryptData,
42528        decryptData
42529    };
42530})();
42531
42532
42533CAFE24.CRYPTOKEY.encryptAndSave = async function (name, data) {
42534    let key = await CAFE24.CRYPTOKEY.loadKey();
42535
42536    if (!key) {
42537        key = await CAFE24.CRYPTOKEY.generateKey();
42538        await CAFE24.CRYPTOKEY.saveKey(key);
42539    }
42540
42541    const result = await CAFE24.CRYPTOKEY.encryptData(data, key);
42542    const encryptedData = new Uint8Array(result.encryptedData);
42543    const iv = new Uint8Array(result.iv);
42544
42545    window.sessionStorage.setItem(`eto4${name}`, JSON.stringify(Array.from(encryptedData)));
42546    window.sessionStorage.setItem(`eto5${name}`, JSON.stringify(Array.from(iv)));
42547};
42548
42549
42550CAFE24.CRYPTOKEY.decryptAndLoad = async function (name) {
42551    const loadedKey = await CAFE24.CRYPTOKEY.loadKey();
42552    if (!loadedKey) return null;
42553
42554    const encryptedData = window.sessionStorage.getItem(`eto4${name}`);
42555    const iv = window.sessionStorage.getItem(`eto5${name}`);
42556
42557    if (!encryptedData || !iv) return null;
42558
42559    const encryptedArray = new Uint8Array(JSON.parse(encryptedData));
42560    const ivArray = new Uint8Array(JSON.parse(iv));
42561
42562    return await CAFE24.CRYPTOKEY.decryptData(
42563        encryptedArray.buffer,
42564        ivArray.buffer,
42565        loadedKey
42566    );
42567};
42568/**
42569 * 프론트 로그인 상태 가드
42570 *
42571 * bfcache 복원(pageshow persisted) 또는 브라우저 HTTP 캐시 재사용으로 표시된 문서가
42572 * 현재 로그인 상태(ec_mem_level 쿠키)와 다르면 재로드하여 화면과 실제 상태를 일치시킨다.
42573 * - bfcache 경로: JS 힙이 보존되므로 렌더 시점 쿠키 스냅샷과 현재 쿠키를 비교
42574 * - HTTP 캐시 재사용 경로: JS가 재실행되어 스냅샷이 무효이므로 서버 렌더 산출물(로그인/로그아웃 모듈 DOM)과 현재 쿠키를 비교
42575 * 불일치일 때만 재로드하므로 비로그인 사용자의 bfcache 복원(뒤로가기 목록/스크롤 유지)은 그대로 동작한다.
42576 *
42577 * @package app/Manage
42578 * @since 2026. 7. 30.
42579 * @see https://jira.simplexi.com/browse/ECQAUNIT-75013
42580 * @see https://jira.simplexi.com/browse/ECHOSTING-385628
42581 * @see https://jira.simplexi.com/browse/ECHOSTING-635932
42582 * @see https://jira.simplexi.com/browse/ECHOSTING-636994
42583 * @see https://jira.simplexi.com/browse/ECHOSTING-636472
42584 * @see https://jira.simplexi.com/browse/ECHOSTING-637169
42585 * @see https://jira.simplexi.com/browse/PLUSAPP-56623
42586 */
42587(function() {
42588    // 서브프레임에서는 동작하지 않는다 - 가드의 목적은 캐시 복원된 "최상위 문서" 의 로그인 표시 불일치
42589    // 교정이고, 프레임 안의 location.reload() 는 프레임만 다시 그려 교정 효과가 없으면서 브레이크
42590    // (sessionStorage) 만 공유해 부모를 방해한다. 로그인 페이지가 same-origin 으로 품는
42591    // /protected/loginSns.html iframe 이 이 경로다 (appMemberFrontDispLogin -> agreement_layer.tpl).
42592    // pageshow 리스너 등록 전에 반환해야 프레임 문서가 재로드 판정 자체에 진입하지 않는다.
42593    // window.top !== window.self 는 참조 비교뿐이라 cross-origin 상위에서도 SecurityError 가 없다.
42594    if (window.top !== window.self) {
42595        return;
42596    }
42597
42598    // 브레이크는 "이 문서를 이미 한 번 리로드했다" 는 기억이므로 문서 단위여야 한다. 단일 키였을 때
42599    // (1) same-origin iframe 이 부모와 같은 칸을 번갈아 덮어써 브레이크가 매번 풀렸고 (무한 재로드의 직접 원인)
42600    // (2) 같은 탭에서 다른 문서로 이동하면 앞 문서의 기억이 지워져 되돌아올 때 또 reload 됐다.
42601    // (1) 은 위 서브프레임 반환으로도 막히지만 안전장치 실패였던 만큼 이중으로 건다. [ECHOSTING-636994]
42602    var sBrakeKey = 'EC_STATE_GUARD_RELOADED_' + location.pathname;
42603
42604    // 현재 로그인 여부 (로그인시 생성/로그아웃시 삭제되는 ec_mem_level 쿠키 기준)
42605    var hasAuthCookie = function() {
42606        return /(?:^|;\s*)ec_mem_level=/.test(document.cookie);
42607    };
42608
42609    // 렌더 시점 로그인 상태 스냅샷 (bfcache 복원시 힙에 보존됨)
42610    var bRenderedAuth = hasAuthCookie();
42611
42612    // 서버가 렌더한 로그인 상태
42613    // 1순위: 서버 출력값(CAFE24.FRONTEND.IS_RENDERED_LOGIN) - HTML 에 박혀 있어 캐시 재사용 문서에서도 렌더 시점 값이 유지되며 스킨 무관
42614    // 2순위: 로그인/로그아웃 모듈 DOM (서버 출력값이 없는 구버전 캐시 문서 폴백. 판별 불가시 null - 동작하지 않음)
42615    var getRenderedAuthState = function() {
42616        try {
42617            if (window.CAFE24 && CAFE24.FRONTEND && (CAFE24.FRONTEND.IS_RENDERED_LOGIN === 'T' || CAFE24.FRONTEND.IS_RENDERED_LOGIN === 'F')) {
42618                return CAFE24.FRONTEND.IS_RENDERED_LOGIN === 'T';
42619            }
42620        } catch (e) {
42621        }
42622        var oLogon = document.querySelector('.xans-layout-statelogon, .xans-layout-logon');
42623        var oLogoff = document.querySelector('.xans-layout-statelogoff');
42624        if (oLogon !== null && oLogoff === null) return true;
42625        if (oLogoff !== null && oLogon === null) return false;
42626        return null;
42627    };
42628
42629    // 일반 로드에서는 네트워크 전송이 없었고 reload 가 아닌 문서만 HTTP 캐시 재사용으로 판정한다.
42630    // 새 응답이나 reload 응답까지 교정하면 서버 상태와 쿠키가 계속 어긋나는 멀티샵 환경에서
42631    // sessionStorage 사용이 제한될 때 reload 를 멈출 수 없다. [ECHOSTING-636472, ECHOSTING-637169, PLUSAPP-56623]
42632    var isCacheReusedDocument = function() {
42633        try {
42634            if (!window.performance || typeof performance.getEntriesByType !== 'function') return false;
42635            var aEntries = performance.getEntriesByType('navigation');
42636            if (aEntries.length < 1 || typeof aEntries[0].transferSize !== 'number') return false;
42637            return aEntries[0].type !== 'reload' && aEntries[0].transferSize === 0;
42638        } catch (e) {
42639            return false;
42640        }
42641    };
42642
42643    // 동일 URL 재발동 방지 (서버 렌더와 쿠키가 계속 어긋나는 예외 상황에서 재로드 반복 차단)
42644    var reloadOnce = function() {
42645        // 디자인 편집기 미리보기(blob:)는 쿠키를 사용할 수 없어 서버 렌더 상태와 비교할 수 없다.
42646        if (location.protocol === 'blob:') {
42647            return;
42648        }
42649        try {
42650            if (window.sessionStorage) {
42651                if (sessionStorage.getItem(sBrakeKey) === location.href) return;
42652                sessionStorage.setItem(sBrakeKey, location.href);
42653            }
42654        } catch (e) {
42655        }
42656        location.reload();
42657    };
42658
42659    var clearBrake = function() {
42660        try {
42661            if (window.sessionStorage) sessionStorage.removeItem(sBrakeKey);
42662        } catch (e) {
42663        }
42664    };
42665
42666    window.addEventListener('pageshow', function(e) {
42667        // bfcache 복원: 렌더 시점 스냅샷과 현재 쿠키 비교
42668        if (e.persisted === true && hasAuthCookie() !== bRenderedAuth) {
42669            reloadOnce();
42670            return;
42671        }
42672
42673        // 일반 로드(HTTP 캐시 재사용 포함): 서버 렌더 상태와 현재 쿠키 비교
42674        var bRenderedState = getRenderedAuthState();
42675        if (bRenderedState !== null && bRenderedState !== hasAuthCookie() && isCacheReusedDocument()) {
42676            reloadOnce();
42677            return;
42678        }
42679
42680        clearBrake();
42681    });
42682})();
42683
42684/**
42685 * 비동기식 데이터
42686 */
42687var CAPP_ASYNC_METHODS = {
42688    STATUS: 'unready',
42689    DEBUG: false,
42690    IS_LOGIN: (document.cookie.match(/(?:^| |;)iscache=F/) ? true : false),
42691    EC_PATH_ROLE: EC$('meta[name="path_role"]').attr('content') || '',
42692    aDatasetList: [],
42693    $xansMyshopMain: EC$('.xans-myshop-main'),
42694    init: function()
42695    {
42696        CAPP_ASYNC_METHODS.STATUS = 'ready';
42697    	var bDebug = CAPP_ASYNC_METHODS.DEBUG;
42698
42699        var aUseModules = [];
42700        var aNoCachedModules = [];
42701
42702        EC$(CAPP_ASYNC_METHODS.aDatasetList).each(function() {
42703            var sKey = this;
42704
42705            var oTarget = CAPP_ASYNC_METHODS[sKey];
42706
42707            if (bDebug) {
42708                console.log(sKey);
42709            }
42710            var bIsUse = oTarget.isUse();
42711            if (bDebug) {
42712                console.log('   isUse() : ' + bIsUse);
42713            }
42714
42715            if (bIsUse === true) {
42716                aUseModules.push(sKey);
42717
42718                if (oTarget.restoreCache === undefined || oTarget.restoreCache() === false) {
42719                    if (bDebug) {
42720                        console.log('   restoreCache() : true');
42721                    }
42722                    aNoCachedModules.push(sKey);
42723                }
42724            }
42725        });
42726
42727        if (aNoCachedModules.length > 0) {
42728            var sEditor = '';
42729            try {
42730                if (bEditor === true) {
42731                    // 에디터에서 접근했을 경우 임의의 상품 지정
42732                    sEditor = '&PREVIEW_SDE=1';
42733                }
42734            } catch (e) { }
42735
42736            var sPathRole = '&path_role=' + CAPP_ASYNC_METHODS.EC_PATH_ROLE;
42737            var sEcMobile = '&EC_MOBILE=' + EC_MOBILE;
42738
42739            // 모듈별 추가 파라미터 수집 (getParam 훅)
42740            var sModuleParam = '';
42741            for (var i = 0; i < aNoCachedModules.length; i++) {
42742                var oMod = CAPP_ASYNC_METHODS[aNoCachedModules[i]];
42743                if (typeof oMod.getParam === 'function') {
42744                    var sParam = oMod.getParam();
42745                    if (sParam) {
42746                        sModuleParam += '&' + sParam;
42747                    }
42748                }
42749            }
42750
42751            var sUrl = '/exec/front/manage/async?module=' + aNoCachedModules.join(',') + sModuleParam + sEditor + sPathRole + sEcMobile;
42752            EC$.ajax(
42753            {
42754                url: sUrl,
42755                dataType: 'json',
42756                success: function(aData)
42757                {
42758                	CAPP_ASYNC_METHODS.setData(aData, aUseModules);
42759                }
42760            });
42761
42762        } else {
42763        	CAPP_ASYNC_METHODS.setData({}, aUseModules);
42764
42765        }
42766    },
42767    setData: function(aData, aUseModules)
42768    {
42769        aData = aData || {};
42770
42771        EC$(aUseModules).each(function() {
42772            var sKey = this;
42773
42774            var oTarget = CAPP_ASYNC_METHODS[sKey];
42775
42776            if (oTarget.setData !== undefined && aData.hasOwnProperty(sKey) === true) {
42777                oTarget.setData(aData[sKey]);
42778            }
42779
42780            if (oTarget.execute !== undefined) {
42781                oTarget.execute();
42782            }
42783        });
42784
42785        CAPP_ASYNC_METHODS.STATUS = 'complete';
42786    },
42787
42788    _getCookie: function(sCookieName)
42789    {
42790        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
42791        var aCookieValue = document.cookie.match(re);
42792        return aCookieValue ? aCookieValue[1] : null;
42793    }
42794};
42795
42796var eCache = null;
42797if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
42798    CAFE24.CRYPTOKEY.decryptAndLoad('member_' + CAFE24.SDE_SHOP_NUM).then(function(o) {
42799        eCache = o;
42800    }).catch(function(err) {
42801        // console.log(err);
42802    });
42803}
42804
42805
42806/**
42807 * 비동기식 데이터 - 회원 정보
42808 */
42809CAPP_ASYNC_METHODS.aDatasetList.push('member');
42810CAPP_ASYNC_METHODS.member = {
42811    __sEncryptedString: null,
42812    __isAdult: 'F',
42813
42814    // 회원 데이터
42815    __sMemberId: null,
42816    __sHMemberId: null,
42817    __sName: null,
42818    __sNickName: null,
42819    __sGroupName: null,
42820    __sEmail: null,
42821    __sNewsMail: null,
42822    __sPhone: null,
42823    __sCellphone: null,
42824    __sSms: null,
42825    __sBirthday: null,
42826    __sGroupNo: null,
42827    __sBoardWriteName: null,
42828    __sAdditionalInformation: null,
42829    __sAuthenticationMethod: null,
42830    __sCreatedDate: null,
42831
42832    isUse: function()
42833    {
42834        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
42835            if (EC$('.xans-layout-statelogon, .xans-layout-logon').length > 0) {
42836                return true;
42837            }
42838
42839            if (CAPP_ASYNC_METHODS.recent.isUse() === true
42840                && typeof(EC_FRONT_JS_CONFIG_SHOP) !== 'undefined'
42841                && EC_FRONT_JS_CONFIG_SHOP.adult19Warning === 'T') {
42842                return true;
42843            }
42844
42845            if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('customer', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
42846                return true;
42847            }
42848
42849        } else {
42850            // 비 로그인 상태에서 삭제처리
42851            this.removeCache();
42852        }
42853
42854        return false;
42855    },
42856
42857    restoreCache: function()
42858    {
42859        // sessionStorage 지원 여부 확인
42860        if (!window.sessionStorage) {
42861            return false;
42862        }
42863
42864        // 데이터 복구 유무
42865        var bRestored = false;
42866
42867        try {
42868            // 데이터 복구
42869            var oCache = null;
42870            if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
42871                if (eCache) {
42872                    oCache = JSON.parse(eCache);
42873                }
42874            } else if (window.location.protocol === 'http:' && (typeof CryptoJS) == 'object') {
42875                if (window.sessionStorage.getItem('member_' + CAFE24.SDE_SHOP_NUM)) {
42876                    oCache = window.sessionStorage.getItem('member_' + CAFE24.SDE_SHOP_NUM);
42877                    oCache = CryptoJS.AES.decrypt(oCache, SHOP.getMallID() + '_' + EC_SDE_SHOP_NUM).toString(CryptoJS.enc.Utf8);
42878                    oCache = JSON.parse(oCache);
42879                }
42880            }
42881
42882            // expire 체크
42883            if (oCache.exp < Date.now()) {
42884                throw 'cache has expired.';
42885            }
42886
42887            // 데이터 체크
42888            if (typeof oCache.data.member_id === 'undefined'
42889                || oCache.data.member_id === ''
42890                || typeof oCache.data.h_member_id === 'undefined'
42891                || oCache.data.h_member_id === ''
42892                || typeof oCache.data.name === 'undefined'
42893                || typeof oCache.data.nick_name === 'undefined'
42894                || typeof oCache.data.group_name === 'undefined'
42895                || typeof oCache.data.group_no === 'undefined'
42896                || typeof oCache.data.email === 'undefined'
42897                || typeof oCache.data.news_mail === 'undefined'
42898                || typeof oCache.data.phone === 'undefined'
42899                || typeof oCache.data.cellphone === 'undefined'
42900                || typeof oCache.data.sms === 'undefined'
42901                || typeof oCache.data.birthday === 'undefined'
42902                || typeof oCache.data.board_write_name === 'undefined'
42903                || typeof oCache.data.additional_information === 'undefined'
42904                || typeof oCache.data.authentication_method === 'undefined'
42905                || typeof oCache.data.created_date === 'undefined'
42906            ) {
42907                throw 'Invalid cache data.';
42908            }
42909
42910            // 데이터 복구
42911            this.__sMemberId = oCache.data.member_id;
42912            this.__sHMemberId = oCache.data.h_member_id;
42913            this.__sName = oCache.data.name;
42914            this.__sNickName = oCache.data.nick_name;
42915            this.__sGroupName = oCache.data.group_name;
42916            this.__sGroupNo = oCache.data.group_no;
42917            this.__sEmail = oCache.data.email;
42918            this.__sNewsMail = oCache.data.news_mail;
42919            this.__sPhone = oCache.data.phone;
42920            this.__sCellphone = oCache.data.cellphone;
42921            this.__sSms = oCache.data.sms;
42922            this.__sBirthday = oCache.data.birthday;
42923            this.__sBoardWriteName = oCache.data.board_write_name;
42924            this.__sAdditionalInformation = oCache.data.additional_information;
42925            this.__sAuthenticationMethod = oCache.data.authentication_method;
42926            this.__sCreatedDate = oCache.data.created_date;
42927
42928            bRestored = true;
42929        } catch (e) {
42930            // 복구 실패시 캐시 삭제
42931            this.removeCache();
42932        }
42933
42934        return bRestored;
42935    },
42936
42937    cache: function()
42938    {
42939        // sessionStorage 지원 여부 확인
42940        if (!window.sessionStorage) {
42941            return;
42942        }
42943        // 캐시
42944        var sData = JSON.stringify({exp: Date.now() + (1000 * 60 * 10),data: this.getData()})
42945
42946        if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
42947            CAFE24.CRYPTOKEY.encryptAndSave('member_' + CAFE24.SDE_SHOP_NUM, sData);
42948        } else if (window.location.protocol === 'http:' && (typeof CryptoJS) == 'object') {
42949            sData = CryptoJS.AES.encrypt(sData, SHOP.getMallID() + '_' + EC_SDE_SHOP_NUM).toString();
42950            window.sessionStorage.setItem('member_' + CAFE24.SDE_SHOP_NUM, sData);
42951        }
42952    },
42953
42954    removeCache: function()
42955    {
42956        // sessionStorage 지원 여부 확인
42957        if (!window.sessionStorage) {
42958            return;
42959        }
42960
42961        // 캐시 삭제
42962        window.sessionStorage.removeItem('encryptedData_member_' + CAFE24.SDE_SHOP_NUM);
42963        window.sessionStorage.removeItem('iv_member_' + CAFE24.SDE_SHOP_NUM);
42964        window.sessionStorage.removeItem('eto4member_' + CAFE24.SDE_SHOP_NUM);
42965        window.sessionStorage.removeItem('eto5member_' + CAFE24.SDE_SHOP_NUM);
42966        window.sessionStorage.removeItem('member_' + CAFE24.SDE_SHOP_NUM);
42967    },
42968
42969    setData: function(oData)
42970    {
42971        this.__sEncryptedString = oData.memberData;
42972        this.__isAdult = oData.memberIsAdult;
42973    },
42974
42975    execute: function()
42976    {
42977        if (this.__sMemberId === null) {
42978            if (this.__sEncryptedString.id) {
42979                this.setDataCallback(this.__sEncryptedString);
42980            } else {
42981                AuthSSLManager.weave({
42982                    'auth_mode': 'decryptClient',
42983                    'auth_string': this.__sEncryptedString,
42984                    'auth_callbackName': 'CAPP_ASYNC_METHODS.member.setDataCallback'
42985                });
42986            }
42987        } else {
42988            this.render();
42989        }
42990    },
42991
42992    setDataCallback: function(sData)
42993    {
42994        try {
42995            if (sData.id) {
42996                var oData = sData;
42997            } else {
42998                var sDecodedData = decodeURIComponent(sData);
42999                if (AuthSSLManager.isError(sDecodedData) == true) {
43000                    console.log(sDecodedData);
43001                    return;
43002                }
43003                var oData = AuthSSLManager.unserialize(sDecodedData);
43004            }
43005
43006            this.__sMemberId = oData.id || '';
43007            this.__sHMemberId = oData.h_member_id || '';
43008            this.__sName = oData.name || '';
43009            this.__sNickName = oData.nick || '';
43010            this.__sGroupName = oData.group_name || '';
43011            this.__sGroupNo = oData.group_no || '';
43012            this.__sEmail = oData.email || '';
43013            this.__sNewsMail = oData.news_mail || '';
43014            this.__sPhone = oData.phone || '';
43015            this.__sCellphone = oData.cellphone || '';
43016            this.__sSms = oData.sms || '';
43017            this.__sBirthday = oData.birthday || 'F';
43018            this.__sBoardWriteName = oData.board_write_name || '';
43019            this.__sAdditionalInformation = oData.additional_information || '';
43020            this.__sAuthenticationMethod = oData.personal_type || null;
43021            this.__sCreatedDate = oData.created_date || '';
43022
43023            // 데이터 랜더링
43024            this.render();
43025
43026            // 데이터 캐시
43027            this.cache();
43028        } catch (e) {}
43029    },
43030
43031    render: function()
43032    {
43033        // 친구초대
43034        if (EC$('.xans-myshop-asyncbenefit').length > 0) {
43035            if (EC$('#reco_url').val() && EC$('#reco_url').val().split('=')[1] == '') {
43036                EC$('#reco_url').attr({value: EC$('#reco_url').val() + this.__sMemberId});
43037            }
43038        }
43039
43040        EC$('.authssl_member_name').html(this.__sName);
43041        EC$('.xans-member-var-id').html(this.__sMemberId);
43042        EC$('.xans-member-var-h_id').html(this.__sHMemberId);
43043        EC$('.xans-member-var-name').html(this.__sName);
43044        EC$('.xans-member-var-nick').html(this.__sNickName);
43045        EC$('.xans-member-var-group_name').html(this.__sGroupName);
43046        EC$('.xans-member-var-group_no').html(this.__sGroupNo);
43047        EC$('.xans-member-var-email').html(this.__sEmail);
43048        EC$('.xans-member-var-phone').html(this.__sPhone);
43049
43050        if (EC$('.xans-board-commentwrite').length > 0 && typeof BOARD_COMMENT !== 'undefined') {
43051            BOARD_COMMENT.setCmtData();
43052        }
43053    },
43054
43055    getMemberIsAdult: function()
43056    {
43057        if (CAPP_ASYNC_METHODS.STATUS == 'unready') {
43058            CAPP_ASYNC_METHODS.init();
43059        }
43060        return this.__isAdult;
43061    },
43062
43063    getData: function()
43064    {
43065        if (CAPP_ASYNC_METHODS.STATUS == 'unready') {
43066            CAPP_ASYNC_METHODS.init();
43067        }
43068        return {
43069            member_id: this.__sMemberId,
43070            h_member_id: this.__sHMemberId,
43071            name: this.__sName,
43072            nick_name: this.__sNickName,
43073            group_name: this.__sGroupName,
43074            group_no: this.__sGroupNo,
43075            email: this.__sEmail,
43076            news_mail: this.__sNewsMail,
43077            phone: this.__sPhone,
43078            cellphone: this.__sCellphone,
43079            sms: this.__sSms,
43080            birthday: this.__sBirthday,
43081            board_write_name: this.__sBoardWriteName,
43082            additional_information: this.__sAdditionalInformation,
43083            authentication_method: this.__sAuthenticationMethod,
43084            created_date: this.__sCreatedDate
43085        };
43086    }
43087};
43088
43089/**
43090 * 비동기식 데이터 - 예치금
43091 */
43092CAPP_ASYNC_METHODS.aDatasetList.push('Ordercnt');
43093CAPP_ASYNC_METHODS.Ordercnt = {
43094    __iOrderShppiedBeforeCount: null,
43095    __iOrderShppiedStandbyCount: null,
43096    __iOrderShppiedBeginCount: null,
43097    __iOrderShppiedComplateCount: null,
43098    __iOrderShppiedCancelCount: null,
43099    __iOrderShppiedExchangeCount: null,
43100    __iOrderShppiedReturnCount: null,
43101
43102    __$target: EC$('#xans_myshop_orderstate_shppied_before_count'),
43103    __$target2: EC$('#xans_myshop_orderstate_shppied_standby_count'),
43104    __$target3: EC$('#xans_myshop_orderstate_shppied_begin_count'),
43105    __$target4: EC$('#xans_myshop_orderstate_shppied_complate_count'),
43106    __$target5: EC$('#xans_myshop_orderstate_order_cancel_count'),
43107    __$target6: EC$('#xans_myshop_orderstate_order_exchange_count'),
43108    __$target7: EC$('#xans_myshop_orderstate_order_return_count'),
43109
43110    isUse: function()
43111    {
43112        if (EC$('.xans-myshop-orderstate').length > 0) {
43113            return true; 
43114        }
43115
43116        return false;
43117    },
43118
43119    restoreCache: function()
43120    {
43121        var sCookieName = 'ordercnt_' + CAFE24.SDE_SHOP_NUM;
43122        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
43123        var aCookieValue = document.cookie.match(re);
43124        if (aCookieValue) {
43125            var aData = CAFE24.UTIL.parseJSON(decodeURIComponent(aCookieValue[1]));
43126            this.__iOrderShppiedBeforeCount = aData.shipped_before_count;
43127            this.__iOrderShppiedStandbyCount = aData.shipped_standby_count;
43128            this.__iOrderShppiedBeginCount = aData.shipped_begin_count;
43129            this.__iOrderShppiedComplateCount = aData.shipped_complate_count;
43130            this.__iOrderShppiedCancelCount = aData.order_cancel_count;
43131            this.__iOrderShppiedExchangeCount = aData.order_exchange_count;
43132            this.__iOrderShppiedReturnCount = aData.order_return_count;
43133            return true;
43134        }
43135
43136        return false;
43137    },
43138
43139    setData: function(aData)
43140    {
43141        this.__iOrderShppiedBeforeCount = aData['shipped_before_count'];
43142        this.__iOrderShppiedStandbyCount = aData['shipped_standby_count'];
43143        this.__iOrderShppiedBeginCount = aData['shipped_begin_count'];
43144        this.__iOrderShppiedComplateCount = aData['shipped_complate_count'];
43145        this.__iOrderShppiedCancelCount = aData['order_cancel_count'];
43146        this.__iOrderShppiedExchangeCount = aData['order_exchange_count'];
43147        this.__iOrderShppiedReturnCount = aData['order_return_count'];
43148    },
43149
43150    execute: function()
43151    {
43152        this.__$target.html(this.__iOrderShppiedBeforeCount);
43153        this.__$target2.html(this.__iOrderShppiedStandbyCount);
43154        this.__$target3.html(this.__iOrderShppiedBeginCount);
43155        this.__$target4.html(this.__iOrderShppiedComplateCount);
43156        this.__$target5.html(this.__iOrderShppiedCancelCount);
43157        this.__$target6.html(this.__iOrderShppiedExchangeCount);
43158        this.__$target7.html(this.__iOrderShppiedReturnCount);
43159    },
43160
43161    getData: function()
43162    {
43163        return {
43164            shipped_before_count: this.__iOrderShppiedBeforeCount,
43165            shipped_standby_count: this.__iOrderShppiedStandbyCount,
43166            shipped_begin_count: this.__iOrderShppiedBeginCount,
43167            shipped_complate_count: this.__iOrderShppiedComplateCount,
43168            order_cancel_count: this.__iOrderShppiedCancelCount,
43169            order_exchange_count: this.__iOrderShppiedExchangeCount,
43170            order_return_count: this.__iOrderShppiedReturnCount
43171        };
43172    }
43173};
43174
43175/**
43176 * 비동기식 데이터 - 장바구니 갯수
43177 */
43178CAPP_ASYNC_METHODS.aDatasetList.push('Basketcnt');
43179CAPP_ASYNC_METHODS.Basketcnt = {
43180    __iBasketCount: null,
43181
43182    __$target: EC$('.xans-layout-orderbasketcount span a'),
43183    __$target2: EC$('#xans_myshop_basket_cnt'),
43184    __$target3: CAPP_ASYNC_METHODS.$xansMyshopMain.find('.xans_myshop_main_basket_cnt'),
43185    __$target4: EC$('.EC-Layout-Basket-count'),
43186
43187    isUse: function()
43188    {
43189        if (this.__$target.length > 0) {
43190            return true;
43191        }
43192        if (this.__$target2.length > 0) {
43193            return true;
43194        }
43195        if (this.__$target3.length > 0) {
43196            return true;
43197        }
43198        if (this.__$target4.length > 0) {
43199            return true;
43200        }
43201
43202        if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('personal', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43203            return true;
43204        }
43205
43206        return false;
43207    },
43208
43209    restoreCache: function()
43210    {
43211        var sCookieName = 'basketcount_' + CAFE24.SDE_SHOP_NUM;
43212
43213        // 쿠키명에 ch_ref 파라미터 추가
43214        if (typeof CAFE24 !== 'undefined' && CAFE24.getChRefData && CAFE24.getChRefData()) {
43215            sCookieName += '_' + CAFE24.getChRefData();
43216        }
43217
43218        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
43219        var aCookieValue = document.cookie.match(re);
43220        if (aCookieValue) {
43221            this.__iBasketCount = parseInt(aCookieValue[1], 10);
43222            return true;
43223        }
43224        
43225        return false;
43226    },
43227
43228    setData: function(sData)
43229    {
43230        this.__iBasketCount = Number(sData);
43231    },
43232
43233    execute: function()
43234    {
43235        this.__$target.html(this.__iBasketCount);
43236
43237        if (SHOP.getLanguage() === 'ko_KR') {
43238            this.__$target2.html(this.__iBasketCount + '개');
43239        } else {
43240            this.__$target2.html(this.__iBasketCount);
43241        }
43242
43243        this.__$target3.html(this.__iBasketCount);
43244        
43245        this.__$target4.html(this.__iBasketCount);
43246        
43247        if (this.__iBasketCount > 0 && this.__$target4.length > 0) {
43248            var $oCountDisplay = EC$('.EC-Layout_Basket-count-display');
43249
43250            if ($oCountDisplay.length > 0) {
43251                $oCountDisplay.removeClass('displaynone');
43252            }
43253        }
43254    },
43255
43256    getData: function()
43257    {
43258        return {
43259            count: this.__iBasketCount
43260        };
43261    }
43262};
43263
43264/**
43265 * 비동기식 데이터 - 장바구니 금액
43266 */
43267CAPP_ASYNC_METHODS.aDatasetList.push('Basketprice');
43268CAPP_ASYNC_METHODS.Basketprice = {
43269    __sBasketPrice: null,
43270
43271    __$target: EC$('#xans_myshop_basket_price'),
43272
43273    isUse: function()
43274    {
43275        if (this.__$target.length > 0) {
43276            return true;
43277        }
43278
43279        if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('personal', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43280            return true;
43281        }
43282
43283        return false;
43284    },
43285
43286    restoreCache: function()
43287    {
43288        var sCookieName = 'basketprice_' + CAFE24.SDE_SHOP_NUM;
43289
43290        // 쿠키명에 ch_ref 파라미터 추가
43291        if (typeof CAFE24 !== 'undefined' && CAFE24.getChRefData && CAFE24.getChRefData()) {
43292            sCookieName += CAFE24.getChRefData();
43293        }
43294
43295        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
43296        var aCookieValue = document.cookie.match(re);
43297        if (aCookieValue) {
43298            this.__sBasketPrice = decodeURIComponent((aCookieValue[1]+ '').replace(/\+/g, '%20'));
43299            return true;
43300        }
43301        
43302        return false;
43303    },
43304
43305    setData: function(sData)
43306    {
43307        this.__sBasketPrice = sData;
43308    },
43309
43310    execute: function()
43311    {
43312        // ECHOSTING-610183: presentment 화폐 변환
43313        var sPrice = this.__sBasketPrice;
43314        var oCurrInfo = CAFE24.SHOP_CURRENCY_INFO ? CAFE24.SHOP_CURRENCY_INFO[CAFE24.SDE_SHOP_NUM] : null;
43315        if (oCurrInfo && oCurrInfo.bPresentmentEnabled && oCurrInfo.aPresentmentCurrencyInfo) {
43316            var fRaw = parseFloat(CAFE24.SHOP_PRICE_FORMAT.detachFormat(htmlentities.decode((sPrice || '0') + '')));
43317            if (!isNaN(fRaw)) {
43318                sPrice = CAFE24.SHOP_PRICE_FORMAT.toShopPricePresentment(fRaw);
43319            }
43320        }
43321        this.__$target.html(sPrice);
43322    },
43323
43324    getData: function()
43325    {
43326        // 데이터 없는경우 0
43327        var sBasketPrice = (this.__sBasketPrice || 0) + '';
43328
43329        return {
43330            basket_price: parseFloat(CAFE24.SHOP_PRICE_FORMAT.detachFormat(htmlentities.decode(sBasketPrice))).toFixed(2)
43331        };
43332    }
43333};
43334
43335/*
43336 * 비동기식 데이터 - 장바구니 상품리스트
43337 */
43338CAPP_ASYNC_METHODS.aDatasetList.push('BasketProduct');
43339CAPP_ASYNC_METHODS.BasketProduct = {
43340
43341    STORAGE_KEY: 'BasketProduct_' + CAFE24.SDE_SHOP_NUM,
43342
43343    __aData: null,
43344
43345    __$target: EC$('.xans-layout-orderbasketcount span a'),
43346    __$target2: EC$('#xans_myshop_basket_cnt'),
43347    __$target3: CAPP_ASYNC_METHODS.$xansMyshopMain.find('.xans_myshop_main_basket_cnt'),
43348    __$target4: EC$('.EC-Layout-Basket-count'),
43349
43350    isUse: function()
43351    {
43352        if (this.__$target.length > 0) {
43353            return true;
43354        }
43355        if (this.__$target2.length > 0) {
43356            return true;
43357        }
43358        if (this.__$target3.length > 0) {
43359            return true;
43360        }
43361        if (this.__$target4.length > 0) {
43362            return true;
43363        }
43364
43365        if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('personal', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43366            return true;
43367        }
43368    },
43369
43370    restoreCache: function()
43371    {
43372        // sessionStorage 지원 여부 확인
43373        if (!window.sessionStorage) {
43374            return false;
43375        }
43376
43377        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
43378        if (sSessionStorageData === null) {
43379            return false;
43380        }
43381
43382        try {
43383            this.__aData = [];
43384            var aStorageData = JSON.parse(sSessionStorageData);
43385
43386            for (var iKey in aStorageData) {
43387                this.__aData.push(aStorageData[iKey]);
43388            }
43389
43390            return true;
43391        } catch (e) {
43392
43393            // 복구 실패시 캐시 삭제
43394            this.removeCache();
43395
43396            return false;
43397        }
43398    },
43399
43400    removeCache: function()
43401    {
43402        // sessionStorage 지원 여부 확인
43403        if (!window.sessionStorage) {
43404            return;
43405        }
43406        // 캐시 삭제
43407        window.sessionStorage.removeItem(this.STORAGE_KEY);
43408    },
43409
43410    setData: function(oData)
43411    {
43412        this.__aData = oData;
43413
43414        // sessionStorage 지원 여부 확인
43415        if (!window.sessionStorage) {
43416            return;
43417        }
43418
43419        try {
43420            sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.getData()));
43421        } catch (error) {
43422        }
43423    },
43424
43425    execute: function()
43426    {
43427
43428    },
43429
43430    getData: function()
43431    {
43432        var aStorageData = this.__aData;
43433        var aResult = [];
43434        return new Promise(function (resolve, reject) {
43435
43436            if (aStorageData != null && aStorageData.length > 1) {
43437                var oNewStorageData = [];
43438
43439                for (var iKey in aStorageData) {
43440                    oNewStorageData.push(aStorageData[iKey]);
43441                }
43442
43443                aResult = oNewStorageData;
43444                resolve(aResult);
43445            } else {
43446                var sUrl = '/exec/front/manage/async?module=BasketProduct';
43447                //랜딩결제 : ch_ref 붙여주기
43448                sUrl = CAFE24.attachChRef(sUrl);
43449                EC$.ajax({
43450                    url: sUrl,
43451                    success: function (aData) {
43452                        aResult = aData.BasketProduct;
43453                        resolve(aResult);
43454                    }
43455                });
43456            }
43457
43458        });
43459    },
43460
43461    setAsyncData: function (aPostData) {
43462        return new Promise(function (resolve, reject) {
43463            EC$.post('/exec/front/order/basket/', aPostData, function (data) {
43464                resolve(data);
43465            }).catch(function (data) {
43466                reject(data);
43467            });
43468        });
43469    },
43470    deleteAllAsyncData: function (basket_shipping_type) {
43471        return new Promise(function (resolve, reject) {
43472            EC$.post('/exec/front/order/basket/', {command: 'delete', delvtype: basket_shipping_type}, function(data) {
43473                resolve(data);
43474            }, 'json').catch(function (data) {
43475                reject(data);
43476            });
43477        });
43478    },
43479
43480    deleteCartItems: function (basket_shipping_type, product_list) {
43481        var aDeleteProducts = [];
43482        var idx = 0;
43483        if (product_list.length > 0) {
43484            for (var iKey in product_list) {
43485                aDeleteProducts[idx] = product_list[iKey].product_no + ':' + product_list[iKey].option_id + ':F:' + product_list[iKey].basket_product_no + ':null:'+basket_shipping_type;
43486                idx ++;
43487            }
43488        }
43489
43490        var sDeleteProducts = aDeleteProducts.join();
43491        return new Promise(function (resolve, reject) {
43492            EC$.post('/exec/front/order/basket/', {command: 'select_delete', checked_product:sDeleteProducts, calls:'CAFE24_SDK'}, function(data) {
43493                CAPP_ASYNC_METHODS.BasketProduct.setData();
43494                resolve(data.aResultDeleteCartItems);
43495            }, 'json').catch(function (data) {
43496                reject(data);
43497            });
43498        });
43499    }
43500};
43501
43502/**
43503 * 비동기식 데이터 - 쿠폰 갯수
43504 */
43505CAPP_ASYNC_METHODS.aDatasetList.push('Couponcnt');
43506CAPP_ASYNC_METHODS.Couponcnt = {
43507    __iCouponCount: null,
43508
43509    __$target: EC$('.xans-layout-myshopcouponcount'),
43510    __$target2: EC$('#xans_myshop_coupon_cnt'),
43511    __$target3: CAPP_ASYNC_METHODS.$xansMyshopMain.find('.xans_myshop_main_coupon_cnt'),
43512    __$target4: EC$('#xans_myshop_bankbook_coupon_cnt'),
43513
43514    isUse: function()
43515    {
43516        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
43517            if (this.__$target.length > 0) {
43518                return true;
43519            }
43520
43521            if (this.__$target2.length > 0) {
43522                return true;
43523            }
43524
43525            if (this.__$target3.length > 0) {
43526                return true;
43527            }
43528
43529            if (this.__$target4.length > 0) {
43530                return true;
43531            }
43532
43533            if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('promotion', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43534                return true;
43535            }
43536        }
43537
43538        return false;
43539    },
43540    
43541    restoreCache: function()
43542    {
43543        var sCookieName = 'couponcount_' + CAFE24.SDE_SHOP_NUM;
43544        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
43545        var aCookieValue = document.cookie.match(re);
43546        if (aCookieValue) {
43547            this.__iCouponCount = parseInt(aCookieValue[1], 10);
43548            return true;
43549        }
43550        
43551        return false;
43552    },
43553    setData: function(sData)
43554    {
43555        this.__iCouponCount = Number(sData);
43556    },
43557
43558    execute: function()
43559    {
43560        this.__$target.html(this.__iCouponCount);
43561
43562        if (SHOP.getLanguage() === 'ko_KR') {
43563            this.__$target2.html(this.__iCouponCount + '개');
43564        } else {
43565            this.__$target2.html(this.__iCouponCount);
43566        }
43567
43568        this.__$target3.html(this.__iCouponCount);
43569        this.__$target4.html(this.__iCouponCount);
43570    },
43571
43572    getData: function()
43573    {
43574        return {
43575            count: this.__iCouponCount
43576        };
43577    }
43578};
43579
43580/**
43581 * 비동기식 데이터 - 적립금
43582 */
43583CAPP_ASYNC_METHODS.aDatasetList.push('Mileage');
43584CAPP_ASYNC_METHODS.Mileage = {
43585    __sAvailMileage: null,
43586    __sUsedMileage: null,
43587    __sTotalMileage: null,
43588    __sUnavailMileage: null,
43589    __sReturnedMileage: null,
43590
43591    __$target: EC$('#xans_myshop_mileage'),
43592    __$target2: EC$('#xans_myshop_bankbook_avail_mileage, #xans_myshop_summary_avail_mileage'),
43593    __$target3: EC$('#xans_myshop_bankbook_used_mileage, #xans_myshop_summary_used_mileage'),
43594    __$target4: EC$('#xans_myshop_bankbook_total_mileage, #xans_myshop_summary_total_mileage'),
43595    __$target5: EC$('#xans_myshop_summary_unavail_mileage'),
43596    __$target6: EC$('#xans_myshop_summary_returned_mileage'),
43597    __$target7: EC$('#xans_myshop_avail_mileage'),
43598
43599    isUse: function()
43600    {
43601        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
43602            if (this.__$target.length > 0) {
43603                return true;
43604            }
43605
43606            if (this.__$target2.length > 0) {
43607                return true;
43608            }
43609
43610            if (this.__$target3.length > 0) {
43611                return true;
43612            }
43613
43614            if (this.__$target4.length > 0) {
43615                return true;
43616            }
43617
43618            if (this.__$target5.length > 0) {
43619                return true;
43620            }
43621
43622            if (this.__$target6.length > 0) {
43623                return true;
43624            }
43625
43626            if (this.__$target7.length > 0) {
43627                return true;
43628            }
43629
43630            if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('customer', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43631                return true;
43632            }
43633        }
43634
43635        return false;
43636    },
43637
43638    restoreCache: function()
43639    {
43640        // 특정 경로 룰의 경우 복구 취소
43641        if (PathRoleValidator.isInvalidPathRole()) {
43642            return false;
43643        }
43644
43645        // 쿠키로부터 데이터 획득
43646        var sAvailMileage = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_avail_mileage_' + CAFE24.SDE_SHOP_NUM);
43647        var sReturnedMileage = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_returned_mileage_' + CAFE24.SDE_SHOP_NUM);
43648        var sUnavailMileage = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_unavail_mileage_' + CAFE24.SDE_SHOP_NUM);
43649        var sUsedMileage = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_used_mileage_' + CAFE24.SDE_SHOP_NUM);
43650
43651        // 데이터가 하나라도 없는경우 복구 실패
43652        if (sAvailMileage === null
43653            || sReturnedMileage === null
43654            || sUnavailMileage === null
43655            || sUsedMileage === null
43656        ) {
43657            return false;
43658        }
43659
43660        // 전체 마일리지 계산
43661        var sTotalMileage = (parseFloat(sAvailMileage) +
43662            parseFloat(sUnavailMileage) +
43663            parseFloat(sUsedMileage)).toString();
43664
43665        // 단위정보를 계산하여 필드에 셋
43666        this.__sAvailMileage = parseFloat(sAvailMileage).toFixed(2);
43667        this.__sReturnedMileage = parseFloat(sReturnedMileage).toFixed(2);
43668        this.__sUnavailMileage = parseFloat(sUnavailMileage).toFixed(2);
43669        this.__sUsedMileage = parseFloat(sUsedMileage).toFixed(2);
43670        this.__sTotalMileage = parseFloat(sTotalMileage).toFixed(2);
43671
43672        return true;
43673    },
43674
43675    setData: function(aData)
43676    {
43677        this.__sAvailMileage = parseFloat(aData['avail_mileage'] || 0).toFixed(2);
43678        this.__sUsedMileage = parseFloat(aData['used_mileage'] || 0).toFixed(2);
43679        this.__sTotalMileage = parseFloat(aData['total_mileage'] || 0).toFixed(2);
43680        this.__sUnavailMileage = parseFloat(aData['unavail_mileage'] || 0).toFixed(2);
43681        this.__sReturnedMileage = parseFloat(aData['returned_mileage'] || 0).toFixed(2);
43682    },
43683
43684    execute: function()
43685    {
43686        // ECHOSTING-610183: presentment 화폐 변환
43687        var fnFormat = CAFE24.SHOP_PRICE_FORMAT.toShopMileagePrice;
43688        var oCurrInfo = CAFE24.SHOP_CURRENCY_INFO ? CAFE24.SHOP_CURRENCY_INFO[CAFE24.SDE_SHOP_NUM] : null;
43689        if (oCurrInfo && oCurrInfo.bPresentmentEnabled && oCurrInfo.aPresentmentCurrencyInfo) {
43690            fnFormat = CAFE24.SHOP_PRICE_FORMAT.toShopMileagePricePresentment;
43691        }
43692        this.__$target.html(fnFormat(this.__sAvailMileage));
43693        this.__$target2.html(fnFormat(this.__sAvailMileage));
43694        this.__$target3.html(fnFormat(this.__sUsedMileage));
43695        this.__$target4.html(fnFormat(this.__sTotalMileage));
43696        this.__$target5.html(fnFormat(this.__sUnavailMileage));
43697        this.__$target6.html(fnFormat(this.__sReturnedMileage));
43698        this.__$target7.html(fnFormat(this.__sAvailMileage));
43699    },
43700
43701    getData: function()
43702    {
43703        return {
43704            available_mileage: this.__sAvailMileage,
43705            used_mileage: this.__sUsedMileage,
43706            total_mileage: this.__sTotalMileage,
43707            returned_mileage: this.__sReturnedMileage,
43708            unavailable_mileage: this.__sUnavailMileage
43709        };
43710    }
43711};
43712
43713/**
43714 * 비동기식 데이터 - 예치금
43715 */
43716CAPP_ASYNC_METHODS.aDatasetList.push('Deposit');
43717CAPP_ASYNC_METHODS.Deposit = {
43718    __sTotalDeposit: null,
43719    __sAllDeposit: null,
43720    __sUsedDeposit: null,
43721    __sRefundWaitDeposit: null,
43722    __sMemberTotalDeposit: null,
43723
43724    __$target: EC$('#xans_myshop_deposit'),
43725    __$target2: EC$('#xans_myshop_bankbook_deposit'),
43726    __$target3: EC$('#xans_myshop_summary_deposit'),
43727    __$target4: EC$('#xans_myshop_summary_all_deposit'),
43728    __$target5: EC$('#xans_myshop_summary_used_deposit'),
43729    __$target6: EC$('#xans_myshop_summary_refund_wait_deposit'),
43730    __$target7: EC$('#xans_myshop_total_deposit'),
43731
43732    isUse: function()
43733    {
43734        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
43735            if (this.__$target.length > 0) {
43736                return true;
43737            }
43738
43739            if (this.__$target2.length > 0) {
43740                return true;
43741            }
43742
43743            if (this.__$target3.length > 0) {
43744                return true;
43745            }
43746
43747            if (this.__$target4.length > 0) {
43748                return true;
43749            }
43750
43751            if (this.__$target5.length > 0) {
43752                return true;
43753            }
43754
43755            if (this.__$target6.length > 0) {
43756                return true;
43757            }
43758
43759            if (this.__$target7.length > 0) {
43760                return true;
43761            }
43762
43763            if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('customer', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
43764                return true;
43765            }
43766        }
43767
43768        return false;
43769    },
43770
43771    restoreCache: function()
43772    {
43773        // 특정 경로 룰의 경우 복구 취소
43774        if (PathRoleValidator.isInvalidPathRole()) {
43775            return false;
43776        }
43777
43778        // 쿠키로부터 데이터 획득
43779        var sAllDeposit = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_all_deposit_' + CAFE24.SDE_SHOP_NUM);
43780        var sUsedDeposit = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_used_deposit_' + CAFE24.SDE_SHOP_NUM);
43781        var sRefundWaitDeposit = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_deposit_refund_wait_' + CAFE24.SDE_SHOP_NUM);
43782        var sMemberTotalDeposit = CAPP_ASYNC_METHODS._getCookie('ec_async_cache_member_total_deposit_' + CAFE24.SDE_SHOP_NUM);
43783
43784        // 데이터가 하나라도 없는경우 복구 실패
43785        if (sAllDeposit === null
43786            || sUsedDeposit === null
43787            || sRefundWaitDeposit === null
43788            || sMemberTotalDeposit === null
43789        ) {
43790            return false;
43791        }
43792
43793        // 사용 가능한 예치금 계산
43794        var sTotalDeposit = (parseFloat(sAllDeposit) -
43795            parseFloat(sUsedDeposit) -
43796            parseFloat(sRefundWaitDeposit)).toString();
43797
43798        // 단위정보를 계산하여 필드에 셋
43799        this.__sTotalDeposit = parseFloat(sTotalDeposit).toFixed(2);
43800        this.__sAllDeposit = parseFloat(sAllDeposit).toFixed(2);
43801        this.__sUsedDeposit = parseFloat(sUsedDeposit).toFixed(2);
43802        this.__sRefundWaitDeposit = parseFloat(sRefundWaitDeposit).toFixed(2);
43803        this.__sMemberTotalDeposit = parseFloat(sMemberTotalDeposit).toFixed(2);
43804
43805        return true;
43806    },
43807
43808    setData: function(aData)
43809    {
43810        this.__sTotalDeposit = parseFloat(aData['total_deposit'] || 0).toFixed(2);
43811        this.__sAllDeposit = parseFloat(aData['all_deposit'] || 0).toFixed(2);
43812        this.__sUsedDeposit = parseFloat(aData['used_deposit'] || 0).toFixed(2);
43813        this.__sRefundWaitDeposit = parseFloat(aData['deposit_refund_wait'] || 0).toFixed(2);
43814        this.__sMemberTotalDeposit = parseFloat(aData['member_total_deposit'] || 0).toFixed(2);
43815    },
43816
43817    execute: function()
43818    {
43819        // ECHOSTING-616370: presentment 화폐 변환
43820        var fnFormat = CAFE24.SHOP_PRICE_FORMAT.toShopDepositPrice;
43821        var oCurrInfo = CAFE24.SHOP_CURRENCY_INFO ? CAFE24.SHOP_CURRENCY_INFO[CAFE24.SDE_SHOP_NUM] : null;
43822        if (oCurrInfo && oCurrInfo.bPresentmentEnabled && oCurrInfo.aPresentmentCurrencyInfo) {
43823            fnFormat = CAFE24.SHOP_PRICE_FORMAT.toShopDepositPricePresentment;
43824        }
43825        this.__$target.html(fnFormat(this.__sTotalDeposit));
43826        this.__$target2.html(fnFormat(this.__sTotalDeposit));
43827        this.__$target3.html(fnFormat(this.__sTotalDeposit));
43828        this.__$target4.html(fnFormat(this.__sAllDeposit));
43829        this.__$target5.html(fnFormat(this.__sUsedDeposit));
43830        this.__$target6.html(fnFormat(this.__sRefundWaitDeposit));
43831        this.__$target7.html(fnFormat(this.__sMemberTotalDeposit));
43832    },
43833
43834    getData: function()
43835    {
43836        return {
43837            total_deposit: this.__sTotalDeposit,
43838            used_deposit: this.__sUsedDeposit,
43839            refund_wait_deposit: this.__sRefundWaitDeposit,
43840            all_deposit: this.__sAllDeposit,
43841            member_total_deposit: this.__sMemberTotalDeposit
43842        };
43843    }
43844};
43845
43846/**
43847 * 비동기식 데이터 - 위시리스트
43848 */
43849CAPP_ASYNC_METHODS.aDatasetList.push('WishList');
43850CAPP_ASYNC_METHODS.WishList = {
43851    STORAGE_KEY: 'localWishList' + CAFE24.SDE_SHOP_NUM,
43852    __$targetWishIcon: EC$('.icon_img.ec-product-listwishicon'),
43853    __$targetWishList: EC$('.xans-myshop-wishlist'),
43854    __aWishList: null,
43855    __aTags_on: null,
43856    __aTags_off: null,
43857
43858    isUse: function()
43859    {
43860        if (this.__$targetWishIcon.length > 0 || this.__$targetWishList.length > 0
43861        || CAPP_ASYNC_METHODS.EC_PATH_ROLE === 'PRODUCT_DETAIL') {
43862            return true;
43863        }
43864        return false;
43865    },
43866
43867    restoreCache: function()
43868    {
43869        if (!window.sessionStorage) {
43870            return false;
43871        }
43872
43873        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
43874        if (sSessionStorageData === null) {
43875            return false;
43876        }
43877
43878        var aStorageData = CAFE24.UTIL.parseJSON(sSessionStorageData);
43879        if (this.__$targetWishList.length > 0 || aStorageData['isLogin'] !== CAPP_ASYNC_METHODS.IS_LOGIN) {
43880            this.clearStorage();
43881            return false;
43882        }
43883
43884        var aWishList = aStorageData['wishList'];
43885        this.__aTags_on = aStorageData['on_tags'];
43886        this.__aTags_off = aStorageData['off_tags'];
43887        this.__aWishList = [];
43888        for (var i = 0; i < aWishList.length; i++) {
43889            var aTempWishList = [];
43890            aTempWishList.product_no = aWishList[i];
43891            this.__aWishList.push(aTempWishList);
43892        }
43893        return true;
43894    },
43895
43896    setData: function(aData)
43897    {
43898        if (aData.hasOwnProperty('wishList') === false || aData.hasOwnProperty('on_tags') === false) {
43899            return;
43900        }
43901
43902        this.__aWishList = aData.wishList;
43903        this.__aTags_on = aData.on_tags;
43904        this.__aTags_off = aData.off_tags;
43905
43906        if (window.sessionStorage) {
43907            var aWishList = [];
43908
43909            for (var i = 0; i < aData.wishList.length; i++) {
43910                aWishList.push(aData.wishList[i].product_no);
43911            }
43912
43913            var oNewStorageData = {
43914                'wishList': aWishList,
43915                'on_tags': aData.on_tags,
43916                'off_tags': aData.off_tags,
43917                'isLogin': CAPP_ASYNC_METHODS.IS_LOGIN
43918            };
43919
43920            if (typeof oNewStorageData !== 'undefined') {
43921                sessionStorage.setItem(this.STORAGE_KEY , JSON.stringify(oNewStorageData));
43922            }
43923        }
43924    },
43925
43926    execute: function()
43927    {
43928        var aWishList = this.__aWishList;
43929        var aTagsOn = this.__aTags_on;
43930        var aTagsOff = this.__aTags_off;
43931
43932        if (aWishList === null || typeof aWishList === 'undefined') {
43933            aWishList = [];
43934        }
43935
43936        var oTarget = EC$('.ec-product-listwishicon');
43937        for (var sKey in aTagsOff) {
43938            oTarget.attr(sKey, aTagsOff[sKey]);
43939        }
43940
43941        for (var i = 0; i < aWishList.length; i++) {
43942            assignAttribute(aWishList[i]);
43943        }
43944
43945        /**
43946         * oTarget 엘레먼트에 aData의 정보를 어싸인함.
43947         * @param array aData 위시리스트 정보
43948         */
43949        function assignAttribute(aData)
43950        {
43951            var iProductNo = aData['product_no'];
43952            var oTarget = EC$('.ec-product-listwishicon[productno="'+iProductNo+'"]');
43953
43954            // oTarget의 src, alt, icon_status attribute의 값을 할당
43955            for (var sKey in aTagsOn) {
43956                oTarget.attr(sKey, aTagsOn[sKey]);
43957            }
43958        }
43959
43960    },
43961
43962    /**
43963     * 세션스토리지 삭제
43964     */
43965    clearStorage: function()
43966    {
43967        if (!window.sessionStorage) {
43968            return;
43969        }
43970        window.sessionStorage.removeItem(this.STORAGE_KEY);
43971    },
43972
43973    /**
43974     * sCommand에 따른 sessionStorage Set
43975     * @param iProductNo
43976     * @param sCommand 추가(add)/삭제(del) sCommand
43977     */
43978    setSessionStorageItem: function(iProductNo, sCommand)
43979    {
43980        if (this.isUse() === false) {
43981            return;
43982        }
43983
43984        var oStorageData = CAFE24.UTIL.parseJSON(sessionStorage.getItem(this.STORAGE_KEY));
43985        var aWishList = oStorageData['wishList'];
43986        var iLimit = 200;
43987
43988        if (aWishList === null) {
43989            aWishList = [];
43990        }
43991
43992        var iProductNo = parseInt(iProductNo, 10);
43993        var iIndex = aWishList.indexOf(iProductNo);
43994
43995        if (sCommand === 'add') {
43996            if (aWishList.length >= iLimit) {
43997                aWishList.splice(aWishList.length - 1, 1);
43998            }
43999            if (iIndex < 0) {
44000                aWishList.unshift(iProductNo);
44001            }
44002        } else {
44003            if (iIndex > -1) {
44004                aWishList.splice(iIndex, 1);
44005            }
44006        }
44007
44008        oStorageData['wishList'] = aWishList;
44009        sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify(oStorageData));
44010    }
44011};
44012
44013/**
44014 * 비동기식 데이터 - 관심상품 갯수
44015 */
44016CAPP_ASYNC_METHODS.aDatasetList.push('Wishcount');
44017CAPP_ASYNC_METHODS.Wishcount = {
44018    __iWishCount: null,
44019
44020    __$target: EC$('#xans_myshop_interest_prd_cnt'),
44021    __$target2: CAPP_ASYNC_METHODS.$xansMyshopMain.find('.xans_myshop_main_interest_prd_cnt'),
44022
44023    isUse: function()
44024    {
44025        if (this.__$target.length > 0) {
44026            return true;
44027        }
44028        if (this.__$target2.length > 0) {
44029            return true;
44030        }
44031
44032        if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('personal', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
44033            return true;
44034        }
44035
44036        return false;
44037    },
44038
44039    restoreCache: function()
44040    {
44041        var sCookieName = 'wishcount_' + CAFE24.SDE_SHOP_NUM;
44042        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
44043        var aCookieValue = document.cookie.match(re);
44044        if (aCookieValue) {
44045            this.__iWishCount = parseInt(aCookieValue[1], 10);
44046            return true;
44047        }
44048
44049        return false;
44050    },
44051
44052    setData: function(sData)
44053    {
44054        this.__iWishCount = Number(sData);
44055    },
44056
44057    execute: function()
44058    {
44059        if (SHOP.getLanguage() === 'ko_KR') {
44060            this.__$target.html(this.__iWishCount + '개');
44061        } else {
44062            this.__$target.html(this.__iWishCount);
44063        }
44064
44065        this.__$target2.html(this.__iWishCount);
44066    },
44067
44068    getData: function()
44069    {
44070        return {
44071            count: this.__iWishCount
44072        };
44073    }
44074};
44075
44076/**
44077 * 비동기식 데이터 - 최근 본 상품
44078 */
44079CAPP_ASYNC_METHODS.aDatasetList.push('recent');
44080CAPP_ASYNC_METHODS.recent = {
44081    STORAGE_KEY: 'localRecentProduct' + CAFE24.SDE_SHOP_NUM,
44082
44083    __$target: EC$('.xans-layout-productrecent'),
44084
44085    __aData: null,
44086
44087    isUse: function()
44088    {
44089        this.__$target.hide();
44090
44091        if (this.__$target.find('.xans-record-').length > 0) {
44092            return true;
44093        }
44094
44095        return false;
44096    },
44097
44098    restoreCache: function()
44099    {
44100        this.__aData = [];
44101
44102        var iTotalCount = CAPP_ASYNC_METHODS.RecentTotalCount.getData();
44103        if (iTotalCount == 0) {
44104            // 총 갯수가 없는 경우 복구할 것이 없으므로 복구한 것으로 리턴
44105            return true;
44106        }
44107
44108        var sAdultImage = '';
44109
44110        if (window.sessionStorage === undefined) {
44111            return false;
44112        }
44113
44114        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
44115        if (sSessionStorageData === null) {
44116            return false;
44117        }
44118
44119        var iViewCount = EC_FRONT_JS_CONFIG_SHOP.recent_count;
44120
44121        this.__aData = [];
44122        var aStorageData = CAFE24.UTIL.parseJSON(sSessionStorageData);
44123        var iCount = 1;
44124        var bDispRecent = true;
44125        for (var iKey in aStorageData) {
44126            var sProductImgSrc = aStorageData[iKey].sImgSrc;
44127
44128            if (isFinite(iKey) === false) {
44129                continue;
44130            }
44131
44132            var aDataTmp = [];
44133            aDataTmp.recent_img = getImageUrl(sProductImgSrc);
44134            aDataTmp.name = aStorageData[iKey].sProductName;
44135            aDataTmp.disp_recent = true;
44136            aDataTmp.is_adult_product = aStorageData[iKey].isAdultProduct;
44137            aDataTmp.link_product_detail = aStorageData[iKey].link_product_detail;
44138
44139            //aDataTmp.param = '?product_no=' + aStorageData[iKey].iProductNo + '&cate_no=' + aStorageData[iKey].iCateNum + '&display_group=' + aStorageData[iKey].iDisplayGroup;
44140            aDataTmp.param = filterXssUrlParameter(aStorageData[iKey].sParam);
44141            if (iViewCount < iCount) {
44142                bDispRecent = false;
44143            }
44144            aDataTmp.disp_recent = bDispRecent;
44145
44146            iCount++;
44147            this.__aData.push(aDataTmp);
44148        }
44149
44150        return true;
44151
44152        /**
44153         * get SessionStorage image url
44154         * @param sNewImgUrl DB에 저장되어 있는 tiny값
44155         */
44156        function getImageUrl(sImgUrl)
44157        {
44158            if (typeof(sImgUrl) === 'undefined' || sImgUrl === null) {
44159                return;
44160            }
44161            var sNewImgUrl = '';
44162
44163            if (sImgUrl.indexOf('http://') >= 0 || sImgUrl.indexOf('https://') >= 0 || sImgUrl.substr(0, 2) === '//') {
44164                sNewImgUrl = sImgUrl;
44165            } else {
44166                sNewImgUrl = EC_FRONT_JS_CONFIG_SHOP.cdnUrl + '/web/product/tiny/' + sImgUrl;
44167            }
44168
44169            return sNewImgUrl;
44170        }
44171
44172        /**
44173         * 파라미터 URL에서 XSS 공격 관련 파라미터를 필터링합니다. ECHOSTING-162977
44174         * @param string sParam 파라미터
44175         * @return string 필터링된 파라미터
44176         */
44177        function filterXssUrlParameter(sParam)
44178        {
44179            sParam = sParam || '';
44180
44181            var sPrefix = '';
44182            if (sParam.substr(0, 1) === '?') {
44183                sPrefix = '?';
44184                sParam = sParam.substr(1);
44185            }
44186
44187            var aParam = {};
44188
44189            var aParamList = (sParam).split('&');
44190            EC$.each(aParamList, function() {
44191                var aMatch = this.match(/^([^=]+)=(.*)$/);
44192                if (aMatch) {
44193                    aParam[aMatch[1]] = aMatch[2];
44194                }
44195            });
44196
44197            return sPrefix + EC$.param(aParam);
44198        }
44199
44200    },
44201
44202    setData: function(aData)
44203    {
44204        this.__aData = aData;
44205
44206        // 쿠키엔 있지만 sessionStorage에 없는 데이터 복구
44207        if (window.sessionStorage) {
44208
44209            var oNewStorageData = [];
44210
44211            for (var i = 0; i < aData.length; i++) {
44212                if (aData[i].bNewProduct !== true) {
44213                    continue;
44214                }
44215
44216                var aNewStorageData = {
44217                    'iProductNo': aData[i].product_no,
44218                    'sProductName': aData[i].name,
44219                    'sImgSrc': aData[i].recent_img,
44220                    'sParam': aData[i].param,
44221                    'link_product_detail': aData[i].link_product_detail
44222                };
44223
44224                oNewStorageData.push(aNewStorageData);
44225            }
44226
44227            if (oNewStorageData.length > 0) {
44228                sessionStorage.setItem(this.STORAGE_KEY , JSON.stringify(oNewStorageData));
44229            }
44230        }
44231    },
44232
44233    execute: function()
44234    {
44235        var sAdult19Warning = EC_FRONT_JS_CONFIG_SHOP.adult19Warning;
44236
44237        var aData = this.__aData;
44238
44239        var aNodes = this.__$target.find('.xans-record-');
44240        var iRecordCnt = aNodes.length;
44241        var iAddedElementCount = 0;
44242
44243        var aNodesParent = EC$(aNodes[0]).parent();
44244        for (var i = 0; i < aData.length; i++) {
44245            if (!aNodes[i]) {
44246                EC$(aNodes[iRecordCnt - 1]).clone().appendTo(aNodesParent);
44247                iAddedElementCount++;
44248            }
44249        }
44250
44251        if (iAddedElementCount > 0) {
44252            aNodes = this.__$target.find('.xans-record-');
44253        }
44254
44255        if (aData.length > 0) {
44256            this.__$target.show();
44257        }
44258
44259        for (var i = 0; i < aData.length; i++) {
44260            assignVariables(aNodes[i], aData[i]);
44261        }
44262
44263        // 종료 카운트 지정
44264        if (aData.length < aNodes.length) {
44265            iLength = aData.length;
44266            deleteNode();
44267        }
44268
44269        recentBntInit(this.__$target);
44270
44271        /**
44272         * 패치되지 않은 노드를 제거
44273         */
44274        function deleteNode()
44275        {
44276            for (var i = iLength; i < aNodes.length; i++) {
44277                EC$(aNodes[i]).remove();
44278            }
44279        }
44280
44281        /**
44282         * oTarget 엘레먼트에 aData의 변수를 어싸인합니다.
44283         * @param Element oTarget 변수를 어싸인할 엘레먼트
44284         * @param array aData 변수 데이터
44285         */
44286        function assignVariables(oTarget, aData)
44287        {
44288            var recentImage = aData.recent_img;
44289
44290            if (sAdult19Warning === 'T' && CAPP_ASYNC_METHODS.member.getMemberIsAdult() === 'F' && aData.is_adult_product === 'T') {
44291                    recentImage = EC_FRONT_JS_CONFIG_SHOP.adult19BaseTinyImage;
44292            }
44293
44294            var $oTarget = EC$(oTarget);
44295
44296            var sHtml = $oTarget.html();
44297
44298            sHtml = sHtml.replace('about:blank', recentImage)
44299                         .replace('##param##', aData.param)
44300                         .replace('##name##',aData.name)
44301                         .replace('##link_product_detail##', aData.link_product_detail);
44302            $oTarget.html(sHtml);
44303
44304            if (aData.disp_recent === true) {
44305                $oTarget.removeClass('displaynone');
44306            }
44307        }
44308
44309        function recentBntInit($target)
44310        {
44311            // 화면에 뿌려진 갯수
44312            var iDisplayCount = 0;
44313            // 보여지는 style
44314            var sDisplay = '';
44315            var iIdx = 0;
44316            //
44317            var iDisplayNoneIdx = 0;
44318
44319            var nodes = $target.find('.xans-record-').each(function()
44320            {
44321                sDisplay = EC$(this).css('display');
44322                if (sDisplay != 'none') {
44323                    iDisplayCount++;
44324                } else {
44325                    if (iDisplayNoneIdx == 0) {
44326                        iDisplayNoneIdx = iIdx;
44327                    }
44328
44329                }
44330                iIdx++;
44331            });
44332
44333            var iRecentCount = nodes.length;
44334            var bBtnActive = iDisplayCount > 0;
44335            EC$('.xans-layout-productrecent .prev').off('click').click(function()
44336            {
44337                if (bBtnActive !== true) return;
44338                var iFirstNode = iDisplayNoneIdx - iDisplayCount;
44339                if (iFirstNode == 0 || iDisplayCount == iRecentCount) {
44340                    alert(__('최근 본 첫번째 상품입니다.'));
44341                    return;
44342                } else {
44343                    iDisplayNoneIdx--;
44344                    EC$(nodes[iDisplayNoneIdx]).hide();
44345                    EC$(nodes[iFirstNode - 1]).removeClass('displaynone');
44346                    EC$(nodes[iFirstNode - 1]).fadeIn('fast');
44347
44348                }
44349            }).css(
44350            {
44351                cursor: 'pointer'
44352            });
44353
44354            EC$('.xans-layout-productrecent .next').off('click').click(function()
44355            {
44356                if (bBtnActive !== true) return;
44357                if ((iRecentCount) == iDisplayNoneIdx || iDisplayCount == iRecentCount) {
44358                    alert(__('최근 본 마지막 상품입니다.'));
44359                } else {
44360                    EC$(nodes[iDisplayNoneIdx]).fadeIn('fast');
44361                    EC$(nodes[iDisplayNoneIdx]).removeClass('displaynone');
44362                    EC$(nodes[ (iDisplayNoneIdx - iDisplayCount)]).hide();
44363                    iDisplayNoneIdx++;
44364                }
44365            }).css(
44366            {
44367                cursor: 'pointer'
44368            });
44369
44370        }
44371
44372    }
44373};
44374
44375/**
44376 * 비동기식 데이터 - Recentkeyword
44377 */
44378CAPP_ASYNC_METHODS.aDatasetList.push('Recentkeyword');
44379CAPP_ASYNC_METHODS.Recentkeyword = {
44380    __$target: EC$('div.xans-search-recentkeyword'),
44381    RECENT_WORD_KEY: 'RECENT_WORD_' + EC_SDE_SHOP_NUM + '_',
44382    RECENT_WORD_COUNT: 10,
44383
44384    isUse: function()
44385    {
44386        if (this.__$target.length > 0) {
44387            return true;
44388        }
44389    },
44390    //restoreCache: function()
44391    // {
44392    //     var sCookieName = 'RECENT_WORD_' + CAFE24.SDE_SHOP_NUM;
44393    //     var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
44394    //     var aCookieValue = document.cookie.match(re);
44395    //     if (aCookieValue) {
44396    //         this.recentword = aCookieValue[1];
44397    //         return true;
44398    //     }
44399    //
44400    //     return false;
44401    // },
44402
44403    setData: function()
44404    {
44405    },
44406    execute: function()
44407    {
44408        var oTemplate = this.getTemplate();
44409        var sHtml = '';
44410        var sRecentSearchUrl = '/product/search.html?keyword=';
44411        if (typeof(EC_FRONT_JS_CONFIG_SHOP.sSearchUrl) !== 'undefined') {
44412            sRecentSearchUrl = EC_FRONT_JS_CONFIG_SHOP.sSearchUrl;
44413        }
44414
44415        for (var i=1; i <= this.RECENT_WORD_COUNT; i++) {
44416            var sRecentKeyword = CAPP_ASYNC_METHODS._getCookie(this.RECENT_WORD_KEY + i);
44417
44418            if (sRecentKeyword !== null) {
44419                sRecentKeyword = decodeURIComponent(sRecentKeyword);
44420                var oLi = oTemplate.clone();
44421                oLi.find('a').attr('href', sRecentSearchUrl + sRecentKeyword);
44422                oLi.find('a').text(sRecentKeyword);
44423                oLi.find('button').addClass('recent_keyword_remove');
44424                oLi.find('button').attr('index', i);
44425                oLi.find('button').removeAttr('onclick');
44426                sHtml += '<li data-index="' + i + '">' + oLi.html() + '</li>' ;
44427
44428            }
44429        }
44430
44431        CAPP_ASYNC_METHODS.Recentkeyword.__$target.find('ul').html(sHtml);
44432        CAPP_ASYNC_METHODS.Recentkeyword.__$target.find('button.btnDeleteAll').addClass('recent_keyword_remove_all').removeAttr('onclick');
44433    },
44434    getTemplate: function ()
44435    {
44436        return this.__$target.find('ul > li:eq(0)').clone();
44437
44438    }
44439}
44440/**
44441 * 비동기식 데이터 - 최근본상품 총 갯수
44442 */
44443CAPP_ASYNC_METHODS.aDatasetList.push('RecentTotalCount');
44444CAPP_ASYNC_METHODS.RecentTotalCount = {
44445    __iRecentCount: null,
44446
44447    __$target: CAPP_ASYNC_METHODS.$xansMyshopMain.find('.xans_myshop_main_recent_cnt'),
44448
44449    isUse: function()
44450    {
44451        if (this.__$target.length > 0) {
44452            return true;
44453        }
44454
44455        return false;
44456    },
44457
44458    restoreCache: function()
44459    {
44460        var sCookieName = 'recent_plist';
44461        if (CAFE24.SDE_SHOP_NUM > 1) {
44462            sCookieName = 'recent_plist' + CAFE24.SDE_SHOP_NUM;
44463        }
44464        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
44465        var aCookieValue = document.cookie.match(re);
44466        if (aCookieValue) {
44467            this.__iRecentCount = decodeURI(aCookieValue[1]).split('|').length;
44468        } else {
44469            this.__iRecentCount = 0;
44470        }
44471    },
44472
44473    execute: function()
44474    {
44475        this.__$target.html(this.__iRecentCount);
44476    },
44477
44478    getData: function()
44479    {
44480        if (this.__iRecentCount === null) {
44481            // this.isUse값이 false라서 복구되지 않았는데 이 값이 필요한 경우 복구
44482            this.restoreCache();
44483        }
44484
44485        return this.__iRecentCount;
44486    }
44487};
44488
44489/**
44490 * 비동기식 데이터 - 주문정보
44491 */
44492CAPP_ASYNC_METHODS.aDatasetList.push('Order');
44493CAPP_ASYNC_METHODS.Order = {
44494    __iOrderCount: null,
44495    __iOrderTotalPrice: null,
44496    __iGradeIncreaseValue: null,
44497
44498    __$target: EC$('#xans_myshop_bankbook_order_count'),
44499    __$target2: EC$('#xans_myshop_bankbook_order_price'),
44500    __$target3: EC$('#xans_myshop_bankbook_grade_increase_value'),
44501
44502    isUse: function()
44503    {
44504        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
44505            if (this.__$target.length > 0) {
44506                return true;
44507            }
44508
44509            if (this.__$target2.length > 0) {
44510                return true;
44511            }
44512
44513            if (this.__$target3.length > 0) {
44514                return true;
44515            }
44516        }
44517        
44518        return false;        
44519    },
44520
44521    restoreCache: function()
44522    {
44523        var sCookieName = 'order_' + CAFE24.SDE_SHOP_NUM;
44524        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
44525        var aCookieValue = document.cookie.match(re);
44526        if (aCookieValue) {
44527            var aData = CAFE24.UTIL.parseJSON(decodeURIComponent(aCookieValue[1]));
44528            this.__iOrderCount = aData.total_order_count;
44529            this.__iOrderTotalPrice = aData.total_order_price;
44530            this.__iGradeIncreaseValue = Number(aData.grade_increase_value);
44531            return true;
44532        }
44533
44534        return false;
44535    },
44536
44537    setData: function(aData)
44538    {
44539        this.__iOrderCount = aData['total_order_count'];
44540        this.__iOrderTotalPrice = aData['total_order_price'];
44541        this.__iGradeIncreaseValue = Number(aData['grade_increase_value']);
44542    },
44543
44544    execute: function()
44545    {
44546        this.__$target.html(this.__iOrderCount);
44547        this.__$target2.html(this.__iOrderTotalPrice);
44548        this.__$target3.html(this.__iGradeIncreaseValue);
44549    },
44550
44551    getData: function()
44552    {
44553        return {
44554            total_order_count: this.__iOrderCount,
44555            total_order_price: this.__iOrderTotalPrice,
44556            grade_increase_value: this.__iGradeIncreaseValue
44557        };
44558    }
44559};
44560
44561/**
44562 * 비동기식 데이터 - Benefit
44563 */
44564CAPP_ASYNC_METHODS.aDatasetList.push('Benefit');
44565CAPP_ASYNC_METHODS.Benefit = {
44566    __aBenefit: null,
44567    __$target: EC$('.xans-myshop-asyncbenefit'),
44568
44569    isUse: function()
44570    {
44571        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
44572            if (this.__$target.length > 0) {
44573                return true;
44574            }
44575        }
44576
44577        return false;
44578    },
44579
44580    setData: function(aData)
44581    {
44582        this.__aBenefit = aData;
44583    },
44584
44585    execute: function()
44586    {
44587        var aFilter = [
44588            'group_image_tag',
44589            'group_icon_tag',
44590            'display_no_benefit',
44591            'display_with_all',
44592            'display_mobile_use_dc',
44593            'display_mobile_use_mileage',
44594            'display_member_group_dc_limit'
44595        ];
44596        var __aData = this.__aBenefit;
44597        
44598        // 그룹이미지
44599        EC$('.myshop_benefit_group_image_tag').attr({alt: __aData['group_name'], src: __aData['group_image']});
44600
44601        // 그룹아이콘
44602        EC$('.myshop_benefit_group_icon_tag').attr({alt: __aData['group_name'], src: __aData['group_icon']});
44603
44604        if (__aData['display_no_benefit'] === true) {
44605            EC$('.myshop_benefit_display_no_benefit').removeClass('displaynone').show();
44606        }
44607        
44608        if (__aData['display_with_all'] === true) {
44609            EC$('.myshop_benefit_display_with_all').removeClass('displaynone').show();
44610        }
44611        
44612        if (__aData['display_mobile_use_dc'] === true) {
44613            EC$('.myshop_benefit_display_mobile_use_dc').removeClass('displaynone').show();
44614        } 
44615        
44616        if (__aData['display_mobile_use_mileage'] === true) {
44617            EC$('.myshop_benefit_display_mobile_use_mileage').removeClass('displaynone').show();
44618        }
44619
44620        if (__aData['display_member_group_dc_limit'] === true) {
44621            EC$('.myshop_benefit_display_member_group_dc_limit').removeClass('displaynone').show();
44622        }
44623
44624        EC$.each(__aData, function(key, val) {
44625            if (EC$.inArray(key, aFilter) === -1) {
44626                EC$('.myshop_benefit_' + key).html(val);
44627            }
44628        });
44629    }    
44630};
44631
44632/**
44633 * 비동기식 데이터 - 비동기장바구니 레이어
44634 */
44635CAPP_ASYNC_METHODS.aDatasetList.push('BasketLayer');
44636CAPP_ASYNC_METHODS.BasketLayer = {
44637    __sBasketLayerHtml: null,
44638    __$target: document.getElementById('ec_async_basket_layer_container'),
44639
44640    isUse: function()
44641    {
44642        if (this.__$target !== null) {
44643            return true;
44644        }
44645        return false;
44646    },
44647
44648    execute: function()
44649    {
44650        EC$.ajax({
44651            url: '/order/async_basket_layer.html?__popupPage=T',
44652            async: false,
44653            success: function(data) {
44654                var sBasketLayerHtml = data;
44655                var sBasketLayerStyle = '';
44656                var sBasketLayerBody = '';
44657
44658                sBasketLayerHtml = sBasketLayerHtml.replace(/<script([\s\S]*?)<\/script>/gi,''); // 스크립트 제거
44659                sBasketLayerHtml = sBasketLayerHtml.replace(/<link([\s\S]*?)\/>/gi,''); // 옵티마이져 제거
44660
44661                var regexStyle = /<style([\s\S]*?)<\/style>/; // Style 추출
44662                if (regexStyle.exec(sBasketLayerHtml) != null) sBasketLayerStyle = regexStyle.exec(sBasketLayerHtml)[0];
44663
44664                var regexBody = /<body[\s\S]*?>([\s\S]*?)<\/body>/; // Body 추출
44665                var aBasketLayerBodyMatch = regexBody.exec(sBasketLayerHtml);
44666                if (aBasketLayerBodyMatch) {
44667                    // 구엔진(libxml2): fragment를 html/head/body로 감싸므로 body 내부만 사용
44668                    sBasketLayerBody = aBasketLayerBodyMatch[1];
44669                } else {
44670                    // 새엔진(xrlib): body 래핑 없이 style+fragment만 반환하므로 그대로 사용
44671                    // (style은 아래에서 합치므로 중복 방지 위해 별도 추출본은 비움)
44672                    sBasketLayerStyle = '';
44673                    sBasketLayerBody = sBasketLayerHtml;
44674                }
44675
44676                CAPP_ASYNC_METHODS.BasketLayer.__sBasketLayerHtml = sBasketLayerStyle + sBasketLayerBody;
44677            }
44678        });
44679        this.__$target.innerHTML = this.__sBasketLayerHtml;
44680    }
44681};
44682
44683/**
44684 * 비동기식 데이터 - Benefit
44685 */
44686CAPP_ASYNC_METHODS.aDatasetList.push('Grade');
44687CAPP_ASYNC_METHODS.Grade = {
44688    __aGrade: null,
44689    __$target: EC$('#sGradeAutoDisplayArea'),
44690
44691    isUse: function()
44692    {
44693        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
44694            if (this.__$target.length > 0) {
44695                return true;
44696            }
44697        }
44698
44699        return false;
44700    },
44701
44702    setData: function(aData)
44703    {
44704        this.__aGrade = aData;
44705    },
44706
44707    execute: function()
44708    {
44709        var __aData = this.__aGrade;
44710        var aFilter = ['bChangeMaxTypePrice', 'bChangeMaxTypePriceAndCount', 'bChangeMaxTypePriceOrCount', 'bChangeMaxTypeCount'];
44711
44712        var aMaxDisplayJson = {
44713            "bChangeMaxTypePrice": [
44714                {"sId": "sChangeMaxTypePriceArea"}
44715            ],
44716            "bChangeMaxTypePriceAndCount": [
44717                {"sId": "sChangeMaxTypePriceAndCountArea"}
44718            ],
44719            "bChangeMaxTypePriceOrCount": [
44720                {"sId": "sChangeMaxTypePriceOrCountArea"}
44721            ],
44722            "bChangeMaxTypeCount": [
44723                {"sId": "sChangeMaxTypeCountArea"}
44724            ]
44725        };
44726
44727        if (EC$('.sNextGroupIconArea').length > 0) {
44728            if (__aData['bDisplayNextGroupIcon'] === true) {
44729                EC$('.sNextGroupIconArea').removeClass('displaynone').show();
44730                EC$('.myshop_benefit_next_group_icon_tag').attr({alt: __aData['sNextGrade'], src: __aData['sNextGroupIcon']});
44731            } else {
44732                EC$('.sNextGroupIconArea').addClass('displaynone');
44733            }
44734        }
44735
44736        var sIsAutoGradeDisplay = "F";
44737        EC$.each(__aData, function(key, val) {
44738            if (EC$.inArray(key, aFilter) === -1) {
44739                return true;
44740            }
44741            if (val === true) {
44742                if (EC$('#'+aMaxDisplayJson[key][0].sId).length > 0) {
44743                    EC$('#' + aMaxDisplayJson[key][0].sId).removeClass('displaynone').show();
44744                }
44745                sIsAutoGradeDisplay = "T";
44746            }
44747        });
44748        if (sIsAutoGradeDisplay == "T" && EC$('#sGradeAutoDisplayArea .sAutoGradeDisplay').length > 0) {
44749            EC$('#sGradeAutoDisplayArea .sAutoGradeDisplay').addClass('displaynone');
44750        }
44751
44752        EC$.each(__aData, function(key, val) {
44753            if (EC$.inArray(key, aFilter) === -1) {
44754                if (EC$('.xans-member-var-' + key).length > 0) {
44755                    EC$('.xans-member-var-' + key).html(val);
44756                }
44757            }
44758        });
44759    }    
44760};
44761
44762/**
44763 * 비동기식 데이터 - Benefit
44764 */
44765CAPP_ASYNC_METHODS.aDatasetList.push('AutomaticGradeShow');
44766CAPP_ASYNC_METHODS.AutomaticGradeShow = {
44767    __aGrade: null,
44768    __$target: EC$('#sAutomaticGradeShowArea'),
44769
44770    isUse: function()
44771    {
44772        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
44773            if (this.__$target.length > 0) {
44774                return true;
44775            }
44776        }
44777        return false;
44778    },
44779
44780    setData: function(aData)
44781    {
44782        this.__aGrade = aData;
44783    },
44784
44785    execute: function()
44786    {
44787        var __aData = this.__aGrade;
44788
44789        /**
44790         * 아이콘 표기 제외
44791        if (EC$('.sNextGroupIconArea').length > 0) {
44792            if (__aData['bDisplayNextGroupIcon'] === true) {
44793                EC$('.sNextGroupIconArea').removeClass('displaynone').show();
44794                EC$('.myshop_benefit_next_group_icon_tag').attr({alt: __aData['sNextGrade'], src: __aData['sNextGroupIcon']});
44795            } else {
44796                EC$('.sNextGroupIconArea').addClass('displaynone');
44797            }
44798        }
44799         */
44800
44801        var sIsAutoGradeDisplay = "F";
44802        EC$.each(__aData, function(key, val) {
44803            if (val === true) {
44804                sIsAutoGradeDisplay = "T";
44805                return false;
44806            }
44807        });
44808        if (sIsAutoGradeDisplay == "T" && EC$('#sAutomaticGradeShowArea .sAutoGradeDisplay').length > 0) {
44809            EC$('#sAutomaticGradeShowArea .sAutoGradeDisplay').addClass('displaynone');
44810        }
44811
44812        EC$.each(__aData, function(key, val) {
44813            if (EC$('.xans-member-var-' + key).length > 0) {
44814                EC$('.xans-member-var-' + key).html(val);
44815            }
44816        });
44817    }    
44818};
44819
44820/**
44821 * 비동기식 데이터 - 비동기장바구니 레이어
44822 */
44823CAPP_ASYNC_METHODS.aDatasetList.push('MobileMutiPopup');
44824CAPP_ASYNC_METHODS.MobileMutiPopup = {
44825    __$target: EC$('div[class^="ec-async-multi-popup-layer-container"]'),
44826
44827    isUse: function()
44828    {
44829        if (this.__$target.length > 0) {
44830            return true;
44831        }
44832        return false;
44833    },
44834
44835    execute: function()
44836    {
44837        for (var i=0; i < this.__$target.length; i++) {
44838            EC$.ajax({
44839                url: '/exec/front/popup/AjaxMultiPopup?index='+i,
44840                data: EC_ASYNC_MULTI_POPUP_OPTION[i],
44841                dataType: "json",
44842                success: function (oResult) {
44843                    switch (oResult.code) {
44844                        case '0000' :
44845                            if (oResult.data.length < 1) {
44846                                break;
44847                            }
44848                            EC$('.ec-async-multi-popup-layer-container-' + oResult.data.html_index).html(oResult.data.html_text);
44849                            if (oResult.data.type == 'P') {
44850                                BANNER_POPUP_OPEN.setPopupSetting();
44851                                BANNER_POPUP_OPEN.setPopupWidth();
44852                                BANNER_POPUP_OPEN.setPopupClose();
44853                            } else {
44854                                /**
44855                                 * 이중 스크롤 방지 클래스 추가(비동기) 
44856                                 *
44857                                 */
44858                                EC$('body').addClass('eMobilePopup');
44859                                EC$('body').width('100%');
44860
44861                                BANNER_POPUP_OPEN.setFullPopupSetting();
44862                                BANNER_POPUP_OPEN.setFullPopupClose();
44863                            }
44864                            break;
44865                        default :
44866                            break;
44867                    }
44868                },
44869                error: function () {
44870                }
44871            });
44872        }
44873    }
44874};
44875
44876/**
44877 * sns 연동 정보
44878 */
44879CAPP_ASYNC_METHODS.aDatasetList.push('CustomerProvider');
44880CAPP_ASYNC_METHODS.CustomerProvider = {
44881    STORAGE_KEY: 'CustomerProvider_' + CAFE24.SDE_SHOP_NUM,
44882    aData: {member_id: null, provider: null},
44883
44884    isUse: function()
44885    {
44886        return false;
44887    },
44888
44889    restoreCache: function() {
44890        // sessionStorage 지원 여부 확인
44891        if (!window.sessionStorage) {
44892            return false;
44893        }
44894
44895        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
44896        if (sSessionStorageData === null) {
44897            return false;
44898        }
44899
44900        try {
44901
44902            var jsonData = JSON.parse(this.aData);
44903            var aStorageData = JSON.parse(sSessionStorageData);
44904            
44905            // 캐쉬 데이터 설정
44906            jsonData.member_id = aStorageData.membr_id;
44907            jsonData.provider = aStorageData.provider;
44908
44909            this.aData = jsonData;
44910
44911            return true;
44912        } catch (e) {
44913
44914            // 복구 실패시 캐시 삭제
44915            this.removeCache();
44916
44917            return false;
44918        }
44919    },
44920
44921    removeCache: function()
44922    {
44923        // sessionStorage 지원 여부 확인
44924        if (!window.sessionStorage) {
44925            return;
44926        }
44927        // 캐시 삭제
44928        window.sessionStorage.removeItem(this.STORAGE_KEY);
44929    },
44930
44931    setData: function(aData)
44932    {
44933        this.aData = JSON.stringify(aData);
44934        // sessionStorage 지원 여부 확인
44935        if (!window.sessionStorage) {
44936            return false;
44937        }
44938
44939        try {
44940            sessionStorage.setItem(this.STORAGE_KEY, this.aData);
44941        } catch (error) {
44942        }
44943    },
44944
44945    execute: function()
44946    {
44947
44948    },
44949
44950    getData: function()
44951    {
44952        if (typeof this.aData.member_id === 'object') return this.aData;
44953        return JSON.parse(this.aData);
44954    }
44955};
44956
44957var eCacheDefaultShippingAddress = null;
44958if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
44959    CAFE24.CRYPTOKEY.decryptAndLoad('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM).then(function(o) {
44960        eCacheDefaultShippingAddress = o;
44961    }).catch(function(err) {
44962        // console.log(err);
44963    });
44964}
44965
44966
44967/**
44968 * 비동기식 데이터 - 기본 배송주소
44969 */
44970CAPP_ASYNC_METHODS.aDatasetList.push('DefaultShippingAddress');
44971CAPP_ASYNC_METHODS.DefaultShippingAddress = {
44972
44973    __sShippingAlias: null,
44974    __sZipCode: null,
44975    __sAddress1: null,
44976    __sAddress2: null,
44977    __bRestoredFromCache: false,
44978
44979    isUse: function()
44980    {
44981        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
44982            // ECHOSTING-635081: 조회 결과의 유일한 소비처는 App Script SDK
44983            // (CAFE24API.getDefaultShippingAddress -> AppCommon -> getData) 이며,
44984            // 그 진입점이 'customer' scope 를 이미 검사한다. 로그인 UI 존재 여부는
44985            // 배송지 소비와 무관한데도 전 페이지뷰 선조회를 유발했으므로 판정에서 제외한다.
44986            if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('customer', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
44987                return true;
44988            }
44989
44990        } else {
44991            // 비 로그인 상태에서 삭제처리
44992            this.removeCache();
44993        }
44994
44995        return false;
44996    },
44997
44998    restoreCache: function()
44999    {
45000        // sessionStorage 지원 여부 확인
45001        if (!window.sessionStorage) {
45002            return false;
45003        }
45004
45005        // 데이터 복구 유무
45006        var bRestored = false;
45007
45008        try {
45009            // 데이터 복구
45010            var oCache = null;
45011            if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
45012                if (eCacheDefaultShippingAddress) {
45013                    oCache = JSON.parse(eCacheDefaultShippingAddress);
45014                }
45015            } else if (window.location.protocol === 'http:' && (typeof CryptoJS) == 'object') {
45016                if (window.sessionStorage.getItem('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM)) {
45017                    oCache = window.sessionStorage.getItem('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45018                    oCache = CryptoJS.AES.decrypt(oCache, SHOP.getMallID() + '_' + EC_SDE_SHOP_NUM).toString(CryptoJS.enc.Utf8);
45019                    oCache = JSON.parse(oCache);
45020                }
45021            }
45022
45023            // expire 체크
45024            if (oCache.exp < Date.now()) {
45025                throw new Error('cache has expired.');
45026            }
45027
45028            // 데이터 체크
45029            if (typeof oCache.data === 'undefined'
45030                || oCache.data === null
45031                || typeof oCache.data.shipping_alias === 'undefined'
45032                || typeof oCache.data.zip_code === 'undefined'
45033                || typeof oCache.data.address1 === 'undefined'
45034                || typeof oCache.data.address2 === 'undefined'
45035            ) {
45036                throw new Error('Invalid cache data.');
45037            }
45038
45039            // 데이터 복구
45040            this.__sShippingAlias = oCache.data.shipping_alias;
45041            this.__sZipCode = oCache.data.zip_code;
45042            this.__sAddress1 = oCache.data.address1;
45043            this.__sAddress2 = oCache.data.address2;
45044
45045            this.__bRestoredFromCache = true;
45046            bRestored = true;
45047        } catch (e) {
45048            // 복구 실패시 캐시 삭제
45049            this.removeCache();
45050        }
45051
45052        return bRestored;
45053    },
45054
45055    cache: function()
45056    {
45057        // sessionStorage 지원 여부 확인
45058        if (!window.sessionStorage) {
45059            return;
45060        }
45061        // 캐시
45062        var sData = JSON.stringify({exp: Date.now() + (1000 * 60 * 10), data: this.getData()});
45063
45064        if (window.location.protocol === 'https:' && (typeof CAFE24.CRYPTOKEY) == 'object') {
45065            CAFE24.CRYPTOKEY.encryptAndSave('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM, sData);
45066        } else if (window.location.protocol === 'http:' && (typeof CryptoJS) == 'object') {
45067            sData = CryptoJS.AES.encrypt(sData, SHOP.getMallID() + '_' + EC_SDE_SHOP_NUM).toString();
45068            window.sessionStorage.setItem('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM, sData);
45069        }
45070    },
45071
45072    removeCache: function()
45073    {
45074        // sessionStorage 지원 여부 확인
45075        if (!window.sessionStorage) {
45076            return;
45077        }
45078
45079        // 캐시 삭제
45080        window.sessionStorage.removeItem('encryptedData_DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45081        window.sessionStorage.removeItem('iv_DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45082        window.sessionStorage.removeItem('eto4DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45083        window.sessionStorage.removeItem('eto5DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45084        window.sessionStorage.removeItem('DefaultShippingAddress_' + CAFE24.SDE_SHOP_NUM);
45085    },
45086
45087    setData: function(oData)
45088    {
45089        if (oData === null || typeof oData === 'undefined') {
45090            return;
45091        }
45092
45093        var val = function(v) {
45094            return (v === null || typeof v === 'undefined') ? null : v;
45095        };
45096
45097        this.__sShippingAlias = val(oData.shipping_alias);
45098        this.__sZipCode = val(oData.zip_code);
45099        this.__sAddress1 = val(oData.address1);
45100        this.__sAddress2 = val(oData.address2);
45101    },
45102
45103    execute: function()
45104    {
45105        // ECHOSTING-635081: 캐시에서 복원된 경우 재저장하지 않는다.
45106        // async.js setData() 는 캐시 히트 모듈에도 execute() 를 호출하므로, 그대로 두면
45107        // 매 페이지뷰마다 exp 가 갱신되어 TTL 이 슬라이딩 윈도우가 된다(= 활성 세션 동안 만료 안 됨).
45108        // 어드민/API 로 배송지가 바뀌었을 때의 노출 창을 10분으로 고정하기 위해 분기한다.
45109        if (this.__bRestoredFromCache === true) {
45110            return;
45111        }
45112        this.cache();
45113    },
45114
45115    getData: function()
45116    {
45117        if (CAPP_ASYNC_METHODS.STATUS == 'unready') {
45118            CAPP_ASYNC_METHODS.init();
45119        }
45120
45121        if (this.__sShippingAlias === null
45122            && this.__sZipCode === null
45123            && this.__sAddress1 === null
45124            && this.__sAddress2 === null) {
45125            return null;
45126        }
45127
45128        return {
45129            shipping_alias: this.__sShippingAlias,
45130            zip_code: this.__sZipCode,
45131            address1: this.__sAddress1,
45132            address2: this.__sAddress2
45133        };
45134    }
45135};
45136
45137/**
45138 * 비동기식 데이터 - 좋아요 상품 갯수
45139 */
45140CAPP_ASYNC_METHODS.aDatasetList.push('MyLikeProductCount');
45141CAPP_ASYNC_METHODS.MyLikeProductCount = {
45142    __iMyLikeCount: null,
45143
45144    __$target: EC$('#xans_myshop_like_prd_cnt'),
45145    __$target_main: EC$('#xans_myshop_main_like_prd_cnt'),
45146    isUse: function()
45147    {
45148        if (this.__$target.length > 0 && SHOP.getLanguage() === 'ko_KR') {
45149            return true;
45150        }
45151
45152        if (this.__$target_main.length > 0 && SHOP.getLanguage() === 'ko_KR') {
45153            return true;
45154        }
45155
45156        return false;
45157    },
45158    restoreCache: function()
45159    {
45160        var sCookieName = 'like_product_cnt' + CAFE24.SDE_SHOP_NUM;
45161        var re = new RegExp('(?:^| |;)' + sCookieName + '=([^;]+)');
45162        var aCookieValue = document.cookie.match(re);
45163        if (aCookieValue) {
45164            this.__iMyLikeCount = parseInt(aCookieValue[1], 10);
45165            return true;
45166        }
45167
45168        return false;
45169    },
45170
45171    setData: function(sData)
45172    {
45173        this.__iMyLikeCount = Number(sData);
45174    },
45175
45176    execute: function()
45177    {
45178        if (SHOP.getLanguage() === 'ko_KR') {
45179            this.__$target.html(this.__iMyLikeCount + '개');
45180            this.__$target_main.html(this.__iMyLikeCount);
45181        }
45182    }
45183};
45184
45185/**
45186 * 비동기식 데이터 - 좋아요 상품 list
45187 */
45188CAPP_ASYNC_METHODS.aDatasetList.push('MyLikeProductList');
45189CAPP_ASYNC_METHODS.MyLikeProductList = {
45190    __aMyLikeList: null,
45191    __iMyLikeListLimit: 10,
45192    __$target: EC$('.xans-product-likeproductasync'),
45193    isUse: function()
45194    {
45195        if (this.__$target.length > 0 && SHOP.getLanguage() === 'ko_KR') {
45196            return true;
45197        }
45198
45199        if (EC$('#EC_LIKE_ASYNC_LINK_DATA_LIST').length > 0) {
45200            return true;
45201        }
45202        return false;
45203    },
45204    setData: function(aData)
45205    {
45206        this.__iMyLikeListLimit = EC_FRONT_JS_CONFIG_SHOP.aSyncLikeLimit;
45207        this.__aMyLikeList = aData;
45208    },
45209    execute: function()
45210    {
45211
45212        if (this.__aMyLikeList === null || this.__aMyLikeList.length === 0) {
45213            EC$('#EC_LIKE_ASYNC_LINK_DATA_EMPTY').html('');
45214            return;
45215        }
45216
45217        //EC$('#EC_LIKE_ASYNC_LINK_DATA_EMPTY').remove();
45218        var sSpaceIcon = ' ';
45219        for (var iKey = 0; iKey < this.__aMyLikeList.length; iKey++) {
45220            var oRowData = EC$('#EC_LIKE_ASYNC_LINK_DATA_LIST_TEMP').clone().removeAttr('id');
45221            oRowData.find('a[href^="/product/detail.html"').attr('href', this.__aMyLikeList[iKey].link_product_detail);
45222            oRowData.find('.thumb img').attr('src',this.__aMyLikeList[iKey].image_medium);
45223            oRowData.find('.EC_LIKE_ASYNC_LINK_DATA_PRODUCT_NAME').html('<a href="' + this.__aMyLikeList[iKey].link_product_detail + '">' + this.__aMyLikeList[iKey].disp_product_name + '</a>');
45224
45225            var sIconListHtml = this.__aMyLikeList[iKey].soldout_icon + sSpaceIcon + this.__aMyLikeList[iKey].stock_icon + sSpaceIcon + this.__aMyLikeList[iKey].recommend_icon + sSpaceIcon +
45226                this.__aMyLikeList[iKey].new_icon + sSpaceIcon + this.__aMyLikeList[iKey].product_icons + sSpaceIcon + this.__aMyLikeList[iKey].benef
45226it_icons;
45227             if (sIconListHtml !== '') {
45228                oRowData.find('.EC_LIKE_ASYNC_LINK_DATA_ICON_LIST').html(sIconListHtml);
45229            }
45230
45231            EC$('#EC_LIKE_ASYNC_LINK_DATA_APPEND').append(oRowData);
45232
45233            if (iKey >= (this.__iMyLikeListLimit - 1)) {
45234                break;
45235            }
45236        }
45237        EC$('#EC_LIKE_ASYNC_LINK_DATA_LIST_TEMP').remove();
45238        if (this.__aMyLikeList.length < this.__iMyLikeListLimit) {
45239            EC$('#EC_LIKE_ASYNC_LINK_DATA_MORE_VIEW').remove();
45240        }
45241
45242        if (EC_FRONT_JS_CONFIG_SHOP.bAutoView === 'T') {
45243            document.getElementById('EC_LIKE_ASYNC_LINK_DATA_LIST').style.display = 'block';
45244        }
45245
45246    }
45247};
45248
45249/**
45250 * 비동기식 데이터 - 마이쇼핑 > 주문 카운트 (주문 건수 / CS건수 / 예전주문)
45251 */
45252CAPP_ASYNC_METHODS.aDatasetList.push('OrderHistoryCount');
45253CAPP_ASYNC_METHODS.OrderHistoryCount = {
45254    __sTotalOrder: null,
45255    __sTotalOrderCs: null,
45256    __sTotalOrderOld: null,
45257
45258    __$target: EC$('#ec_myshop_total_orders'),
45259    __$target2: EC$('#ec_myshop_total_orders_cs'),
45260    __$target3: EC$('#ec_myshop_total_orders_old'),
45261
45262    isUse: function()
45263    {
45264        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
45265            if (this.__$target.length > 0) {
45266                return true;
45267            }
45268
45269            if (this.__$target2.length > 0) {
45270                return true;
45271            }
45272
45273            if (this.__$target3.length > 0) {
45274                return true;
45275            }
45276        }
45277
45278        return false;
45279    },
45280
45281    setData: function(aData)
45282    {
45283        this.__sTotalOrder = aData['total_orders'];
45284        this.__sTotalOrderCs = aData['total_orders_cs'];
45285        this.__sTotalOrderOld = aData['total_orders_old'];
45286
45287    },
45288
45289    execute: function()
45290    {
45291        this.__$target.html(this.__sTotalOrder);
45292        this.__$target2.html(this.__sTotalOrderCs);
45293        this.__$target3.html(this.__sTotalOrderOld);
45294    }
45295};
45296
45297/**
45298 * 주문조회 > 주문내역조회 및 취소/교환/반품내역 등 탭(OrderHistoryTab) 갯수 비동기호출
45299 */
45300CAPP_ASYNC_METHODS.aDatasetList.push('OrderHistoryTab');
45301CAPP_ASYNC_METHODS.OrderHistoryTab = {
45302    __$targetTotalOrders: EC$('#xans_myshop_total_orders'),
45303    __$targetTotalOrdersCs: EC$('#xans_myshop_total_orders_cs'),
45304    __$targetTotalOrdersPast: EC$('#xans_myshop_total_orders_past'),
45305    __$targetTotalOrdersOld: EC$('#xans_myshop_total_orders_old'),
45306
45307    isUse: function()
45308    {
45309        if (EC$('.xans-myshop-orderhistorytab').length > 0) {
45310            return true;
45311        }
45312        return false;
45313    },
45314    execute: function()
45315    {
45316        try {
45317            var mode = this.getUrlParam('mode');
45318            var order_id = this.getUrlParam('order_id');
45319            var order_status = this.getUrlParam('order_status');
45320            var history_start_date = this.getUrlParam('history_start_date');
45321            var history_end_date = this.getUrlParam('history_end_date');
45322            var past_year = this.getUrlParam('past_year');
45323            var count = this.getUrlParam('count');
45324
45325            var sPathName = window.location.pathname;
45326
45327            var oParameters = {
45328                'mode': mode == null ? '' : mode,
45329                'order_id': order_id == null ? '' : order_id,
45330                'order_status': order_status == null ? '' : order_status,
45331                'history_start_date': history_start_date == null ? '' : history_start_date,
45332                'history_end_date': history_end_date == null ? '' : history_end_date,
45333                'past_year': past_year == null ? '' : past_year,
45334                'count': count == null ? '' : count,
45335                'page_name': sPathName.substring(sPathName.lastIndexOf("/") + 1, sPathName.indexOf('.'))
45336            };
45337
45338            if (typeof EC_ASYNC_ORDERHISTORYTAB_ORDER_ID !== 'undefined') {
45339                oParameters['encrypted_str'] = EC_ASYNC_ORDERHISTORYTAB_ORDER_ID;
45340            }
45341
45342            var oThis = this;
45343
45344            EC$.ajax({
45345                url: '/exec/front/Myshop/OrderHistoryTab',
45346                dataType: 'json',
45347                data: oParameters,
45348                success: function (aData) {
45349                    if (aData['result'] === true) {
45350                        oThis.__$targetTotalOrders.html(aData['total_orders']);
45351                        oThis.__$targetTotalOrdersCs.html(aData['total_orders_cs']);
45352                        oThis.__$targetTotalOrdersOld.html(aData['total_orders_old']);
45353                        oThis.__$targetTotalOrdersPast.html(aData['total_orders_past']);
45354
45355                        var oTabATagList = {
45356                            'param': EC$('.tab_class a'),
45357                            'param_cs': EC$('.tab_class_cs a'),
45358                            'param_past': EC$('.tab_class_past a'),
45359                            'param_old': EC$('.tab_class_old a'),
45360                        };
45361                        var sHref;
45362                        EC$.each(oTabATagList, function(sKey, oTarget) {
45363                            if (oTarget.length > 0) {
45364                                sHref = oTarget.attr("href");
45365                                sHref = sHref.replace("$" + sKey, aData[sKey]);
45366                                oTarget.attr("href", sHref);
45367                            }
45368                        });
45369
45370                        EC$("." + aData['selected_tab_class']).addClass('selected');
45371
45372                        if (aData['is_past_list_display'] === false) {
45373                            EC$('.tab_class_past').addClass("displaynone");
45374                        } else {
45375                            EC$('.tab_class_past').removeClass("displaynone");
45376                        }
45377
45378                        if (aData['old_list_display'] === false) {
45379                            EC$('.tab_class_old').addClass("displaynone");
45380                        } else {
45381                            EC$('.tab_class_old').removeClass("displaynone");
45382                        }
45383                    }
45384                }
45385            });
45386        } catch (oError) {
45387            this.errorAjaxCall(oError);
45388        }
45389    },
45390    getUrlParam: function(name)
45391    {
45392        var param = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
45393        if (param == null) {
45394            return null;
45395        } else {
45396            return decodeURI(param[1]) || null;
45397        }
45398    },
45399    errorAjaxCall: function(oError)
45400    {
45401        var sError = oError.toString();
45402        var aMatch = sError.match(/Error*/g);
45403
45404        if (typeof(oError) !== 'object' || aMatch == null || aMatch.length < 1 || !oError.stack) return;
45405
45406        EC$.ajax({
45407            url: '/exec/front/order/FormJserror/',
45408            method: 'POST',
45409            cache: false,
45410            async: false,
45411            data: {
45412                errorMessage: oError.message,
45413                errorStack: oError.stack,
45414                errorName: oError.name
45415            }
45416        });
45417    }
45418};
45419
45420/*
45421 * 비동기식 데이터 - 주문조회 품목 리스트
45422 */
45423CAPP_ASYNC_METHODS.aDatasetList.push('OrderHistoryItemList');
45424CAPP_ASYNC_METHODS.OrderHistoryItemList = {
45425
45426    STORAGE_KEY: 'OrderHistoryItemList_' + EC_SDE_SHOP_NUM,
45427
45428    __aData: null,
45429
45430    isUse: function()
45431    {
45432        // 주문조회 페이지 && SDK order권한이 있는경우에만 노출
45433        if (EC$('.xans-myshop-orderhistorylistitem').length > 0 && typeof EC_APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('order', EC_APPSCRIPT_SDK_DATA) > -1) {
45434            return true;
45435        }
45436
45437        // 비 로그인 상태에서 삭제처리
45438        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
45439            this.removeCache();
45440        }
45441    },
45442
45443    restoreCache: function()
45444    {
45445        // sessionStorage 지원 여부 확인
45446        if (!window.sessionStorage) {
45447            return false;
45448        }
45449
45450        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
45451        if (sSessionStorageData === null || !sSessionStorageData) {
45452            return false;
45453        }
45454
45455        try {
45456            var aStorageData = JSON.parse(sSessionStorageData);
45457
45458            // expire 체크
45459            if (aStorageData.exp < Date.now()) {
45460                throw 'cache has expired.';
45461            }
45462
45463            this.__aData = [];
45464            for (var iKey in aStorageData.data) {
45465                this.__aData.push(aStorageData.data[iKey]);
45466            }
45467
45468            return true;
45469        } catch (e) {
45470
45471            // 복구 실패시 캐시 삭제
45472            this.removeCache();
45473
45474            return false;
45475        }
45476    },
45477
45478    removeCache: function()
45479    {
45480        // sessionStorage 지원 여부 확인
45481        if (!window.sessionStorage) {
45482            return;
45483        }
45484        // 캐시 삭제
45485        window.sessionStorage.removeItem(this.STORAGE_KEY);
45486    },
45487
45488    setData: function(oData)
45489    {
45490        this.__aData = oData;
45491
45492        // sessionStorage 지원 여부 확인
45493        if (!window.sessionStorage) {
45494            return;
45495        }
45496
45497        try {
45498            sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify({
45499                exp: Date.now() + (1000 * 60 * 1),
45500                data: this.getData()
45501            }));
45502        } catch (error) {
45503        }
45504    },
45505
45506    getData: function()
45507    {
45508        this.restoreCache();
45509        var aStorageData = this.__aData;
45510
45511        if (aStorageData !== null && aStorageData !== false) {
45512            var oNewStorageData = [];
45513            for (var iKey in aStorageData) {
45514                oNewStorageData.push(aStorageData[iKey]);
45515            }
45516            return oNewStorageData;
45517        }
45518        return false;
45519    },
45520
45521    getAsyncData: function(start_date, end_date, order_status, page, count, order_id)
45522    {
45523        return new Promise(function (res) {
45524            var oParameters = {
45525                'order_id': order_id === null ? '' : order_id,
45526                'order_status': order_status === null ? '' : order_status,
45527                'start_date': start_date === null ? '' : start_date,
45528                'end_date': end_date === null ? '' : end_date,
45529                'count': count === null ? '' : count,
45530                'page': page === null ? '' : page,
45531            };
45532
45533            if (typeof EC_ASYNC_ORDERHISTORYTAB_ORDER_ID !== 'undefined') {
45534                oParameters['encrypted_str'] = EC_ASYNC_ORDERHISTORYTAB_ORDER_ID;
45535            }
45536
45537            EC$.ajax(
45538                {
45539                    url: '/exec/front/manage/async?module=OrderHistoryItemList',
45540                    data: oParameters,
45541                    dataType: 'json',
45542                    success: function (aData) {
45543                        var aResult = [];
45544                        var aStorageData = aData.OrderHistoryItemList;
45545
45546                        for (var iKey in aStorageData) {
45547                            aResult.push(aStorageData[iKey]);
45548                        }
45549                        res(aResult);
45550                    }
45551                });
45552        });
45553    }
45554};
45555/**
45556 * 비동기식 데이터 - 주문상세 조회
45557 */
45558CAPP_ASYNC_METHODS.aDatasetList.push('OrderDetailInfo');
45559CAPP_ASYNC_METHODS.OrderDetailInfo = {
45560    STORAGE_KEY: 'OrderDetailInfo_' + EC_SDE_SHOP_NUM,
45561    __aData: null,
45562
45563
45564    isUse: function()
45565    {
45566        // 주문상세 페이지 && SDK order권한이 있는경우에만 노출
45567        if (EC$('.xans-myshop-orderhistorydetail').length > 0 && typeof EC_APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('order', EC_APPSCRIPT_SDK_DATA) > -1) {
45568            return true;
45569        }
45570
45571        // 비 로그인 상태에서 삭제처리
45572        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
45573            this.removeCache();
45574        }
45575    },
45576
45577    restoreCache: function()
45578    {
45579        // sessionStorage 지원 여부 확인
45580        if (!window.sessionStorage) {
45581            return false;
45582        }
45583
45584        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
45585        if (sSessionStorageData === null || !sSessionStorageData) {
45586            return false;
45587        }
45588
45589        try {
45590            var aStorageData = JSON.parse(sSessionStorageData);
45591
45592            // expire 체크
45593            if (aStorageData.exp < Date.now()) {
45594                throw 'cache has expired.';
45595            }
45596
45597            this.__aData = [];
45598            for (var iKey in aStorageData.data) {
45599                this.__aData.push(aStorageData.data[iKey]);
45600            }
45601
45602            return true;
45603        } catch (e) {
45604
45605            // 복구 실패시 캐시 삭제
45606            this.removeCache();
45607
45608            return false;
45609        }
45610    },
45611
45612
45613    removeCache: function()
45614    {
45615        // sessionStorage 지원 여부 확인
45616        if (!window.sessionStorage) {
45617            return;
45618        }
45619        // 캐시 삭제
45620        window.sessionStorage.removeItem(this.STORAGE_KEY);
45621    },
45622
45623    setData: function(oData)
45624    {
45625        this.__aData = oData;
45626
45627        // sessionStorage 지원 여부 확인
45628        if (!window.sessionStorage) {
45629            return;
45630        }
45631
45632        try {
45633            sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify({
45634                exp: Date.now() + (1000 * 60 * 1),
45635                data: this.getData()
45636            }));
45637        } catch (error) {
45638        }
45639    },
45640
45641    getData: function()
45642    {
45643        this.restoreCache();
45644        var aStorageData = this.__aData;
45645
45646        if (aStorageData !== null && aStorageData !== false) {
45647            var oNewStorageData = [];
45648            for (var iKey in aStorageData) {
45649                oNewStorageData.push(aStorageData[iKey]);
45650            }
45651            return oNewStorageData;
45652        }
45653        return false;
45654    },
45655
45656    getAsyncData: function (shop_no, order_id) {
45657        return new Promise(function (res) {
45658            var oParameters = {
45659                'shop_no': shop_no === null ? '' : shop_no,
45660                'order_id': order_id === null ? '' : order_id,
45661            };
45662
45663            if (typeof EC_ASYNC_ORDERHISTORYTAB_ORDER_ID !== 'undefined') {
45664                oParameters['encrypted_str'] = EC_ASYNC_ORDERHISTORYTAB_ORDER_ID;
45665            }
45666
45667            EC$.ajax(
45668                {
45669                    url: '/exec/front/manage/async?module=OrderDetailInfo',
45670                    data: oParameters,
45671                    dataType: 'json',
45672                    success: function (aData) {
45673                        var aResult = [];
45674                        var aStorageData = aData.OrderDetailInfo;
45675
45676                        for (var iKey in aStorageData) {
45677                            aResult.push(aStorageData[iKey]);
45678                        }
45679                        res(aResult);
45680                    }
45681                });
45682        });
45683    }
45684}
45685/**
45686 * 비동기식 데이터 - 주문 취소/교환/반품 가능 품목리스트
45687 */
45688CAPP_ASYNC_METHODS.aDatasetList.push('ClaimableItemList');
45689CAPP_ASYNC_METHODS.ClaimableItemList = {
45690    STORAGE_KEY: 'ClaimableItemList_' + EC_SDE_SHOP_NUM,
45691    __aData: null,
45692    __$target: EC$('.xans-myshop-orderhistoryapplycancel'), //취소
45693    __$target2: EC$('.xans-myshop-orderhistoryapplyexchange'), //교환
45694    __$target3: EC$('.xans-myshop-orderhistoryapplyreturn'), //반품
45695
45696    isUse: function()
45697    {
45698        // 주문상세 페이지 && SDK order권한이 있는경우에만 노출
45699        if (typeof EC_APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('order', EC_APPSCRIPT_SDK_DATA) > -1) {
45700            if (this.__$target.length > 0) {
45701                return true;
45702            }
45703            if (this.__$target2.length > 0) {
45704                return true;
45705            }
45706            if (this.__$target3.length > 0) {
45707                return true;
45708            }
45709        }
45710
45711        // 비 로그인 상태에서 삭제처리
45712        if (CAPP_ASYNC_METHODS.IS_LOGIN === false) {
45713            this.removeCache();
45714        }
45715    },
45716
45717    restoreCache: function()
45718    {
45719        // sessionStorage 지원 여부 확인
45720        if (!window.sessionStorage) {
45721            return false;
45722        }
45723
45724        var sSessionStorageData = window.sessionStorage.getItem(this.STORAGE_KEY);
45725        if (sSessionStorageData === null || !sSessionStorageData) {
45726            return false;
45727        }
45728
45729        try {
45730            var aStorageData = JSON.parse(sSessionStorageData);
45731
45732            // expire 체크
45733            if (aStorageData.exp < Date.now()) {
45734                throw new Error('cache has expired.');
45735            }
45736
45737            this.__aData = [];
45738            for (var iKey in aStorageData.data) {
45739                this.__aData.push(aStorageData.data[iKey]);
45740            }
45741
45742            return true;
45743        } catch (e) {
45744            // 복구 실패시 캐시 삭제
45745            this.removeCache();
45746            return false;
45747        }
45748    },
45749
45750
45751    removeCache: function()
45752    {
45753        // sessionStorage 지원 여부 확인
45754        if (!window.sessionStorage) {
45755            return;
45756        }
45757        // 캐시 삭제
45758        window.sessionStorage.removeItem(this.STORAGE_KEY);
45759    },
45760
45761    setData: function(oData)
45762    {
45763        this.__aData = oData;
45764
45765        // sessionStorage 지원 여부 확인
45766        if (!window.sessionStorage) {
45767            return;
45768        }
45769
45770        try {
45771            sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify({
45772                exp: Date.now() + (1000 * 60 * 1),
45773                data: this.getData()
45774            }));
45775        } catch (error) {
45776        }
45777    },
45778
45779    getData: function()
45780    {
45781        this.restoreCache();
45782        var aStorageData = this.__aData;
45783
45784        if (aStorageData !== null && aStorageData !== false && aStorageData.length > 0) {
45785            var oNewStorageData = [];
45786            for (var iKey in aStorageData) {
45787                oNewStorageData.push(aStorageData[iKey]);
45788            }
45789            return oNewStorageData;
45790        }
45791        return false;
45792    },
45793
45794    getAsyncData: function (order_id, customer_service_type) {
45795        return new Promise(function (res,rej) {
45796            if (customer_service_type === null) {
45797                if (CAPP_ASYNC_METHODS.ClaimableItemList.__$target.length > 0) {
45798                    customer_service_type = 'C';
45799                } else if (CAPP_ASYNC_METHODS.ClaimableItemList.__$target2.length > 0) {
45800                    customer_service_type = 'E';
45801                } else if (CAPP_ASYNC_METHODS.ClaimableItemList.__$target3.length > 0) {
45802                    customer_service_type = 'R';
45803                }
45804            }
45805            order_id = order_id === null ? CAPP_ASYNC_METHODS.ClaimableItemList.getUrlParam('order_id') : order_id;
45806
45807            if (order_id === '' || order_id === null) {
45808                rej({code: 422, message: 'order_id is empty'})
45809            }
45810
45811            var oParameters = {
45812                'order_id': order_id,
45813                'customer_service_type': customer_service_type
45814            };
45815
45816            EC$.ajax(
45817                {
45818                    url: '/exec/front/manage/async?module=ClaimableItemList',
45819                    data: oParameters,
45820                    dataType: 'json',
45821                    success: function (aData) {
45822                        var aResult = [];
45823                        var aStorageData = aData.ClaimableItemList;
45824
45825                        CAPP_ASYNC_METHODS.ClaimableItemList.removeCache();
45826                        CAPP_ASYNC_METHODS.ClaimableItemList.setData(aStorageData);
45827
45828                        for (var iKey in aStorageData) {
45829                            aResult.push(aStorageData[iKey]);
45830                        }
45831                        res(aResult);
45832                    }
45833                });
45834        });
45835    },
45836    getUrlParam: function(name)
45837    {
45838        var param = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
45839        if (param === null) {
45840            return null;
45841        } else {
45842            return decodeURI(param[1]) || null;
45843        }
45844    }
45845};
45846var PathRoleValidator = (function() {
45847    /**
45848     * Milage, Deposit 의 경우 처리되지 말아야할 페이지 확인
45849     * @returns {boolean}
45850     */
45851    function isInvalidPathRole()
45852    {
45853        // path role
45854        var sCurrentPathRole = null;
45855
45856        // // euckr 환경에서 path role 획득
45857        if (SHOP.getProductVer() === 1) {
45858            // path 와 role 매핑
45859            var aPathRoleMap = {
45860                '/myshop/index.html': 'MYSHOP_MAIN',
45861                '/myshop/mileage/historyList.html': 'MYSHOP_MILEAGE_LIST',
45862                '/myshop/deposits/historyList.html': 'MYSHOP_DEPOSIT_LIST',
45863                '/order/orderform.html': 'ORDER_ORDERFORM'
45864            };
45865
45866            // 페이지 경로로부터 path role 획득
45867            sCurrentPathRole = aPathRoleMap[document.location.pathname];
45868
45869            // utf8 환경에서 path role 획득
45870        } else {
45871            // 현재 페이지 path role 획득
45872            sCurrentPathRole = EC$('meta[name="path_role"]').attr('content');
45873        }
45874
45875        // 처리되면 안되는 경로
45876        var aInvalidPathRole = [
45877            'MYSHOP_MAIN',
45878            'MYSHOP_MILEAGE_LIST',
45879            'MYSHOP_DEPOSIT_LIST',
45880            'ORDER_ORDERFORM'
45881        ];
45882
45883        return EC$.inArray(sCurrentPathRole, aInvalidPathRole) >= 0;
45884    }
45885
45886    return {
45887        isInvalidPathRole: isInvalidPathRole
45888    };
45889})();
45890
45891EC$(function()
45892{
45893    CAPP_ASYNC_METHODS.init();
45894});
45895
45896CAFE24.MANAGE_PRODUCT_RECENT = {
45897    getRecentImageUrl: function() {
45898        var sStorageKey = 'localRecentProduct' + CAFE24.SDE_SHOP_NUM;
45899
45900        if (typeof sessionStorage[sStorageKey] !== 'undefined') {
45901            var sRecentData = sessionStorage.getItem(sStorageKey);
45902            var oJsonData = JSON.parse(sRecentData);
45903            var sImageSrc = '';
45904
45905            if (oJsonData[0] !== undefined) {
45906                sImageSrc = oJsonData[0].sImgSrc;
45907                if (typeof EC_FRONT_JS_CONFIG_MANAGE !== 'undefined' && typeof EC_FRONT_JS_CONFIG_MANAGE.cdnUrl !== 'undefined' && EC_FRONT_JS_CONFIG_MANAGE.cdnUrl !== '') {
45908                    sImageSrc = EC_FRONT_JS_CONFIG_MANAGE.cdnUrl + '/web/product/tiny/' + sImageSrc;
45909                }
45910            }
45911
45912            document.location.replace('recentproduct://setinfo?simg_src=' + sImageSrc);
45913        }
45914    }
45915};
45916
45917var EC_MANAGE_PRODUCT_RECENT = CAFE24.getDeprecatedNamespace('EC_MANAGE_PRODUCT_RECENT');
45918
45919CAFE24.MANAGE_MEMBER = {
45920    // 카카오싱크 로그인
45921    kakaosyncLogin: function(clientSecret) {
45922        if (Kakao.isInitialized()) {
45923            Kakao.cleanup();
45924        }
45925        Kakao.init(clientSecret);
45926
45927        Kakao.Auth.authorize({
45928            redirectUri: location.origin + EC_ROUTE.getPrefixUrl('/Api/Member/Oauth2ClientCallback/kakao/'),
45929            throughTalk: true
45930        });
45931    }
45932};
45933
45934var EC_MANAGE_MEMBER = CAFE24.getDeprecatedNamespace('EC_MANAGE_MEMBER');
45935
45936// 프로토콜 체크 포함
45937if (window.navigator && 'serviceWorker' in window.navigator) {
45938    window.addEventListener('load', function () {
45939        var getFrontendConfig = function (sOption) {
45940            if (typeof window.CAFE24 === 'object' && typeof window.CAFE24.FRONTEND === 'object') {
45941                return window.CAFE24.FRONTEND[sOption];
45942            }
45943
45944            return null;
45945        };
45946
45947        var sCafeSWName = '/ind-script/sw.php';
45948        var sA2hsLogKey = 'a2hs_manifest_name';
45949        var oManifest = document.querySelector('link[rel="manifest"]');
45950        var bHasManifest = !!oManifest;
45951        if (bHasManifest === true) {
45952            // start_url 로 들어온 경우 로깅
45953            if (location.pathname === '/' && location.search.indexOf('a2hs=1') !== -1) {
45954                var sManifestName = oManifest.href.split('/').pop();
45955
45956                var sStoredManifestName = localStorage.getItem(sA2hsLogKey);
45957                if (!sStoredManifestName || sStoredManifestName !== sManifestName) {
45958                    if (window.fetch) {
45959                        fetch('/exec/front/manage/a2hs', {
45960                            headers: {
45961                                'Content-Type': 'application/json'
45962                            },
45963                            method: 'POST',
45964                            body: JSON.stringify({
45965                                ua: navigator.userAgent
45966                            })
45967                        }).then(function (oResponse) {
45968                            localStorage.setItem(sA2hsLogKey, sManifestName);
45969                        });
45970                    }
45971                }
45972            }
45973        }
45974
45975        var sUserAgent = (navigator.userAgent || '').toLowerCase();
45976        var sClientWebView = ((sUserAgent.indexOf('android') !== -1 && sUserAgent.indexOf('wv') !== -1)
45977            || sUserAgent.indexOf('cafe24plus') !== -1)
45978            ? 'T'
45979            : 'F';
45980
45981        // 서비스워커 설치 검증
45982        var bIsWebView = getFrontendConfig('IS_WEB_VIEW') === 'T' || sClientWebView === 'T';
45983        var oRegistrationPromise = navigator.serviceWorker.getRegistration('/');
45984        if (!oRegistrationPromise) {
45985            return;
45986        }
45987
45988        oRegistrationPromise.then(function (oSWRegistration) {
45989            var bInstallable = true;
45990            // 등록된 서비스워커가 있을 경우, Cafe24 서비스워커인지 확인
45991            if (oSWRegistration) {
45992                var oSW = oSWRegistration.installing || oSWRegistration.waiting || oSWRegistration.active;
45993                if (oSW && oSW.scriptURL.indexOf(sCafeSWName) === -1) {
45994                    bInstallable = false;
45995                } else if (bIsWebView === true) {
45996                    // cafe24 서비스워커면서 웹뷰 접근일 경우 서비스워커 삭제 (크롬 75.0.3770.67 버전 대응)
45997                    return oSWRegistration.unregister().then(function () {
45998                        return false;
45999                    }).catch(function (oError) {
46000                        if (window.EC_JET && EC_JET.message) {
46001                            EC_JET.message(oError, 'ServiceWorker');
46002                        }
46003                        console.warn('unregisterError => ', oError, oError.message, oError.name);
46004                        return false;
46005                    });
46006                }
46007            }
46008
46009            if (bIsWebView) {
46010                bInstallable = false;
46011            }
46012
46013            return bInstallable;
46014        })
46015        .then(function (bInstallable) {
46016            if (!bInstallable) {
46017                return;
46018            }
46019
46020            var sRevision = getFrontendConfig('FW_MANIFEST_CACHE_REVISION');
46021            if (sRevision) {
46022                sCafeSWName = sCafeSWName + '?v=' + sRevision;
46023            }
46024
46025            return navigator.serviceWorker.register(sCafeSWName, {
46026                scope: '/',
46027                updateViaCache: 'all'
46028            }).catch(function (oError) {
46029                if (window.EC_JET && EC_JET.message) {
46030                    EC_JET.message(oError, 'ServiceWorker');
46031                }
46032                console.warn('registerError => ', oError, oError.message, oError.name);
46033            });
46034        });
46035    });
46036}
46037
46038CAFE24.EXTERNAL_FRONT_APPSCRIPT = {
46039    insertAppScript: function() {
46040        if (typeof CAFE24.APPSCRIPT_ASSIGN_DATA !== "undefined" && Array.isArray(CAFE24.APPSCRIPT_ASSIGN_DATA)) {
46041            while (CAFE24.APPSCRIPT_ASSIGN_DATA.length > 0) {
46042                var oSrcData = CAFE24.APPSCRIPT_ASSIGN_DATA.pop();
46043                CAFE24.EXTERNAL_FRONT_APPSCRIPT.appendAppScript(oSrcData['src'], oSrcData['integrity']);
46044            }
46045        }
46046        if (typeof CAFE24.APPSCRIPT_SOURCE_DATA !== "undefined" && Array.isArray(CAFE24.APPSCRIPT_SOURCE_DATA)) {
46047            while (CAFE24.APPSCRIPT_SOURCE_DATA.length > 0) {
46048                CAFE24.EXTERNAL_FRONT_APPSCRIPT.appendSourceTypeScript(CAFE24.APPSCRIPT_SOURCE_DATA.pop());
46049            }
46050        }
46051    },
46052    appendAppScript: function(sSrc, sIntegrity) {
46053        var js = document.createElement('script');
46054        js.src = sSrc;
46055        // integrity 필드가 존재하는 경우 스크립트 무결성 체킹을 위해 추가.
46056        if (sIntegrity && sIntegrity !== null) {
46057            js.integrity = sIntegrity;
46058            js.crossOrigin = "anonymous";
46059        }
46060        document.body.appendChild(js);
46061    },
46062    appendSourceTypeScript: function (sSrc) {
46063        var js = document.createElement('script');
46064        js.type = 'text/javascript';
46065        js.text = CAFE24.EXTERNAL_FRONT_APPSCRIPT.base64Decode(sSrc);
46066        document.body.appendChild(js);
46067    },
46068    base64Decode: function (sEncoded) {
46069        return decodeURIComponent(atob(sEncoded).split('').map(function(c) {
46070            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
46071        }).join(''));
46072    }
46073};
46074if (document.readyState === 'complete') {
46075    CAFE24.EXTERNAL_FRONT_APPSCRIPT.insertAppScript();
46076} else if (window.addEventListener) {
46077    window.addEventListener('load', CAFE24.EXTERNAL_FRONT_APPSCRIPT.insertAppScript);
46078} else if (window.attachEvent) {
46079    window.attachEvent('onload', CAFE24.EXTERNAL_FRONT_APPSCRIPT.insertAppScript);
46080}
46081
46082var EC_EXTERNAL_FRONT_APPSCRIPT = CAFE24.getDeprecatedNamespace('EC_EXTERNAL_FRONT_APPSCRIPT');
46083
46084/**
46085 * SDK spec interface
46086 */
46087EC_EXTERNAL_UTIL_APP_SPECINTERFACE = {
46088
46089    oLoginProvider: {
46090        member_id: null,
46091        provider: null,
46092        client_id: null
46093    },
46094
46095    oCustomerProvider: {
46096        member_id: null,
46097        provider: null
46098    },
46099
46100    oMemberInfo: {
46101        member_id: null,
46102        group_no: null,
46103        guest_id: null
46104    },
46105
46106    oCustomerIDInfo: {
46107        member_id: null,
46108        guest_id: null
46109    },
46110
46111    oCustomerInfo: {
46112        member_id: null,
46113        name: null,
46114        nick_name: null,
46115        group_name: null,
46116        group_no: null,
46117        email: null,
46118        news_mail: null,
46119        phone: null,
46120        cellphone: null,
46121        sms: null,
46122        birthday: null,
46123        additional_information: null,
46124        authentication_method: null,
46125        created_date: null
46126    },
46127
46128    oDefaultShippingAddress: {
46129        shipping_alias: null,
46130        zip_code: null,
46131        address1: null,
46132        address2: null
46133    },
46134
46135    // @todo deprecated
46136    oMileageInfo: {
46137        available_mileage: null,
46138        returned_mileage: null,
46139        total_mileage: null,
46140        unavailable_mileage: null,
46141        used_mileage: null
46142    },
46143
46144    // @todo deprecated
46145    oDepositInfo: {
46146        all_deposit: null,
46147        member_total_deposit: null,
46148        refund_wait_deposit: null,
46149        total_deposit: null,
46150        used_deposit: null
46151    },
46152
46153    oPointInfo: {
46154        available_point: null,
46155        returned_point: null,
46156        total_point: null,
46157        unavailable_point: null,
46158        used_point: null
46159    },
46160
46161    oCreditInfo: {
46162        all_credit: null,
46163        member_total_credit: null,
46164        refund_wait_credit: null,
46165        total_credit: null,
46166        used_credit: null
46167    },
46168
46169    oCartList: {
46170        shop_no: null,
46171        product_no: null,
46172        additional_option: null,
46173        attached_file_option: null,
46174        basket_product_no: null,
46175        product_price: null,
46176        quantity: null,
46177        selected_product: null,
46178        variant_code: null,
46179        option_id: null,
46180        is_set_product: null,
46181        set_product_no: null,
46182        delvtype: null
46183    },
46184
46185    oCartInfo: {
46186        basket_price: null
46187    },
46188
46189    oCartItemList: {
46190        basket_product_no: null,
46191        product_no: null,
46192        price: null,
46193        option_price: null,
46194        quantity: null,
46195        discount_price: null,
46196        variant_code: null,
46197        product_weight: null,
46198        display_group: null,
46199        quantity_based_discount: null,
46200        non_quantity_based_discount: null,
46201        product_volume: null,
46202        additional_option_values: null,
46203        product_bundle: null,
46204        product_bundle_no: null,
46205        option_id: null,
46206        product_name: null,
46207        product_image: null,
46208        option_value: null,
46209        shipping_fee_type: null,
46210        categories: null
46211    },
46212
46213    oCount: {
46214        count: 0
46215    },
46216
46217    oShopInfo: {
46218        language_code: null,
46219        currency_code: null,
46220        timezone: null
46221    },
46222
46223    oAddedProductToCart : {
46224        shop_no: null,
46225        category_no: null,
46226        quantity: null,
46227        additional_option_value: null,
46228        variant_code: null,
46229        product_bundle: null,
46230        prefaid_shipping_fee: null,
46231        attached_file_option: null,
46232        created_date: null,
46233        product_price: null,
46234        option_price: null,
46235        product_bundle_price: null,
46236        product_no: null,
46237        option_id: null,
46238        product_bundle_no: null,
46239        shipping_type : null,
46240        subscription: null,
46241        subscription_cycle: null,
46242        subscription_shipments_cycle_count: null,
46243        basket_product_no: null,
46244        additional_option_values: null,
46245        product_name: null,
46246        checked_products : null,
46247        option_text : null
46248    },
46249
46250    oOrderItemList: {
46251        order_id: null,
46252        order_item_code: null,
46253        order_status: null
46254    },
46255
46256    oOrderDetailInfo: {
46257        shop_no: null,
46258        order_id: null,
46259        initial_order_amount: null,
46260        actual_order_amount: null,
46261        payment_method: null,
46262        order_date: null,
46263        first_payment_method: null,
46264        items: null
46265    },
46266
46267    oClaimableItemList: {
46268        order_id: null,
46269        item_no: null,
46270        order_item_code: null,
46271        variant_code: null,
46272        product_no: null,
46273        product_code: null,
46274        custom_product_code: null,
46275        custom_variant_code: null,
46276        option_id: null,
46277        quantity: null,
46278        price: null,
46279        order_status: null,
46280        supplier_code: null,
46281        supplier_name: null
46282    },
46283
46284    oPrecreateOrder : {
46285        products: null,
46286        hmac: null,
46287        response_time: null,
46288        order_id: null,
46289        return_notification_url: null,
46290        is_nointerest: null,
46291        nointerest_quota: null
46292    },
46293
46294    oPrecreateOrderProduct : {
46295        shop_no: null,
46296        category_no: null,
46297        quantity: null,
46298        additional_option_values: null,
46299        variant_code: null,
46300        product_bundle: null,
46301        prefaid_shipping_fee: null,
46302        attached_file_option: null,
46303        created_date: null,
46304        product_price: null,
46305        option_price: null,
46306        product_bundle_price: null,
46307        product_no: null,
46308        option_id: null,
46309        product_bundle_no: null,
46310        shipping_type : null,
46311        subscription: null,
46312        subscription_cycle: null,
46313        subscription_shipments_cycle_count: null,
46314        basket_product_no: null,
46315        product_name: null,
46316        checked_products : null,
46317        option_text : null,
46318        product_bundle_list: null
46319    },
46320
46321    oBatchBasketAddItem : {
46322        product_no: null,
46323        variants_code: null,
46324        quantity: null,
46325        options: null,
46326        additional_option_values: null
46327    },
46328
46329    oBatchBasketAddSetItem : {
46330        product_no: null,
46331        variants_code: null,
46332        quantity: null,
46333        bundle_product_components: null
46334    }
46335};
46336
46337/**
46338 * 비동기식 데이터 - App Common ( 앱 공통정보 )
46339 */
46340CAPP_ASYNC_METHODS.aDatasetList.push('AppCommon');
46341CAPP_ASYNC_METHODS.AppCommon = {
46342
46343    STORAGE_KEY: 'AppCommon_' + CAFE24.SDE_SHOP_NUM,
46344
46345    __sGuestId: null,
46346
46347    isUse: function()
46348    {
46349        if (typeof CAFE24.APPSCRIPT_SDK_DATA !== "undefined" && EC$.inArray('application', CAFE24.APPSCRIPT_SDK_DATA) > -1) {
46350            return true;
46351        }
46352
46353        return false;
46354    },
46355
46356    restoreCache: function()
46357    {
46358        // sessionStorage 지원 여부 확인
46359        if (!window.sessionStorage) {
46360            return false;
46361        }
46362
46363        try {
46364            var aStorageData = JSON.parse(window.sessionStorage.getItem(this.STORAGE_KEY));
46365
46366            // expire 체크
46367            if (aStorageData.exp < Date.now()) {
46368                throw 'cache has expired.';
46369            }
46370
46371            // 데이터 체크
46372            if (typeof aStorageData.data.guest_id === 'undefined') {
46373                throw 'Invalid cache data.';
46374            }
46375
46376            // 데이터 복구
46377            this.__sGuestId = aStorageData.data.guest_id;
46378
46379            return true;
46380
46381        } catch (e) {
46382            // 복구 실패시 캐시 삭제
46383            this.removeCache();
46384            return false;
46385        }
46386    },
46387
46388    removeCache: function()
46389    {
46390        // sessionStorage 지원 여부 확인
46391        if (!window.sessionStorage) {
46392            return;
46393        }
46394        // 캐시 삭제
46395        window.sessionStorage.removeItem(this.STORAGE_KEY);
46396    },
46397
46398    setData: function(oData)
46399    {
46400        // sessionStorage 지원 여부 확인
46401        if (!window.sessionStorage) {
46402            return;
46403        }
46404
46405        this.__sGuestId = oData.guest_id || '';
46406
46407        try {
46408            sessionStorage.setItem(this.STORAGE_KEY, JSON.stringify({
46409                exp: Date.now() + (1000 * 60 * 10),
46410                data: this.getData()
46411            }));
46412        } catch (error) {
46413        }
46414    },
46415
46416    execute: function()
46417    {
46418    },
46419
46420    getData: function()
46421    {
46422        return {
46423            guest_id: this.__sGuestId
46424        };
46425    },
46426
46427    setSpecData: function(oSpec, oData) {
46428        var aData = {};
46429        for (var prop in oSpec) {
46430            if (oData.hasOwnProperty(prop) === true) {
46431                aData[prop] = oData[prop];
46432            } else {
46433                aData[prop] = oSpec[prop];
46434            }
46435        }
46436        return aData;
46437    },
46438
46439    setSpecDataMap: function(oSpec, oData, oMapData) {
46440        var aData = {};
46441        for (var prop in oSpec) {
46442            if (oData.hasOwnProperty(oMapData[prop]) === true) {
46443                aData[prop] = oData[oMapData[prop]];
46444            } else {
46445                aData[prop] = oSpec[prop];
46446            }
46447        }
46448        return aData;
46449    },
46450
46451    // sdk function list
46452    getMemberID: function()
46453    {
46454        return CAPP_ASYNC_METHODS.member.getData().member_id;
46455    },
46456
46457    getEncryptedMemberId: function(sClientId)
46458    {
46459        var sUrl = '/shop' + EC_SDE_SHOP_NUM + '/Api/Member/Encryptmemberid';
46460        var aParams = {
46461            'client_id': sClientId
46462        };
46463
46464        var aReturn = null;
46465        EC$.ajax({
46466            dataType: "json",
46467            type: "POST",
46468            url: sUrl,
46469            data: aParams,
46470            async: false,
46471
46472            success: function(response) {
46473                var sReturnCode = response.return_code;
46474                var aEncryptedId = response.result.member_id;
46475
46476                if (sReturnCode === '0000') {
46477                    aEncryptedId = '';
46478                }
46479
46480                aReturn = CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerIDInfo, {member_id: aEncryptedId});
46481            }
46482        });
46483        return aReturn;
46484    },
46485
46486    getLoginProvider: function()
46487    {
46488        var sCookieName = "login_provider_"+CAFE24.SDE_SHOP_NUM;
46489        var sLoginProvider = CAPP_ASYNC_METHODS._getCookie(sCookieName);
46490        if (sLoginProvider === null) {
46491            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oLoginProvider, EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oLoginProvider);
46492        }
46493
46494        var oLoginProvider = JSON.parse(decodeURIComponent(sLoginProvider));
46495        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oLoginProvider, oLoginProvider);
46496    },
46497
46498    getCustomerProvider: function()
46499    {
46500        if (CAPP_ASYNC_METHODS.IS_LOGIN !== true) {
46501            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerProvider, EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerProvider);
46502        }
46503
46504        if (typeof CAPP_ASYNC_METHODS.CustomerProvider.getData().member_id !== 'undefined') {
46505            if (CAPP_ASYNC_METHODS.CustomerProvider.getData().member_id !== null) {
46506                return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerProvider, CAPP_ASYNC_METHODS.CustomerProvider.getData());
46507            }
46508        }
46509
46510        var sUrl = EC_ROUTE.getPrefixUrl('/Api/Member/Customerprovider');
46511
46512        var oReturn = EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerProvider;
46513        EC$.ajax({
46514            dataType: "json",
46515            type: "GET",
46516            url: sUrl,
46517            async: false,
46518
46519            success: function(response) {
46520                var sReturnCode = response.return_code;
46521
46522                if (sReturnCode === '0000') {
46523                    return oReturn;
46524                }
46525                oReturn = response.result;
46526
46527                return oReturn;
46528            }
46529        });
46530        CAPP_ASYNC_METHODS.CustomerProvider.setData(oReturn);
46531        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerProvider, oReturn);
46532    },
46533
46534    getMemberInfo: function()
46535    {
46536        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
46537            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oMemberInfo, {group_no: CAPP_ASYNC_METHODS.member.getData().group_no, member_id: CAPP_ASYNC_METHODS.member.getData().member_id});
46538        } else {
46539            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oMemberInfo, {guest_id: CAPP_ASYNC_METHODS.AppCommon.getData().guest_id});
46540        }
46541    },
46542
46543    getCustomerIDInfo: function()
46544    {
46545        if (CAPP_ASYNC_METHODS.IS_LOGIN === true) {
46546            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerIDInfo, {member_id: CAPP_ASYNC_METHODS.member.getData().member_id});
46547        } else {
46548            return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerIDInfo, {guest_id: CAPP_ASYNC_METHODS.AppCommon.getData().guest_id});
46549        }
46550    },
46551
46552    getCustomerInfo: function()
46553    {
46554        var oMember = CAPP_ASYNC_METHODS.member.getData();
46555        if (oMember.created_date && typeof oMember.created_date === 'string') {
46556            oMember.created_date = oMember.created_date.replace(/(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}).+/, '$1');
46557        }
46558        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCustomerInfo, oMember);
46559    },
46560
46561    getDefaultShippingAddress: function()
46562    {
46563        var oData = CAPP_ASYNC_METHODS.DefaultShippingAddress.getData();
46564        if (oData === null) {
46565            return null;
46566        }
46567        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oDefaultShippingAddress, oData);
46568    },
46569
46570    // @todo deprecated
46571    getMileageInfo: function()
46572    {
46573        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oMileageInfo, CAPP_ASYNC_METHODS.Mileage.getData());
46574    },
46575
46576     // @todo deprecated
46577    getDepositInfo: function()
46578    {
46579        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oDepositInfo, CAPP_ASYNC_METHODS.Deposit.getData());
46580    },
46581
46582    getPointInfo: function()
46583    {
46584        var oMapData = {
46585            available_point: 'available_mileage',
46586            returned_point: 'returned_mileage',
46587            total_point: 'total_mileage',
46588            unavailable_point: 'unavailable_mileage',
46589            used_point: 'used_mileage'
46590        };
46591
46592        return this.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPointInfo, CAPP_ASYNC_METHODS.Mileage.getData(), oMap
46592Data);
46593    },
46594
46595    getCreditInfo: function()
46596    {
46597        var oMapData = {
46598            all_credit: 'all_deposit',
46599            member_total_credit: 'member_total_deposit',
46600            refund_wait_credit: 'refund_wait_deposit',
46601            total_credit: 'total_deposit',
46602            used_credit: 'used_deposit'
46603        };
46604
46605        return this.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCreditInfo, CAPP_ASYNC_METHODS.Deposit.getData(), oMapData);
46606    },
46607
46608    getCartList: function()
46609    {
46610        var oCartList = EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCartList;
46611        var aCartList = [];
46612        return new Promise(function (resolve, reject) {
46613            CAPP_ASYNC_METHODS.BasketProduct.getData().then(function(oData) {
46614                for (var iKey in oData) {
46615                    aCartList.push(CAPP_ASYNC_METHODS.AppCommon.setSpecData(oCartList, oData[iKey]));
46616                }
46617                resolve(aCartList);
46618            }).catch(function(data) {
46619                reject(data);
46620            });
46621        });
46622    },
46623
46624    getCartInfo: function()
46625    {
46626        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCartInfo, CAPP_ASYNC_METHODS.Basketprice.getData());
46627    },
46628
46629    getCartItemList: function()
46630    {
46631        var aCartItemList = [];
46632        if (typeof aBasketProductData === "undefined" && typeof aBasketProductOrderData === "undefined") {
46633            return aCartItemList;
46634        }
46635
46636        //aBasketProductOrderData : 주문서
46637        //aBasketProductData : 장바구니
46638        var aData = (typeof aBasketProductOrderData !== "undefined") ? aBasketProductOrderData : aBasketProductData;
46639
46640        var oMapData = {
46641            basket_product_no: 'basket_prd_no',
46642            product_no: 'product_no',
46643            price: 'product_price',
46644            option_price: 'opt_price',
46645            quantity: 'product_qty',
46646            discount_price: 'product_sale_price',
46647            variant_code: 'item_code',
46648            product_weight: 'product_weight',
46649            display_group: 'main_cate_no',
46650            quantity_based_discount: 'add_sale_related_qty',
46651            non_quantity_based_discount: 'add_sale_not_related_qty',
46652            product_volume: 'volume_size_serial',
46653            product_bundle: 'is_set_product',
46654            product_bundle_no: 'set_product_no',
46655            option_id: 'opt_id',
46656            product_name: 'product_name',
46657            product_image: 'product_image', //tiny 작은목록이미지
46658            option_value: 'option_str',
46659            shipping_fee_type : 'shipping_fee_type',
46660            categories: 'categories'
46661        };
46662
46663        var idx = 0;
46664        var iOldBpPrdNo = null;
46665        var iNewBpPrdNo = null;
46666        for (var iKey in aData) {
46667            if (typeof aData[iKey].basket_prd_no === "undefined" || aData[iKey].basket_prd_no === null) {
46668                continue;
46669            }
46670            iNewBpPrdNo = aData[iKey].basket_prd_no;
46671            if (iOldBpPrdNo !== iNewBpPrdNo) {
46672                aCartItemList[idx] = this.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCartItemList, aData[iKey], oMapData);
46673
46674                if (aCartItemList[idx]['product_volume'] !== '' && aCartItemList[idx]['product_volume'] !== null && aCartItemList[idx]['product_volume'] !== undefined) {
46675                    var aProductVolume = aCartItemList[idx]['product_volume'].split('|');
46676                    aCartItemList[idx]['product_volume'] = {
46677                        'product_width': parseFloat(aProductVolume[0]),
46678                        'product_height': parseFloat(aProductVolume[1]),
46679                        'product_length': parseFloat(aProductVolume[2]),
46680                    };
46681                } else {
46682                    aCartItemList[idx]['product_volume'] = {
46683                        'product_width': null,
46684                        'product_height': null,
46685                        'product_length': null,
46686                    };
46687                }
46688
46689                if (aCartItemList[idx]['product_bundle_no'] == '0') { //세트상품번호 기본값 null 로 노출되도록
46690                    aCartItemList[idx]['product_bundle_no'] = null;
46691                }
46692
46693                if (aCartItemList[idx]['product_image'] == '') {
46694                    aCartItemList[idx]['product_image'] = null;
46695                }
46696
46697                if (aCartItemList[idx]['option_value'] !== null && aCartItemList[idx]['option_value'].length < 1) {
46698                    aCartItemList[idx]['option_value'] = null;
46699                }
46700
46701                if (aData[iKey].custom_data != null) {
46702                    aCartItemList[idx]['additional_option_values'] = [];
46703                    aCartItemList[idx]['additional_option_values'].push(aData[iKey].custom_data);
46704                }
46705                idx++;
46706
46707            } else {
46708                aCartItemList[idx - 1]['quantity'] += aData[iKey].product_qty;
46709
46710                if (aData[iKey].custom_data != null) {
46711                    aCartItemList[idx - 1]['additional_option_values'].push(aData[iKey].custom_data);
46712                }
46713            }
46714
46715            iOldBpPrdNo = iNewBpPrdNo;
46716        }
46717
46718        return aCartItemList;
46719    },
46720
46721    getCartCount: function()
46722    {
46723        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCount, CAPP_ASYNC_METHODS.Basketcnt.getData());
46724    },
46725
46726    getCouponCount: function()
46727    {
46728        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCount, CAPP_ASYNC_METHODS.Couponcnt.getData());
46729    },
46730
46731    getWishCount: function()
46732    {
46733        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oCount, CAPP_ASYNC_METHODS.Wishcount.getData());
46734    },
46735
46736    getShopInfo: function()
46737    {
46738        return this.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oShopInfo, {language_code: SHOP.getLanguage(), currency_code: SHOP.getCurrency(), timezone: SHOP.getTimezone()});
46739    },
46740
46741    getCartMapData : function () {
46742        var oMapData = {
46743            shop_no: 'shop_no',
46744            category_no: 'main_cate_no',
46745            quantity: 'quantity',
46746            additional_option_value: 'option_add',
46747            variant_code: 'item_code',
46748            product_bundle: 'is_set_product',
46749            prefaid_shipping_fee: 'prd_detail_ship_type',
46750            attached_file_option: 'option_attached_file_info_json',
46751            created_date: 'ins_timestamp',
46752            product_price: 'product_price',
46753            option_price: 'opt_price',
46754            product_bundle_price: 'set_discount_price',
46755            product_no: 'product_no',
46756            option_id: 'opt_id',
46757            product_bundle_no: 'set_product_no',
46758            shipping_type : 'delvtype',
46759            subscription: 'is_subscription',
46760            subscription_shipments_cycle : 'subscription_cycle',
46761            subscription_shipments_cycle_count: 'subscription_cycle_count',
46762            basket_product_no: 'basket_prd_no',
46763            additional_option_values: 'custom_data',
46764            product_name: 'product_name',
46765            checked_products : 'is_prd',
46766            option_text: 'opt_str',
46767            product_bundle_list: 'product_bundle_list'
46768        };
46769        return oMapData;
46770    },
46771
46772    getPrecreateOrderMapData : function () {
46773        var oMapData = {
46774            products: 'products',
46775            hmac: 'hmac',
46776            response_time: 'response_time',
46777            order_id: 'order_id',
46778            return_notification_url: 'return_noty_url',
46779            is_nointerest: 'nointerest',
46780            nointerest_quota: 'nointerestQuota'
46781        };
46782
46783        return oMapData;
46784    },
46785
46786    addCurrentProductToCart: function(mall_id, request_time, app_key, member_id, hmac, isOrderPurpose = 'F', request_data_json = null)
46787    {
46788        if (isOrderPurpose !== 'T') {
46789            isOrderPurpose = 'F';
46790        }
46791
46792        return new Promise(function (resolve, reject) {
46793            new Promise(function (res, rej) {
46794                var aInfo = {
46795                    mall_id: mall_id,
46796                    request_time: request_time,
46797                    app_key: app_key,
46798                    request_member_id: member_id,
46799                    hmac: hmac,
46800                    isOrderPurpose: isOrderPurpose,
46801                    request_data_json: request_data_json
46802                };
46803
46804                var proc = (typeof(set_option_data) === 'undefined') ? product_submit : product_set_submit;
46805                if(proc === 'undefined') reject();
46806               
46807                var procResult = proc('app', '/exec/front/order/basket/', null, aInfo, res);
46808                if (procResult && procResult.result === false) reject(procResult);
46809
46810            }).then(function (data) {
46811                var oMapData =  CAPP_ASYNC_METHODS.AppCommon.getCartMapData();
46812                var aCurrentProductToCartResult = [];
46813                for (var index in data) {
46814                    aCurrentProductToCartResult[index] = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oAddedProductToCart, data[index], oMapData);
46815                }
46816                resolve(aCurrentProductToCartResult);
46817            }).catch(function (data) {
46818                reject(data);
46819            })
46820        });
46821    },
46822
46823    precreateOrder: function(mall_id, request_time, app_key, member_id, hmac)
46824    {
46825        var self = this;
46826        return new Promise(function (resolve, reject) {
46827            var aInfo = {
46828                mall_id: mall_id,
46829                request_time: request_time,
46830                app_key: app_key,
46831                member_id: member_id,
46832                hmac: hmac,
46833                shipping_type : (typeof(delvtype) == "undefined") ? sBasketDelvType : delvtype
46834            };
46835            
46836            self.handleBasketOrCart(mall_id, request_time, app_key, member_id, hmac, null, aInfo).then(function () {
46837                EC$.post('/exec/front/order/reserve/', aInfo, function(data) {
46838
46839                    if (data['result'] == false) {
46840                        reject(data);
46841                    }
46842
46843                    var oPrecreateOrderMapData = CAPP_ASYNC_METHODS.AppCommon.getPrecreateOrderMapData();
46844                    var oOrderProductMapData =  CAPP_ASYNC_METHODS.AppCommon.getCartMapData();
46845                    var aPrecreateOrderResult = [];
46846
46847                    var aSpecData = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrder, data, oPrecreateOrderMapData);
46848
46849                    for (var key in aSpecData) {
46850                        aPrecreateOrderResult[key] = aSpecData[key];
46851                    }
46852
46853                    var prodList = data['products'];
46854                    for (var index in prodList) {
46855                        // temp, amazon, paypal 다 걷어내면 없앨코드
46856                        aPrecreateOrderResult[index] = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrderProduct, prodList[index], oOrderProductMapData);
46857                        aPrecreateOrderResult['products'][index] = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrderProduct, prodList[index], oOrderProductMapData);
46858                    }
46859
46860                    resolve(aPrecreateOrderResult);
46861                }, 'json');
46862            }).catch(function (data) {
46863                reject(data);
46864            })
46865        });
46866    },
46867
46868    calculatePayment: function(mall_id, request_time, app_key, member_id, request_data_json, hmac) // 결제예정금액 계산
46869    {
46870        // request_data_json : mobile, member_id, shipping_type, payment_method, country_code, carrier_id, zipcode, address_full, address_state, points_spent_amount, order_coupons, items
46871        var aRequestData = this.parseRequestDataJson(request_data_json);
46872
46873        var self = this;
46874        return new Promise(function (resolve, reject) {
46875            var aInfo = self.createApiRequestInfo(mall_id, request_time, app_key, member_id, request_data_json, hmac, aRequestData);
46876
46877            self.handleBasketOrCart(mall_id, request_time, app_key, member_id, hmac, request_data_json, aInfo).then(function (addedCartItems) {
46878                EC$.post('/exec/front/order/Calculationcreate/', aInfo, function(data) {
46879                    if (data['result'] === false) {
46880                        reject(data);
46881                    }
46882
46883                    data['added_cart_items'] = addedCartItems || []; //장바구니에 추가된 품목 정보 (addCurrentProductToCart result)
46884                    resolve(data);
46885                }, 'json');
46886            }).catch(function (data) {
46887                reject(data);
46888            })
46889        });
46890    },
46891
46892    /**
46893     * ECHOSTING-608244
46894     * 결제예약 요청 실패 응답을 { code, message } 형태로 정규화한다.
46895     * 응답 본문이 JSON 이 아니거나 비어 있어도 항상 객체를 돌려주어 콜백 미호출을 막는다.
46896     *
46897     * @param {object} oXhr jqXHR
46898     * @returns {{code: number, message: string}}
46899     */
46900    parseReserveErrorResponse: function (oXhr)
46901    {
46902        var oFallback = { code: 422, message: 'Failed to create a preliminary order.' };
46903
46904        if (!oXhr) {
46905            return oFallback;
46906        }
46907
46908        if (oXhr.responseJSON && oXhr.responseJSON.message) {
46909            return { code: 422, message: oXhr.responseJSON.message };
46910        }
46911
46912        return oFallback;
46913    },
46914
46915    precreateOrderV2: function(mall_id, request_time, app_key, member_id, request_data_json, hmac) // 결제예약 V2
46916    {
46917        // request_data_json : mobile, member_id, shipping_type, payment_method, country_code, carrier_id, zipcode, address_full, address_state, points_spent_amount, order_coupons, items
46918        var aRequestData = this.parseRequestDataJson(request_data_json);
46919
46920        var self = this;
46921        return new Promise(function (resolve, reject) {
46922            var aInfo = self.createApiRequestInfo(mall_id, request_time, app_key, member_id, request_data_json, hmac, aRequestData);
46923            
46924            self.handleBasketOrCart(mall_id, request_time, app_key, member_id, hmac, request_data_json, aInfo).then(function () {
46925                // ECHOSTING-608244 : 서버가 precreateOrderV2 호출임을 식별하기 위한 내부 마커
46926                aInfo['sdk_version'] = 'v2';
46927
46928                EC$.post('/exec/front/order/reserve/', aInfo, function(data) {
46929
46930                    if (data['result'] == false) {
46931                        reject(data);
46932                        // ECHOSTING-608244 : reject 후에도 아래 매핑이 계속 실행되던 결함 교정
46933                        return;
46934                    }
46935
46936                    var oPrecreateOrderMapData = CAPP_ASYNC_METHODS.AppCommon.getPre
46936createOrderMapData();
46937                    var oOrderProductMapData =  CAPP_ASYNC_METHODS.AppCommon.getCartMapData();
46938                    var aPrecreateOrderResult = [];
46939
46940                    var aSpecData = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrder, data, oPrecreateOrderMapData);
46941
46942                    for (var key in aSpecData) {
46943                        aPrecreateOrderResult[key] = aSpecData[key];
46944                    }
46945
46946                    var prodList = data['products'];
46947                    for (var index in prodList) {
46948                        // temp, amazon, paypal 다 걷어내면 없앨코드
46949                        aPrecreateOrderResult[index] = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrderProduct, prodList[index], oOrderProductMapData);
46950                        aPrecreateOrderResult['products'][index] = CAPP_ASYNC_METHODS.AppCommon.setSpecDataMap(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oPrecreateOrderProduct, prodList[index], oOrderProductMapData);
46951                    }
46952
46953                    resolve(aPrecreateOrderResult);
46954                }, 'json').fail(function (oXhr) {
46955                    // ECHOSTING-608244 : 네트워크 오류·타임아웃·JSON 파싱 실패에도 반드시 콜백이 불리도록 한다.
46956                    reject(CAPP_ASYNC_METHODS.AppCommon.parseReserveErrorResponse(oXhr));
46957                });
46958            }).catch(function (data) {
46959                reject(data);
46960            })
46961        });
46962    },
46963
46964    getOrderItemList: function(start_date, end_date, order_status, page, count, order_id)
46965    {
46966        count = count === null ? iOrderHistoryLimit : count;
46967        return new Promise(function (resolve, reject) {
46968            if (start_date || end_date || order_status || order_id || page || count != iOrderHistoryLimit ) { //기본조회값과 조건이 다른경우 새롭게 갱신
46969                CAPP_ASYNC_METHODS.OrderHistoryItemList.getAsyncData(start_date, end_date, order_status, page, count, order_id)
46970                    .then(function(oData) {
46971                        resolve(oData);
46972                    }).catch(function(data) {
46973                        reject(data);
46974                    });
46975            } else {
46976                var oData = CAPP_ASYNC_METHODS.OrderHistoryItemList.getData();
46977
46978                // 주문조회페이지에서만 로딩시 페이지 리로드후 반영됨
46979                // async.js 호출과 sdk호출이 순차적이지 않아서 세션스토리지에 데이터를 못가져오는 경우가 발생하여 데이터가 없는경우 async한번더 호출 하도록 수정
46980                if (oData) {
46981                    var oOrderItemList = EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oOrderItemList;
46982                    var aOrderHistoryItemList = [];
46983
46984                    for (var iKey in oData) {
46985                        aOrderHistoryItemList.push(CAPP_ASYNC_METHODS.AppCommon.setSpecData(oOrderItemList, oData[iKey]));
46986                    }
46987                    resolve(aOrderHistoryItemList);
46988                } else {
46989                    CAPP_ASYNC_METHODS.OrderHistoryItemList.getAsyncData(start_date, end_date, order_status, page, count, order_id)
46990                        .then(function(oData) {
46991                            resolve(oData);
46992                        }).catch(function(data) {
46993                            reject(data);
46994                    });
46995                }
46996            }
46997        });
46998    },
46999
47000    getOrderDetailInfo: function (shop_no, order_id) {
47001        return new Promise(function (resolve, reject) {
47002            var oData = CAPP_ASYNC_METHODS.OrderDetailInfo.getData();
47003            if (oData[0] != null) {
47004                for (var iKey in oData){
47005                    if (oData[iKey].order_id == order_id){
47006                        var oOrderDetailInfo = EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oOrderDetailInfo;
47007                        var aOrderDetailInfo = [];
47008
47009                        for (var iKey in oData) {
47010                            aOrderDetailInfo.push(CAPP_ASYNC_METHODS.AppCommon.setSpecData(oOrderDetailInfo, oData[iKey]));
47011                        }
47012                        resolve(aOrderDetailInfo);
47013                    } else {
47014                        CAPP_ASYNC_METHODS.OrderDetailInfo.getAsyncData(shop_no, order_id)
47015                            .then(function (oData) {
47016                                resolve(oData);
47017                            }).catch(function () {
47018                            reject(oData);
47019                        });
47020                    }
47021                }
47022            } else {
47023                CAPP_ASYNC_METHODS.OrderDetailInfo.getAsyncData(shop_no, order_id)
47024                    .then(function (oData) {
47025                        resolve(oData);
47026                    }).catch(function () {
47027                    reject(oData);
47028                });
47029            }
47030        });
47031    },
47032
47033    getClaimableItemList: function (order_id, customer_service_type) {
47034        return new Promise(function (resolve, reject) {
47035            var orderPattern = /^[0-9]{8}-[0-9]{7}$/;
47036
47037            if (order_id !== null && orderPattern.test(order_id) === false) {
47038                reject({code: 422, message: 'order_id is not val
47038id'});
47039            }
47040            if (customer_service_type !== null && $.inArray(customer_service_type, ['C','E','R']) === -1) {
47041                reject({code: 422, message: 'customer_service_type is not valid'});
47042            }
47043            var oData = CAPP_ASYNC_METHODS.ClaimableItemList.getData();
47044            if (oData) {
47045                if (oData[0].order_id === order_id) {
47046                    var oClaimableItemList = EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oClaimableItemList;
47047                    var aClaimableItemList = [];
47048
47049                    for (var iKey in oData) {
47050                        aClaimableItemList.push(CAPP_ASYNC_METHODS.AppCommon.setSpecData(oClaimableItemList, oData[iKey]));
47051                    }
47052                    resolve(aClaimableItemList);
47053                } else {
47054                    CAPP_ASYNC_METHODS.ClaimableItemList.getAsyncData(order_id, customer_service_type)
47055                        .then(function (oData) {
47056                            resolve(oData);
47057                        }).catch(function (oData) {
47058                            reject(oData);
47059                    });
47060                }
47061            } else {
47062                CAPP_ASYNC_METHODS.ClaimableItemList.getAsyncData(order_id, customer_service_type)
47063                    .then(function (oData) {
47064                        resolve(oData);
47065                    }).catch(function (oData) {
47066                        reject(oData);
47067                });
47068            }
47069        });
47070    },
47071
47072    emptyCart: function (basket_shipping_type) {
47073        return new Promise(function (resolve, reject) {
47074            if (basket_shipping_type !== null && EC$.inArray(basket_shipping_type, ['A', 'B']) === -1) {
47075                reject({code: 422, message: '"basket_shipping_type" must be provided as one of "A, B".'});
47076                return;
47077            }
47078
47079            CAPP_ASYNC_METHODS.BasketProduct.deleteAllAsyncData(basket_shipping_type).then(function (oData) {
47080                if (oData.result < 0) {
47081                    reject({code: 500, message: 'Empty shopping cart failed.'});
47082                } else {
47083                    resolve('success');
47084                }
47085            }).catch(function () {
47086                reject({code: 500, message: 'Empty shopping cart failed.'});
47087            });
47088        });
47089    },
47090
47091    deleteCartItems: function (basket_shipping_type, product_list) {
47092        return new Promise(function (resolve, reject) {
47093            // 1) basket_shipping_type 유효성
47094            if (EC$.inArray(basket_shipping_type, ['A', 'B']) === -1) {
47095                reject({code: 422, message: '"basket_shipping_type" must be provided as one of "A, B".'});
47096                return;
47097            }
47098
47099            // 2) product_list 유효성
47100            if (!EC$.isArray(product_list) || product_list.length < 1) {
47101                reject({code: 422, message: '"product_list" is not valid.'});
47102                return;
47103            }
47104            for (var idx in product_list) {
47105                if (product_list[idx] === null || product_list[idx] === undefined) {
47106                    reject({code: 422, message: '"product_list" is not valid.'});
47107                    return;
47108                }
47109            }
47110
47111            CAPP_ASYNC_METHODS.BasketProduct.deleteCartItems(basket_shipping_type, product_list).then(function (oData) {
47112                if (oData.result < 0) {
47113                    reject({code: 500, message: 'Delete Cart Items failed.'});
47114                } else {
47115                    resolve(oData);
47116                }
47117            }).catch(function () {
47118                reject({code: 500, message: 'Delete Cart Items failed.'});
47119            });
47120        });
47121    },
47122
47123    addCart: function (basket_type, prepaid_shipping_fee, product_list) {
47124        return new Promise(function (resolve, reject) {
47125            ////////////////////// 입력값 valid 체크 //////////////////////
47126            if (product_list.length > 10) {
47127                reject({code: 422, message: 'The maximum number of "product_list" has been exceeded. (Maximum number of requests: 10)'});
47128                return;
47129            }
47130            // 1) basket_type valid 체크
47131            if (basket_type !== null && EC$.inArray(basket_type, ['A0000', 'A0001']) === -1) {
47132                reject({code: 422, message: '"basket_type" must be provided as one of "A0000 : General, A0001 : Interest-free".'});
47133                return;
47134            }
47135
47136            // 2) prepaid_shipping_fee 체크
47137            if (prepaid_shipping_fee !== null && EC$.inArray(prepaid_shipping_fee, ['P','C']) === -1) {
47138                reject({code: 422, message: '"prepaid_shipping_fee" should be provided as one of "P : Prepaid, C : Collected".'});
47139                return;
47140            }
47141
47142            var errorProductMapping = {}; // 실패데이터 세팅
47143            var aProductListRequest = []; // 실제 장바구니 exec 에 요청할 상품파라미터
47144
47145            // 3) product_list 유효성 체크
47146            for (var i in product_list) {
47147                var sInvalidField = ''; // 유효하지 않은 필드
47148
47149                if (isNaN(product_list[i]['product_no']) || product_list[i]['product_no'] < 1) {
47150                    sInvalidField = 'product_no';
47151                } else if (isNaN(product_list[i]['quantity']) || product_list[i]['quantity'] < 1) {
47152                    sInvalidField = 'quantity';
47153                } else if (/^P.{11}$/.test(product_list[i]['variants_code']) === false) {
47154                    sInvalidField = 'variants_code';
47155                } else if (Array.isArray(product_list[i]['additional_option_values'])) {
47156                    for (var j in product_list[i]['additional_option_values']) {
47157                        if (product_list[i]['additional_option_values'][j]['key'] != 'item_option_add') {
47158                            sInvalidField = 'additional_option_values.key';
47159                            break;
47160                        }
47161
47162                        if (product_list[i]['additional_option_values'][j]['type'] != 'text') {
47163                            sInvalidField = 'additional_option_values.type';
47164                            break;
47165                        }
47166                    }
47167                }
47168
47169                // 유효하지 않은 필드가 있는 경우
47170                if (sInvalidField !== '') {
47171                    if (errorProductMapping[sprintf('%s is not valid', sInvalidField)] === undefined) {
47172                        errorProductMapping[sprintf('%s is not valid', sInvalidField)] = [];
47173                    }
47174
47175                    errorProductMapping[sprintf('%s is not valid', sInvalidField)].push(
47176                        CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddItem, product_list[i])
47177                    );
47178                } else {
47179                    aProductListRequest.push(product_list[i]); // 파라미터 유효성을 통과한 요청데이터만 장바구니 exec 진행
47180                }
47181            }
47182            ////////////////////// 입력값 valid 체크 //////////////////////
47183
47184            // 장바구니 담기 exec 요청데이터
47185            var addCartParam = CAPP_ASYNC_METHODS.AppCommon.getAddCartParam(basket_type, prepaid_shipping_fee, aProductListRequest);
47186
47187            if (addCartParam.batch_add_item.length === 0) { // 파라미터 valid 체크 이후, 장바구니 insert 할 데이터가 없는 경우
47188                var aResponse = {}; // sdk 응답값
47189
47190                // 실패 데이터 (message, more_info) 세팅
47191                for (let error_message of Object.keys(errorProductMapping)) {
47192                    if (aResponse['errors'] === undefined) {
47193                        aResponse['errors'] = [];
47194                    }
47195                    aResponse['errors'].push({code: 422, message: error_message, more_info: errorProductMapping[error_message]});
47196                }
47197
47198                resolve(aResponse);
47199            }
47200
47201            CAPP_ASYNC_METHODS.BasketProduct.setAsyncData(addCartParam).then(function (oData) {
47202                var aResponse = {}; // sdk 응답값
47203
47204                if (oData.result.code === 0) { // 장바구니 담기 성공
47205                    if (oData.aBatchAddResult.success !== undefined) {
47206                        aResponse['cart'] = [];
47207                        oData.aBatchAddResult.success.forEach(function (successData) {
47208                            aResponse['cart'].push(
47209                                CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddItem, successData)
47210                            );
47211                        });
47212                    }
47213
47214                    if (oData.aBatchAddResult.fail !== undefined) {
47215                        // 장바구니 exec 이후 실패한 데이터는 아래에서 failMapping 에 등록
47216                        oData.aBatchAddResult.fail.forEach(function (failData) {
47217                            var errMsg = failData.errMsg ? failData.errMsg : 'Failed to add the product to the cart';
47218                            if (errorProductMapping[errMsg] === undefined) {
47219                                errorProductMapping[errMsg] = [];
47220                            }
47221
47222                            errorProductMapping[errMsg].push(
47223                                CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddItem, failData)
47224                            );
47225                        });
47226                    }
47227
47228                    // 실패 데이터 (message, more_info) 세팅
47229                    for (let error_message of Object.keys(errorProductMapping)) {
47230                        if (aResponse['errors'] === undefined) {
47231                            aResponse['errors'] = [];
47232                        }
47233                        aResponse['errors'].push({code: 422, message: error_message, more_info: errorProductMapping[error_message]});
47234                    }
47235
47236                    resolve(aResponse);
47237                } else { // 장바구니 담기 전체 실패
47238                    const errorMessage = oData.result === -998
47239                        ? 'You can add up to 400 items to the cart.'
47240                        : 'Failed to add the product to the cart';
47241
47242                    reject({code: 422, message: errorMessage});
47243                }
47244            }).catch(function () {
47245                reject({code: 422, message: 'Failed to add the product to the cart'});
47246            });
47247        });
47248    },
47249    addBundleProductsCart: function (basket_type, prepaid_shipping_fee, product_list) {
47250        return new Promise(function (resolve, reject) {
47251            ////////////////////// 입력값 valid 체크 //////////////////////
47252            if (product_list.length > 10) {
47253                reject({code: 422, message: 'The maximum number of "product_list" has been exceeded. (Maximum number of requests: 10)'});
47254                return;
47255            }
47256            // 1) basket_type valid 체크
47257            if (basket_type !== null && EC$.inArray(basket_type, ['A0000', 'A0001']) === -1) {
47258                reject({code: 422, message: '"basket_type" must be provided as one of "A0000 : General, A0001 : Interest-free".'});
47259                return;
47260            }
47261
47262            // 2) prepaid_shipping_fee 체크
47263            if (prepaid_shipping_fee !== null && EC$.inArray(prepaid_shipping_fee, ['P','C']) === -1) {
47264                reject({code: 422, message: '"prepaid_shipping_fee" should be provided as one of "P : Prepaid, C : Collected".'});
47265                return;
47266            }
47267
47268            var errorProductMapping = {}; // 실패데이터 세팅
47269            var aProductListRequest = []; // 실제 장바구니 exec 에 요청할 상품파라미터
47270
47271            // 3) aProductList 유효성 체크
47272            for (var i = 0; i < product_list.length; i++) {
47273                var sInvalidField = ''; // 유효하지 않은 필드
47274
47275                if (isNaN(product_list[i]['product_no']) || product_list[i]['product_no'] < 1) {
47276                    sInvalidField = 'product_no';
47277                } else if (isNaN(product_list[i]['quantity']) || product_list[i]['quantity'] < 1) {
47278                    sInvalidField = 'quantity';
47279                } else if (typeof product_list[i]['bundle_product_components'] == 'undefined') {
47280                    sInvalidField = 'bundle_product_components';
47281                }
47282
47283                if (Array.isArray(product_list[i]['bundle_product_components'])) {
47284                    if (product_list[i]['bundle_product_components'].length < 1) {
47285                        sInvalidField = 'bundle_product_components';
47286                    }
47287
47288                    for (var j = 0; j < product_list[i]['bundle_product_components'].length; j++) {
47289                        if (Array.isArray(product_list[i]['bundle_product_components'][j]['additional_option_values'])) {
47290                            for (var k = 0; k < product_list[i]['bundle_product_components'][j]['additional_option_values'].length; k++) {
47291                                if (product_list[i]['bundle_product_components'][j]['additional_option_values'][k]['key'] != 'item_option_add') {
47292                                    sInvalidField = 'bundle_product_components.additional_option_values.key';
47293                                    break;
47294                                }
47295
47296                                if (product_list[i]['bundle_product_components'][j]['additional_option_values'][k]['type'] != 'text') {
47297                                    sInvalidField = 'bundle_product_components.additional_option_values.type';
47298                                    break;
47299                                }
47300                            }
47301                        }
47302                    }
47303                }
47304
47305                // 유효하지 않은 필드가 있는 경우
47306                if (sInvalidField !== '') {
47307                    if (errorProductMapping[sprintf('%s is not valid', sInvalidField)] === undefined) {
47308                        errorProductMapping[sprintf('%s is not valid', sInvalidField)] = [];
47309                    }
47310
47311                    errorProductMapping[sprintf('%s is not valid', sInvalidField)].push(
47312                        CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddSetItem, product_list[i])
47313                    );
47314                } else {
47315                    aProductListRequest.push(product_list[i]); // 파라미터 유효성을 통과한 요청데이터만 장바구니 exec 진행
47316                }
47317            }
47318            ////////////////////// 입력값 valid 체크 //////////////////////
47319
47320            // 장바구니 담기 exec 요청데이터
47321            var addCartParam = CAPP_ASYNC_METHODS.AppCommon.getAddSetProductCartParam(basket_type, prepaid_shipping_fee, aProductListRequest);
47322
47323            if (addCartParam.batch_add_item.length === 0) { // 파라미터 valid 체크 이후, 장바구니 insert 할 데이터가 없는 경우
47324                var aResponse = {}; // sdk 응답값
47325
47326                // 실패 데이터 (message, more_info) 세팅
47327                for (let error_message of Object.keys(errorProductMapping)) {
47328                    if (aResponse['errors'] === undefined) {
47329                        aResponse['errors'] = [];
47330                    }
47331                    aResponse['errors'].push({code: 422, message: error_message, more_info: errorProductMapping[error_message]});
47332                }
47333
47334                resolve(aResponse);
47335            }
47336
47337            CAPP_ASYNC_METHODS.BasketProduct.setAsyncData(addCartParam).then(function (oData) {
47338                var aResponse = {}; // sdk 응답값
47339
47340                if (oData.result.code === 0) { // 장바구니 담기 성공
47341                    if (oData.aBatchAddResult.success !== undefined) {
47342                        aResponse['cart'] = [];
47343                        oData.aBatchAddResult.success.forEach(function (successData) {
47344                            aResponse['cart'].push(
47345                                CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddSetItem, successData)
47346                            );
47347                        });
47348                    }
47349
47350                    if (oData.aBatchAddResult.fail !== undefined) {
47351                        // 장바구니 exec 이후 실패한 데이터는 아래에서 failMapping 에 등록
47352                        oData.aBatchAddResult.fail.forEach(function (failData) {
47353                            var errMsg = failData.errMsg ? failData.errMsg : 'Failed to add the product to the cart';
47354                            if (errorProductMapping[errMsg] === undefined) {
47355                                errorProductMapping[errMsg] = [];
47356                            }
47357
47358                            errorProductMapping[errMsg].push(
47359                                CAPP_ASYNC_METHODS.AppCommon.setSpecData(EC_EXTERNAL_UTIL_APP_SPECINTERFACE.oBatchBasketAddSetItem, failData)
47360                            );
47361                        });
47362                    }
47363
47364                    // 실패 데이터 (message, more_info) 세팅
47365                    for (let error_message of Object.keys(errorProductMapping)) {
47366                        if (aResponse['errors'] === undefined) {
47367                            aResponse['errors'] = [];
47368                        }
47369                        aResponse['errors'].push({code: 422, message: error_message, more_info: errorProductMapping[error_message]});
47370                    }
47371
47372                    resolve(aResponse);
47373                } else { // 장바구니 담기 전체 실패
47374                    const errorMessage = oData.result === -998
47375                        ? 'You can add up to 400 items to the cart.'
47376                        : 'Failed to add the product to the cart';
47377
47378                    reject({code: 422, message: errorMessage});
47379                }
47380            }).catch(function () {
47381                reject({code: 422, message: 'Failed to add the product to the cart'});
47382            });
47383        });
47384    },
47385    getAddCartParam: function (basket_type, prepaid_shipping_fee, aProductList) {
47386        var aPostData = {
47387            'command': 'add',
47388            'basket_type': basket_type,
47389            'prd_detail_ship_type': prepaid_shipping_fee,
47390            'is_set_product': 'F',
47391            'batch_add_item': [] // 다수품목 대량 insert 필드
47392        };
47393
47394        for (var idx in aProductList) {
47395            aPostData['batch_add_item'].push({
47396                'product_no': aProductList[idx]['product_no'],
47397                'variants_code': aProductList[idx]['variants_code'],
47398                'quantity': aProductList[idx]['quantity'],
47399                'options': aProductList[idx]['options'], // 상품연동형 옵션정보
47400                'additional_option_values': aProductList[idx]['additional_option_values'] // 사용자 지정 옵션
47401            });
47402        }
47403
47404        return aPostData;
47405    },
47406    getAddSetProductCartParam: function (basket_type, prepaid_shipping_fee, aProductList) {
47407        var aPostData = {
47408            'command': 'add',
47409            'basket_type': basket_type,
47410            'prd_detail_ship_type': prepaid_shipping_fee,
47411            'is_set_product': 'T',
47412            'batch_add_item': [] // 다수품목 대량 insert 필드
47413        };
47414
47415        for (var idx in aProductList) {
47416            aPostData['batch_add_item'].push({
47417                'product_no': aProductList[idx]['product_no'],
47418                'quantity': aProductList[idx]['quantity'],
47419                'bundle_product_components': aProductList[idx]['bundle_product_components'] // 세트 구성 상품
47420            });
47421        }
47422
47423        return aPostData;
47424         },
47425
47426     /**
47427      * 주문 바스켓 페이지 여부 확인 (공통 함수)
47428      * @returns {boolean} ORDER_BASKET 페이지 여부
47429      */
47430     isOrderBasketPage: function() {
47431         const metaTag = document.querySelector('meta[name="path_role"]');
47432         return metaTag && metaTag.content === 'ORDER_BASKET';
47433     },
47434
47435     /**
47436      * JSON 파싱 처리 (공통 함수)
47437      * @param {string} request_data_json JSON 문자열
47438      * @returns {Array} 파싱된 배열 또는 빈 배열
47439      */
47440     parseRequestDataJson: function(request_data_json) {
47441         var aRequestData = [];
47442         if (request_data_json) { // 값이 있고
47443             try {
47444                 aRequestData = JSON.parse(request_data_json); // 파싱 시도
47445             } catch (e) {
47446                 console.error("JSON 파싱 실패:", e);
47447                 aRequestData = []; // 실패 시 기본값
47448             }
47449         } else {
47450             aRequestData = []; // 값이 없을 경우 기본값
47451         }
47452         return aRequestData;
47453     },
47454
47455     /**
47456      * shipping_type 설정 (공통 함수)
47457      * @param {Object} aRequestData 파싱된 요청 데이터
47458      * @returns {string} shipping_type
47459      */
47460     getShippingType: function(aRequestData) {
47461         let shipping_type;
47462         if (aRequestData.shipping_type) {
47463             shipping_type = aRequestData.shipping_type;
47464         } else if (typeof delvtype === "undefined") {
47465             shipping_type = sBasketDelvType;
47466         } else {
47467             shipping_type = delvtype;
47468         }
47469         return shipping_type;
47470     },
47471
47472     /**
47473      * API 요청 정보 객체 생성 (공통 함수)
47474      * @param {string} mall_id 쇼핑몰 ID
47475      * @param {string} request_time 요청 시간
47476      * @param {string} app_key 앱 키
47477      * @param {string} member_id 회원 ID
47478      * @param {string} request_data_json JSON 문자열
47479      * @param {string} hmac HMAC
47480      * @param {Object} aRequestData 파싱된 요청 데이터
47481      * @returns {Object} API 요청 정보 객체
47482      */
47483     createApiRequestInfo: function(mall_id, request_time, app_key, member_id, request_data_json, hmac, aRequestData) {
47484         var shipping_type = this.getShippingType(aRequestData);
47485         
47486         return {
47487             mall_id: mall_id,
47488             request_time: request_time,
47489             app_key: app_key,
47490             mobile: aRequestData.mobile,
47491             member_id: member_id,
47492             shipping_type: shipping_type,
47493             payment_method: aRequestData.payment_method,
47494             country_code: aRequestData.country_code,
47495             carrier_id: aRequestData.carrier_id,
47496             zipcode: aRequestData.zipcode,
47497             address_full: aRequestData.address_full,
47498             address_state: aRequestData.address_state,
47499             points_spent_amount: aRequestData.points_spent_amount,
47500             order_coupons: aRequestData.order_coupons,
47501             items: aRequestData.items,
47502             gifts: aRequestData.gifts, // 선택 사은품 (ECHOSTING-630597)
47503             basket_type: "A0000",
47504             request_data_json: request_data_json,
47505             hmac: hmac,
47506             from: "precreateOrder"
47507         };
47508     },
47509
47510     /**
47511      * 바스켓 처리 또는 장바구니 추가 (공통 함수)
47512      * @param {string} mall_id 쇼핑몰 ID
47513      * @param {string} request_time 요청 시간
47514      * @param {string} app_key 앱 키
47515      * @param {string} member_id 회원 ID
47516      * @param {string} hmac HMAC
47517      * @param {string} request_data_json JSON 문자열
47518      * @param {Object} aInfo API 요청 정보 객체
47519      * @param {boolean} bIsOrderBasket 주문 바스켓 페이지 여부
47520      * @returns {Promise} Promise 객체
47521      */
47522     handleBasketOrCart: function(mall_id, request_time, app_key, member_id, hmac, request_data_json, aInfo) {
47523         let bIsOrderBasket = this.isOrderBasketPage();
47524
47525         return new Promise(function (res, rej) {
47526             if (Basket.orderSelectBasket != undefined && bIsOrderBasket) {
47527                 var result = Basket.orderSelectBasket(this, aInfo['shipping_type'], 'app', res);
47528                 if(result == false) rej();
47529             } else {
47530                 if (request_data_json) {
47531                     // request_data_json이 있는 경우 (calculatePayment, precreateOrderV2)
47532                     CAPP_ASYNC_METHODS.AppCommon.addCurrentProductToCart(mall_id, request_time, app_key, member_id, hmac, 'T', request_data_json).then(function(addedCartItems){
47533                         res(addedCartItems);
47534                     }).catch(function (result) {
47535                         rej(result);
47536                     });
47537                 } else {
47538                     // request_data_json이 없는 경우 (precreateOrder)
47539                     CAPP_ASYNC_METHODS.AppCommon.addCurrentProductToCart(mall_id, request_time, app_key, member_id, hmac, 'T').then(function(addedCartItems){
47540                         res(addedCartItems);
47541                     }).catch(function (result) {
47542                         rej(result);
47543                     });
47544                 }
47545             }
47546         });
47547     }
47548};
47549
47550/**
47551 * 도메인 개선으로 인한 이미지 로드 이슈 케이스를 수정
47552 * @type {{bInit: boolean, init: EC_ROUTE_FIX.init}}
47553 */
47554EC$(function () {
47555    var EC_ROUTE_FIX = {
47556        bInit: false,
47557        init: function () {
47558            if (this.bInit || typeof EC_ROUTE === 'undefined') {
47559                return ;
47560            }
47561            this.bInit = true;
47562
47563            this.setEvent();
47564            this.setFix();
47565        },
47566        setEvent: function () {
47567            this.setErrorSrcEvent();
47568            this.setErrorHrefEvent();
47569        },
47570        setFix: function ()
47571        {
47572            // 스킨 미리보기에서 쿠키가 설정되지 않도록 설정 후 재발할 경우 처리되도록 한다.
47573            // this.setFixDomainCookie();
47574        },
47575        /**
47576         * EP 캐시 대응용 ECHOSTING-475508
47577         * 서버사이드 까지 전달되지 못해 url 에 포함된 도메인 정보가 쿠키에 저장되지 못할 경우
47578         * 실제 유입된 url 과 쿠키에 저장된 도메인 정보가 다를 수 있다.
47579         * 따라서 쿠키가 존재한다면 쿠키에 저장된 정보를 url 에 따라 캐싱된 ep 에 assign 된 javascript 변수를 사용하여
47580         * 재 갱신 시켜 준다.
47581         */
47582        setFixDomainCookie: function ()
47583        {
47584            if (EC$.cookie(EC_ROUTE.EC_DOMAIN_PATH_INFO) === null) {
47585                return;
47586            }
47587            if (typeof EC_ROUTE.isNeedRoute() !== 'undefined' && EC_ROUTE.isNeedRoute() === false) {
47588                EC$.cookie(EC_ROUTE.EC_DOMAIN_PATH_INFO, null, {path: '/', domain: '.' + window.location.host});
47589                return;
47590            }
47591
47592            var oOverwriteCookie = {}, bWrite = false;
47593            if (typeof EC_ROUTE.getShopNo() !== 'undefined'
47594                && EC_ROUTE.getShopNo() > 0) {
47595                oOverwriteCookie['shop_no'] = EC_ROUTE.getShopNo();
47596                bWrite = true;
47597            }
47598            if (typeof EC_ROUTE.getMobile() !== 'undefined'
47599            && EC_ROUTE.getMobile() === true) {
47600                oOverwriteCookie['is_mobile'] = EC_ROUTE.getMobile();
47601                bWrite = true;
47602            }
47603            if (typeof EC_ROUTE.getLanguageCode() !== 'undefined'
47604            && EC_ROUTE.getLanguageCode() !== 'ZZ') {
47605                oOverwriteCookie['language_code'] = EC_ROUTE.getLanguageCode();
47606                bWrite = true;
47607            }
47608            if (typeof EC_ROUTE.getSkinCode() !== 'undefined'
47609            && EC_ROUTE.getSkinCode() !== 'default') {
47610                oOverwriteCookie['skin_code'] = EC_ROUTE.getSkinCode();
47611                bWrite = true;
47612            }
47613
47614            if (bWrite) {
47615                EC$.cookie(EC_ROUTE.EC_DOMAIN_PATH_INFO, JSON.stringify(oOverwriteCookie), {path: '/', domain: '.' + window.location.host});
47616            } else {
47617                EC$.cookie(EC_ROUTE.EC_DOMAIN_PATH_INFO, null, {path: '/', domain: '.' + window.location.host});
47618            }
47619        },
47620        setErrorSrcEvent: function ()
47621        {
47622            EC$("img, input[type='image'], script").on("error", function(e){
47623                this.onerror = null;
47624                if (EC$(this).attr('src') != EC_ROUTE.getPrefixUrl(EC$(this).attr('src'))) {
47625                    this.src = EC_ROUTE.getPrefixUrl(EC$(this).attr('src'));
47626                }
47627            });
47628        },
47629        setErrorHrefEvent: function ()
47630        {
47631            EC$("link").on("error", function(e){
47632                this.onerror = null;
47633                if (EC$(this).attr('href') != EC_ROUTE.getPrefixUrl(EC$(this).attr('href'))) {
47634                    this.href = EC_ROUTE.getPrefixUrl(EC$(this).attr('href'));
47635                }
47636            });
47637        }
47638    };
47639
47640    EC_ROUTE_FIX.init();
47641});
47642

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.