/* ****************************************************************************************************** Pjax( https://github.com/defunkt/jquery-pjax ) / Tab 생성 JS ****************************************************************************************************** */ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf if(!Array.prototype.indexOf){Array.prototype.indexOf=function(searchElement,fromIndex){var k;if(this==null){throw new TypeError('"this" is null or not defined');}var o=Object(this);var len=o.length>>>0;if(len===0){return-1}var n=+fromIndex||0;if(Math.abs(n)===Infinity){n=0}if(n>=len){return-1}k=Math.max(n>=0?n:len-Math.abs(n),0);while(k>>0,k=0,value;if(arguments.length==2){value=arguments[1]}else{while(k=len){throw new TypeError('Reduce of empty array with no initial value');}value=t[k++]}for(;k
'), // 모더나이저 transEndEventNames = { 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd', 'transition': 'transitionend' }, progressVal = 0, // transition end 이벤트 이름 확인 transEndEventName = transEndEventNames[Modernizr.prefixed('transition')], // Tabs - 방문했던 페이지 저장용(로컬스토리지) Tabs = {}, // GeneralPage - [data-pjax] a링크가 아닌 일반 링크를 클릭한 페이지 저장용(로컬스토리지) GeneralPage = {}, // StayingPage - 마지막에 머물렀던 페이지 저장용(로컬스토리지) StayingPage = {}, // 사이트 리스트 siteListEl = $('.site-setting'), // 메인메뉴 엘리먼트 mainMenuEl = $('#mainMenu'), // 탭메뉴 전체박스 tabMenuWrap = $('#pjaxTabMenuWrap'), // 탭메뉴 tabMenuEl = $('#pjaxTabMenu'), // 브라우저 리사이즈 될시 사라질 탭 저장용 saveTabs = [], // 'next', 'after', 'prev', 'before' 등 메서드이름 저장용 saveEventName = [], // closeTab 버튼 누른거 판단 isCloseTab = false, // 브라우저 크기가 커지고 있는지 판단 oldWidth = $root.width(), // tab Default Size.. tabSize = { width : 170, height : 34, limit : 130 }, isGTU = false, isSiteIdx = false, siteIdx = (function() { var currentSiteIdx = $html.data('siteidx') || '', split = currentSiteIdx.split('/'), emptySiteIdx = false; // siteIdx가 없는지 판단 $.each(split, function(i, val) { if( !val ) { emptySiteIdx = true; isSiteIdx = true; } }); // gtu 처리 if( currentSiteIdx.indexOf('gtu') > -1 ) { currentSiteIdx = currentSiteIdx.split('/')[0] + '/' + location.hostname.split('.')[0]; isGTU = true; emptySiteIdx = false; } if( !emptySiteIdx ){ if( window.sessionStorage && split[1] === 'seed' ){ return window.sessionStorage.siteIdx; } window.sessionStorage.siteIdx = currentSiteIdx; } /*return emptySiteIdx ? sessionStorage.siteIdx : currentSiteIdx;*/ //seed.tab이 계속 뜨는 문제로 인해 하드코딩으로 넘기기_임시방편!!!!!!!!!!!!_이준호 return "case"; }()); // from : https://arifhossen.wordpress.com/2010/07/19/javascript-get-base-url/ function getBaseURL() { var url = location.href; // window.location.href; var pathname = location.pathname; // window.location.pathname; var index1 = url.indexOf(pathname); var index2 = url.indexOf("/", index1 + 1); var baseLocalUrl = ""; var split = baseLocalUrl.split('/'); $.each(['gtm', 'gta', 'gtu', 'gta'], function(index, val) { if( split[split.length-1].indexOf(val) > -1 ){ baseLocalUrl = url.substr(0, index2); } }); if( !baseLocalUrl ){ baseLocalUrl = url.substring(0, url.indexOf('/', 14)) + '/gtm'; } // Root Url for domain name return baseLocalUrl + "/" ; } function randomIntFromInterval(min, max) { return Math.floor(Math.random()*(max-min+1)+min); } /** * 페이지 진입시 기본적으로 실행할 함수 */ function init() { if( siteIdx === undefined || !siteIdx ){ $.SeedModal({ url : getBaseURL() + 'login.do', title : '사이트를 선택해주세요.', close : false }); //location.href = getBaseURL() + 'login.do'; return; } $.ajaxSetup({ cache: false }); createMenuURL(); GeneralPage[siteIdx] = {}; window.localStorage.GeneralPage = JSON.stringify( GeneralPage ); // localStorage 초기화 initLocalStorage(); // 및 설정 updateLocalStorage(); // Tabs 생성 appendedMenuItems.call(tabMenuEl, Tabs[siteIdx]); // 현재 페이지에 해쉬 태그가 없을 경우 createHashTag(); // 메뉴 활성화 activeMenu(); // tabResize.. tabResize(); // Event binding.. initEvents(); } function createMenuURL() { if( !window.sessionStorage.siteIdx ) return; mainMenuEl.find('a').each(function(index, elem) { var path = elem.pathname, sp = path.split('//'), currentSiteIdx = siteIdx.split('/')[1]; if( sp.length > 1 ) { elem.pathname = sp.join('/' + currentSiteIdx + '/'); } // 사이트관리 else if( path.indexOf('/siteEdit/.do') > -1 ){ elem.pathname = path.split('.do').join( currentSiteIdx + '.do' ); elem.hash = currentSiteIdx; } }); } /** * DOM 이벤트 */ function initEvents() { // document $doct // pjax 요청 .on('click.pjax', '[data-pjax] a, a[data-pjax]', pjaxClick) // [data-pjax] a가 아닌 링크 클릭시 .on('click', 'a:not([data-pjax] a, a[data-pjax], .site-setting a)',notPjaxClick).on('submit', 'form', notPjaxClick) // beforeReplace .on('pjax:beforeReplace', pjaxBeforeReplace) // 뒤로가기 .on('pjax:popstate', pjaxPopstate) // 끝 .on('pjax:end', pjaxEnd) // 탭 닫기 .on('click', '.closeTab', closeTab) // 탭 추가 .on('click', '#mainMenu a', function() { var ID = $(this).attr('id'); if( ID && $.support.pjax ){ appendedMenuItems .call(tabMenuEl, ['#' + ID]) ; } }) .on('click', '#pjaxTabMenuWrap > button', function(ev){ if( $('#wholeTabs').length ){ $('#wholeTabs') .remove() ; return; } else { tabMenuWrap .append('
    ') ; } var isWholeTabs = true; appendedMenuItems // jquery object Return .call($('#wholeTabs > ul'), Tabs[siteIdx], isWholeTabs) .append( $('
  • ').addClass('close') .append( $('').on('click', wholeTabClose) ) ) .parent() .show() ; return false; }) .on('click', '#wholeTabs a', function(){ var self = $(this); var currentClass = $(this).attr('class').split(' ')[0]; $.each(saveTabs, function( index, elem ){ elem = $(elem) var saveClass = elem.find('a').attr('class'); if( $(elem).length ){ if( currentClass === saveClass ){ appendedMenuItems .call( tabMenuEl, ['#' + currentClass], true ) ; saveTabs .splice( index, 1 ) ; } } }); }) ; // window $root .on('onhashchange hashchange', hashChange) .on('resize.tabResize', tabResize) ; } /** * 브라우저 resize 모바일 확인용 */ function isResponsiveMobilePoint(){ return !$('#indicator').is(':visible'); } /** * 활성화 되야할 현재 메뉴 */ function currentActiveElement(){ var hash = location.hash, sp = hash.split('#'), ID = '#' + ( $.support.pjax ? sp[sp.length - 1] : mainMenuEl.find('a.on').attr('id') ); if( hash.indexOf('undefined') > -1 || !hash || !mainMenuEl.find( ID ).length ){ ID = StayingPage[siteIdx]; } return $( ID ); } /** * window.localStorage 초기화 및 설정 * JSON.parse / JSON.stringify */ function initLocalStorage(){ var currentElement = currentActiveElement(); var ID = '#' + currentElement.attr('id'); if( currentElement.length && ID ){ Tabs[siteIdx] = [ID]; StayingPage[siteIdx] = ID; } // localStorage.Tabs if( !window.localStorage.Tabs ){ window.localStorage.Tabs = JSON.stringify(Tabs); } else { Tabs = $.extend(true, {}, Tabs, JSON.parse(window.localStorage.Tabs)); window.localStorage.Tabs = JSON.stringify( Tabs ); } // localStorage.StayingPage if( !window.localStorage.StayingPage ){ window.localStorage.StayingPage = JSON.stringify( StayingPage ); } else { StayingPage = $.extend(true, {}, StayingPage, JSON.parse(window.localStorage.StayingPage)); window.localStorage.StayingPage = JSON.stringify( StayingPage ); } // localStorage.GeneralPage if( !window.localStorage.GeneralPage ){ window.localStorage.GeneralPage = JSON.stringify(GeneralPage); } else { GeneralPage= $.extend(true, {}, GeneralPage, JSON.parse( window.localStorage.GeneralPage )); window.localStorage.GeneralPage = JSON.stringify( GeneralPage ); } } /** * 로컬스토리지 업데이트 */ function updateLocalStorage(parmID) { var deferred = $.Deferred(); var currentElement = currentActiveElement(); var ID = parmID || '#' + currentElement.attr('id'); var TabsClone; // 업뎃 하기전에 로컬스토리지 객체가 없으면 초기화 시킴. if( !Tabs[siteIdx] && !StayingPage[siteIdx] && currentElement.length ) { Tabs[siteIdx] = [ID]; StayingPage[siteIdx] = ID; } else if( !Tabs[siteIdx] && !StayingPage[siteIdx] && !currentElement.length ) { return; } // Tabs if( ID && ID[0] === '#' ) { Tabs[siteIdx].push(ID); } TabsClone = JSON.parse(window.localStorage.Tabs); Tabs[siteIdx] = Tabs[siteIdx].concat(TabsClone[siteIdx]).unique(); window.localStorage.Tabs = JSON.stringify(Tabs); // StayingPage StayingPage[siteIdx] = ID; window.localStorage.StayingPage = JSON.stringify(StayingPage); return deferred.resolve().promise(); } /** * 현재 활성화 되야할 메뉴 avtive */ function activeMenu(target) { var currentElement; if( !!target ) { currentElement = target; } else { currentElement = currentActiveElement(); } var classie = (currentElement.attr('id') || currentElement.attr('class')) ; mainMenuEl.add(tabMenuEl).add($('#wholeTabs')).find('a').removeClass('on'); if( GeneralPage[siteIdx] && GeneralPage[siteIdx].id ) { $( GeneralPage[siteIdx].id +','+ GeneralPage[siteIdx].id.replace('#', '.') ).addClass('on'); } else { $('#' + classie).add($( '.' + classie )).addClass('on'); } // 현재 활성화 되야할 메뉴가 열려있지 않을때 강제 클릭,, if( !$('#'+classie).parents('ul').parent('li').hasClass('current-tab') ) { $.fx.off = !$.fx.off; $('#'+classie).parents('ul').parent('li').find(' > a').click(); $.fx.off = !$.fx.off; } // 업데이트 스토리지 updateLocalStorage(); return } /** * Returns String */ function stripHash(location) { return location.href.replace(/#.*/, ''); } /** * pjax request * Returns Promise Object */ function pjaxRequest(url) { if( !$.support.pjax ) return; return $.pjax({ url: url, timeout: 0, dataType: 'html', scrollTo: false, container: '#pjaxContainer', fragment: '#pjaxContainer', error: function() { progressAnimation.error(); } }); } function MorrisChartClear() { // morris resize event off $(window) .off('resize.morris') .off('resize.MorrisDonut') .off('resize.MorrisBar') .off('resize.MorrisLine') [0].Morris = NaN ; } var progressAnimation = (function() { var isProgressAnimation = 0; var loaderElem = $('.pjax-loader-bar'); var progElem = loaderElem.find('.progress'); var progVal = randomIntFromInterval(0, 5); return { start: function(){ if( !isProgressAnimation ) { loaderElem .addClass('is-loading') ; progElem .removeAttr('style') ; } isProgressAnimation++; var updateProgress = function(){ progElem.width(progVal + '%'); } if( progVal <= 75 ) { setTimeout(function(){ if( isProgressAnimation ) { progVal = progVal + randomIntFromInterval(1, 3); updateProgress(); progressAnimation.start(); } }, !isProgressAnimation ? 0 : 100) } }, end: function(){ isProgressAnimation = 0; loaderElem .removeClass('is-loading') .one(transEndEventName, function(){ progVal = 0; }) ; progElem .width(100 + '%') ; }, error: function(){ progressAnimation.end(); setTimeout(function(){ alert('에러!'); location.reload(); }, 0); } } }()); /** * pjax click */ function pjaxClick(ev) { MorrisChartClear(); if( $('#wholeTabs').length && !$(this).parents('#wholeTabs').length ){ $('#wholeTabs').remove(); } var $this = $(this); var url = $this.attr('href'); if( $this.hasClass('on') ) { location.href = $this.attr('href'); return; } if( $.browser.versionNumber > 9 ){ progressAnimation.start(); } // 메뉴 활성화 activeMenu($this); var timer = 0; // 모바일 사이드메뉴 열려있을 경우 if( $.browser.mobile || isResponsiveMobilePoint() && $('#navContainer').hasClass('open') ){ timer = 400; window.seedCommon.Layout.mobileClose(); } setTimeout(function() { if( $.support.pjax ) { // pjax pjaxRequest( url ).done(function( result ) { // 로컬 스토리지 업뎃, updateLocalStorage(); }); } // ie8, 9 else { // 로컬 스토리지 업뎃, updateLocalStorage().done(function() { location.href = url; }); } }, timer); return false; } /** * [data-pjax] a가 아닌 링크, 폼 */ function notPjaxClick(ev) { // siteIdx 저장 sessionStorage.siteIdx = siteIdx; var $this = $(this); href = $this.attr('href') || $this.attr('action'), currentElement = currentActiveElement(), ID = '#' + currentElement.attr('id'); if( href.split('#')[1] && $('#' + href.split('#')[1]).length ) { updateLocalStorage( '#' + href.split('#')[1] ); } // 파일관리쪽... // 기존 a태그 더블클릭시 href값을 바꿔주고있는데 여기서도 똑같이 변경해주고있어서 꼬임,, if( $this.attr('class') === 'dir' || $this.closest('.site').length ) return; // 데이터 전송시 if( href.indexOf('/proc/') > -1 || href.indexOf('javascript:') > -1 ) { GeneralPage[siteIdx] = {'id' : ID}; window.localStorage.GeneralPage = JSON.stringify(GeneralPage); } // 현재 페이지 저장 if( currentElement.length ) { StayingPage[siteIdx] = ID; window.localStorage.StayingPage = JSON.stringify(StayingPage); } // 새창으로 가거나 href=:javascript 걸려있을때 if( $this.attr('target') || href.indexOf('javascript:') > -1 ) { return; } // set link if(href.indexOf(ID) <= -1 && href.indexOf('#') <= -1 ) { $this.attr( ev.currentTarget.tagName.toUpperCase() === 'A' ? 'href' : 'action', href + ID ); } } /** * pjax : 컨텐츠가 바뀌기 전 */ function pjaxBeforeReplace( options, contents ){} /** * pjax 뒤로가기 */ function pjaxPopstate() { // 스토리지 업뎃 updateLocalStorage(); // 탭메뉴 생성 appendedMenuItems.call(tabMenuEl, ['#' + currentActiveElement().attr('id')]); // 메뉴 활성화 activeMenu(); // 차트 클리어 MorrisChartClear(); } /** * pjaxEnd */ function pjaxEnd() { //전역변수 이벤트 seedApp.init(); // 프로그레스 애니메이션 끝 progressAnimation.end(); } /** * hash가 없을 경우 */ function createHashTag() { var hash = location.hash, sp = hash.split('#'), ID = '#' + sp[sp.length - 1]; if( location.hash.indexOf('undefined') > -1 || !location.hash.length || !mainMenuEl.find( ID ).length ) { if( StayingPage[siteIdx] && StayingPage[siteIdx] !== 'undefined' ){ location.hash = StayingPage[siteIdx]; } } else { if( location.hash.length ) { return; } var hash = '#' + mainMenuEl.find('a.on').attr('id'); location.hash = hash; } } /** * 해시 체인지 이벤트 */ function hashChange() { var currentElement = currentActiveElement(); if( !currentElement.length || location.hash.indexOf('undefined') > -1 ){ setTimeout(function() { ///gtm/case/login.do로 계속 리다이렉트되는 에러로 주석 처리_이준호_250110 // location.href = getBaseURL() + 'login.do'; }, 1000); } else { if( GeneralPage[siteIdx] && GeneralPage[siteIdx].id ){ GeneralPage[siteIdx] = {}; window.localStorage.GeneralPage = JSON.stringify(GeneralPage); return; } if( currentElement.length && !isCloseTab ) { isCloseTab = false; return; } pjaxClick.call(currentElement); } } /** * 탭 생성 */ function appendedMenuItems(array, isWholeTabs) { if( !array ) { return; } isWholeTabs = !!isWholeTabs; // 문서조각 var fragment = $(document.createDocumentFragment()); $.each( array, function( index, id ) { var anchors = $( id ), href = anchors.attr('href'), classie = anchors.attr('id'), text = $.trim( anchors.text().replace(/-/g,'') ); if( $('[data-pjax] .' + classie).length || !text ) { if( !isWholeTabs ){ return; } } // 하나 추가햇을때 if( array.length === 1 || $('[data-pjax] .' + classie).hasClass('on')) { classie += ' on'; } if( text.length > 0 ){ fragment.append( $([ '
  • ', '', ''+ text +'', '', '', '
  • ' ].join('')) ); } }); // append $(this).append(fragment); // resize tab tabResize(); return $(this); } function wholeTabClose(ev) { var className = '#pjaxTabMenu a.' + mainMenuEl.find('a.on').attr('id'); $(className).parent().siblings().remove(); // Tabs set Tabs[siteIdx] = [StayingPage[siteIdx]]; // localStorage 업뎃 window.localStorage.Tabs = JSON.stringify( Tabs ); tabResize(); } function closeTab(ev) { isCloseTab = true; ev.stopPropagation(); ev.preventDefault(); var tabButton = $(this), className = tabButton.closest('a').attr('class').split(' ')[0], item = $('[data-pjax] .'+className).parent(), tab = item.find('a'), ID = '#' + className, index = Tabs[siteIdx].indexOf( ID ), direction = item.next().not('.close').length ? 'next' : 'prev', closeEnd = function() { // Tabs set Tabs[siteIdx].splice( index, 1 ); // localStorage 업뎃 window.localStorage.Tabs = JSON.stringify( Tabs ); // this remove item.remove(); // tab resize tabResize(); }; // 하나 남았을때. if( !item.eq( 0 ).siblings().length ){ var firstPage = '#dashboard'; // hash change if( mainMenuEl.find('a').eq( 0 ).attr('href') !== '#' ) { mainMenuEl.find('a').get( 0 ).click(); } else { mainMenuEl.find('li').eq( 0 ).find('ul a').get( 0 ).click(); firstPage = '#' + mainMenuEl.find('li').eq( 0 ).find('ul a').attr('id'); } // this remove if( ID !== firstPage ) { closeEnd(); } return; } // 현재 활성화 된 메뉴를 삭제했을때. else if( tab.hasClass('on') ) { item.eq( 0 )[direction]().find( 'a' ).get( 0 ).click(); } closeEnd(); return false; } function countTab() { return Math.floor(tabMenuEl.width() / tabSize.limit); } function overSize() { return tabSize.width * (tabMenuEl.find('li').length) >= tabMenuEl.width(); } /** * Tabs 크기 지정 */ function tabResize() { var currentItem = tabMenuEl.find('.'+currentActiveElement().attr('id')); var items = tabMenuEl.find('li'); // 탭 지우기 for( var i = items.length; i > countTab(); i-- ) { if( currentItem.parent().index() < Math.floor(tabMenuEl.find('li').length / 2) ) { saveEventName = ['next', 'after']; } else { saveEventName = ['prev', 'before']; } saveTabs.push(currentItem.parent()[saveEventName[0]]().detach()); } var items = tabMenuEl.find('li'); // 탭 살리기 if( oldWidth < $root.width() && !overSize() ){ for( var j = items.length; j < countTab(); j++ ) { if( saveEventName[1] ){ currentItem.parent()[saveEventName[1]]( saveTabs.shift() ); } } } var items = tabMenuEl.find('li'); if( overSize() ) { items.width((tabMenuEl.width() / items.length ) - 2); } else { items.width(tabSize.width); } oldWidth = $root.width(); } window.tabResize = tabResize; // init init(); }; // Tab End // ready Tab $(Tab); }(window, document, jQuery));