/*
 * 特别声明：本技术材料受《中华人民共和国著作权法》、《计算机软件保护条例》等法律、法规、行政
 * 规章以及有关国际条约的保护，赞同科技享有知识产权、保留一切权利并视其为技术秘密。未经本公司书
 * 面许可，任何人不得擅自（包括但不限于：以非法的方式复制、传播、展示、镜像、上载、下载）使用，
 * 不得向第三方泄露、透露、披露。否则，本公司将依法追究侵权者的法律责任。特此声明！
 *
 * Special Declaration: These technical material reserved as the technical secrets by AGREE
 * TECHNOLOGY have been protected by the "Copyright Law" "ordinances on Protection of Computer
 * Software" and other relevant administrative regulations and international treaties. Without
 * the written permission of the Company, no person may use (including but not limited to the
 * illegal copy, distribute, display, image, upload, and download) and disclose the above
 * technical documents to any third party. Otherwise, any infringer shall afford the legal
 * liability to the company.
 */
/**
 * Created by huangdeyun on 2015/5/28.
 */


define([], function () {
    var $tab_min_width = 60;
    var movingIconWidth = 70;//两个移动图标占用的宽度
    var movingLeftIconWidth = 40;
    var totalWidthPrefix = 30;
    return {

//$("#tabFolder").find("li.tab_left_move").on("click", function (e) {
        handleTabLeftMoveClick: function (tabFolderId) {
            var tabs = $("#" + tabFolderId);
            var indexs = this.getBlockIndexs(tabs);
            var blockBegin = indexs[0], blockEnd = indexs[1];
            if (blockBegin <= 0) {
                return;
            }
            var lis = tabs.find("li.adore_tab");
            var count = this.tabLeftMove(tabs, lis, blockBegin);
            if (count <= 1) {
                this.tabLeftMove(tabs, lis, blockBegin - 1);
            }
            this.resetMovingIcon(tabs, lis);
            this.resetIndicator(tabs, lis);
        },

//$("#tabFolder").find("li.tab_right_move").on("click", function (e) {
        handleTabRightMoveClick: function (tabFolderId) {
            var tabs = $("#" + tabFolderId);
            var indexs = this.getBlockIndexs(tabs);
            var blockBegin = indexs[0], blockEnd = indexs[1];
            var lis = tabs.find("li.adore_tab");
            if (this.isEndRight(tabs, lis)) {
                return;
            }
            var count = this.tabRightMove(tabs, lis, blockEnd);
            if (count <= 1) {
                this.tabRightMove(tabs, lis, blockEnd + 1);
            }
            this.resetMovingIcon(tabs, lis);
            this.resetIndicator(tabs, lis);
        },

        isEndRight: function (tabs, lis) {
            var indexs = this.getBlockIndexs(tabs);
            var endRight = false;
            if (indexs[1] === lis.length - 1) {
                var w = $(lis[indexs[1]]).width();
                this.resetAndGetRealWidth(tabs);
                var realW = $(lis[indexs[1]]).width();
                $(lis[indexs[1]]).width(w + "px");
                if (w == realW) {
                    endRight = true;
                }
            }
            if (indexs[0] == indexs[1]) {
                endRight = true;
            }
            return endRight;
        },

        resetMovingIcon: function (tabs, lis) {
            if (tabs.find("li.tab_left_move").css("display") === "none") {
                return;
            }
            var indexs = this.getBlockIndexs(tabs);
            var endRight = this.isEndRight(tabs, lis);
            var arrowRight = tabs.find("li.tab_right_move").find("div");
            var arrowLeft = tabs.find("li.tab_left_move").find("div");
            arrowLeft.removeClass("arrow_not_active").removeClass("arrow_active");
            arrowRight.removeClass("arrow_not_active").removeClass("arrow_active");
            if (endRight) {
                //已到最右
                arrowRight.addClass("arrow_not_active");
            } else {
                arrowRight.addClass("arrow_active");
            }
            if (indexs[0] === 0) {
                //已到最左
                arrowLeft.addClass("arrow_not_active");
            } else {
                arrowLeft.addClass("arrow_active");
            }
        },

        tabLeftMove: function (tabs, lis, blockBegin) {
            lis.removeClass("tab_visible").addClass("tab_not_visible");
            var canUseWidth = tabs.width() - movingIconWidth - totalWidthPrefix;//可使用的宽度
            var usedWidth = 0;//已使用宽度
            var i;
            this.resetAndGetRealWidth(tabs);
            //显示
            for (i = blockBegin; i >= 0 && usedWidth < canUseWidth; i--) {
                $(lis[i]).addClass("tab_visible").removeClass("tab_not_visible");
                usedWidth += $(lis[i]).width();
            }
            for (i = blockBegin + 1; i < lis.length && usedWidth < canUseWidth; i++) {
                $(lis[i]).addClass("tab_visible").removeClass("tab_not_visible");
                usedWidth += $(lis[i]).width();
            }
            var tempIndexs = this.getBlockIndexs(tabs);
            var end = tempIndexs[1];
            if (usedWidth > canUseWidth) {
                $(lis[end]).width($(lis[end]).width() - (usedWidth - canUseWidth) + "px");
            }
            return tempIndexs[1] - tempIndexs[0] + 1;
        },


        tabRightMove: function (tabs, lis, blockEnd) {
            lis.removeClass("tab_visible").addClass("tab_not_visible");
            var canUseWidth = tabs.width() - movingIconWidth - totalWidthPrefix;//可使用的宽度
            var usedWidth = 0;//已使用宽度
            var i;
            this.resetAndGetRealWidth(tabs);
            //显示
            for (i = blockEnd; i < lis.length && usedWidth < canUseWidth; i++) {
                $(lis[i]).addClass("tab_visible").removeClass("tab_not_visible");
                usedWidth += $(lis[i]).width();
            }
            for (i = blockEnd - 1; i >= 0 && usedWidth < canUseWidth; i--) {
                $(lis[i]).addClass("tab_visible").removeClass("tab_not_visible");
                usedWidth += $(lis[i]).width();
            }
            var tempIndexs = this.getBlockIndexs(tabs);
            var end = tempIndexs[1], begin = tempIndexs[0];
            if (usedWidth > canUseWidth) {
                //已经移动到最后一个了
                if (end === lis.length - 1 && end != begin) {
                    $(lis[begin]).removeClass("tab_visible").addClass("tab_not_visible");
                } else {
                    $(lis[end]).width($(lis[end]).width() - (usedWidth - canUseWidth) + "px");
                }
            }
            tempIndexs = this.getBlockIndexs(tabs);
            return tempIndexs[1] - tempIndexs[0] + 1;
        },

        getBlockIndexs: function (tabs) {
            var tabList = tabs.find("li.adore_tab");
            var blockBegin = 0, blockEnd = 0, i;
            for (i = 0; i < tabList.length; i++) {
                if ($(tabList[i]).css("display") === "block") {
                    blockBegin = i;
                    break;
                }
            }
            for (i = tabList.length - 1; i >= 0; i--) {
                if ($(tabList[i]).css("display") === "block") {
                    blockEnd = i;
                    break;
                }
            }
            return [blockBegin, blockEnd];
        },

        getPreTabIndex: function (tabs) {
            var preIndex = 0;
            var activeHref = tabs.find("a.active").attr("href");
            var tabList = tabs.find("li.adore_tab");
            var tmpHref;
            //找到之前tab的下标
            for (var i = 0; i < tabList.length; i++) {
                tmpHref = $(tabList[i]).find("a").attr("href");
                if (activeHref === tmpHref) {
                    preIndex = i;
                    break;
                }
            }
            var blockIndexs = this.getBlockIndexs(tabs);
            if (preIndex < blockIndexs[0]) {
                return -1;//左边
            }
            if (preIndex > blockIndexs[1]) {
                return -2//右边
            }
            return preIndex - blockIndexs[0];
        },

//$("#tabFolder").find("a.waves-effect").on("click", function (e) {
        handleTabClick: function (e, currentTab, tabFolderId) {
            var tabs = $("#" + tabFolderId);

            var tabList = tabs.find("li.tab_visible");
            var currentIndex = 0;
            var currentHref = currentTab.attr("href");
            //找到当前tab的下标
            var tmpHref;
            for (var i = 0; i < tabList.length; i++) {
                tmpHref = $(tabList[i]).find("a").attr("href");
                if (currentHref === tmpHref) {
                    currentIndex = i;
                    break;
                }
            }
            // 找到之前tab的下标
            var lis = tabs.find("li.adore_tab");
            var preIndex = this.getPreTabIndex(tabs);
            //设置之前的tab内容不可见
            var activeHref = tabs.find("a.active").attr("href");
            $(activeHref).css("display", "none");
            // 消除之前的active
            tabs.find("a.active").removeClass("active");
            // 为currentTab添加active
            currentTab.addClass("active");
            $(currentHref).css("display", "block");

            var $tab_width = $(tabList[currentIndex]).width();
            var $indivatorLeft = this.getIndicatorLeftWidth(tabs, lis);
            var $indicator = tabs.find("div.my_indicator");
            // Update indicator
            if (preIndex === -2 || preIndex === -1) {
                $indicator.width($tab_min_width + "px");
            }
            $indicator.velocity({"left": $indivatorLeft, "width": $tab_width + "px"}, { duration: 300, queue: false, easing: 'easeOutQuad'});

        },

// 设置签页的实际宽度并返回实际宽度
        resetAndGetRealWidth: function (tabs) {
            var lis = tabs.find("li.adore_tab");
            //所有tab实际占的宽度
            var tabRealWidth = 0;
            for (var i = 0; i < lis.length; i++) {
                var a = $(lis[i]).find("a");
                var text = a.text();
                var fontSize = a.css("font-size");
                var letterSpacing = a.css("letter-spacing");
                fontSize = parseFloat(fontSize.replace("px", ""));
                letterSpacing = parseFloat(letterSpacing.replace("px", ""));
                var t = (fontSize + letterSpacing) * text.length + $tab_min_width / 2;
                t = t > $tab_min_width ? t : $tab_min_width;// 确保最小的tab宽度为40
                tabRealWidth += t;
                $(lis[i]).width(t + "px");
            }
            return tabRealWidth;
        },

        refreshTabs: function (tabs) {
            var totalWidth = tabs.width() - totalWidthPrefix;
            var lis = tabs.find("li.adore_tab");
            var activeIndex = this.getActiveIndex(lis);
            lis.removeClass("tab_visible");
            lis.addClass("tab_not_visible");
            tabs.find("li.tab_left_move").css("display", "none");
            tabs.find("li.tab_right_move").css("display", "none");
            movingIconWidth = tabs.find("li.tab_left_move").width() + tabs.find("li.tab_right_move").width() + 10;
            var tabRealWidth = this.resetAndGetRealWidth(tabs);//所有签页的实际宽度
            tabs.find("li.adore_tab_space").css("display", "none");
            if (tabRealWidth > totalWidth) {
                //添加左移动图标
                tabs.find("li.tab_left_move").css("display", "block");
                //添加右移动图标
                tabs.find("li.tab_right_move").css("display", "block");
                this.tabRightMove(tabs, lis, activeIndex);
            } else {
                lis.removeClass("tab_not_visible").addClass("tab_visible");
                tabs.find("li.adore_tab_space").css("display", "block");
            }

            //添加indicator
            tabs.find("div.indicator").remove();
            tabs.find("div.my_indicator").remove();
            var indicator = $("<div></div>").addClass("my_indicator");
            indicator.appendTo(tabs);
            this.resetIndicator(tabs, lis)
            this.resetMovingIcon(tabs, lis);
        },

        getActiveIndex: function (lis) {
            var activeIndex = 0;
            for (var i = 0; i < lis.length; i++) {
                if ($(lis[i]).find("a.active").length != 0) {
                    activeIndex = i;
                    break;
                }
            }
            return activeIndex;
        },

        resetIndicator: function (tabs, lis) {
            var indicatorLeft = this.getIndicatorLeftWidth(tabs, lis);
            var indicator = tabs.find("div.my_indicator");
            if (indicatorLeft === -1) {
                indicator.width(0);
                return;
            }
            var index = this.getActiveIndex(lis);
            indicator.width($(lis[index]).width() + "px");
            indicator.css("left", indicatorLeft + "px");
        },

        getIndicatorLeftWidth: function (tabs, lis) {
            var indexs = this.getBlockIndexs(tabs), activeIndex = this.getActiveIndex(lis), indicatorLeft = 0;
            if (activeIndex < indexs[0] || activeIndex > indexs[1]) {
                return -1;
            }
            if (tabs.find("li.tab_left_move").css("display") === "block") {
                indicatorLeft += movingLeftIconWidth;
            } else {
                indicatorLeft += totalWidthPrefix;
            }
            for (var i = indexs[0]; i < activeIndex; i++) {
                indicatorLeft += $(lis[i]).width();
            }
            return indicatorLeft;
        },

        tabsSwitch:function(tabs){
          var methods = {
            init : function() {
              return this.each(function() {

              // For each set of tabs, we want to keep track of
              // which tab is active and its associated content
              var $this = $(this),
                  window_width = $(window).width();

              $this.width('100%');
              var $active, $content, $links = $this.find('li.adore_tab a'),
                  $tabs_width = $this.width(),
                  $tab_width = $this.find('li').first().outerWidth(),
                  $index = 0;

              // If the location.hash matches one of the links, use that as the active tab.
              $active = $($links.filter('[href="'+location.hash+'"]'));

              // If no match is found, use the first link or any with class 'active' as the initial active tab.
              if ($active.length === 0) {
                  $active = $(this).find('li.adore_tab a.active').first();
              }
              if ($active.length === 0) {
                $active = $(this).find('li.adore_tab a').first();
              }

              $active.addClass('active');
              $index = $links.index($active);
              if ($index < 0) {
                $index = 0;
              }

              $content = $($active[0].hash);

              // append indicator then set indicator width to tab width
              $this.append('<div class="indicator"></div>');
              var $indicator = $this.find('.indicator');
              if ($this.is(":visible")) {
                $indicator.css({"right": $tabs_width - (($index + 1) * $tab_width)});
                $indicator.css({"left": $index * $tab_width});
              }
              $(window).resize(function () {
                $tabs_width = $this.width();
                $tab_width = $this.find('li').first().outerWidth();
                if ($index < 0) {
                  $index = 0;
                }
                if ($tab_width !== 0 && $tabs_width !== 0) {
                  $indicator.css({"right": $tabs_width - (($index + 1) * $tab_width)});
                  $indicator.css({"left": $index * $tab_width});
                }
              });

              // Hide the remaining content
              $links.not($active).each(function () {
                $(this.hash).hide();
              });


              // Bind the click event handler
              $this.on('click', 'a', function(e) {
                if ($(this).parent().hasClass('disabled')) {
                  e.preventDefault();
                  return;
                }

                $tabs_width = $this.width();
                $tab_width = $this.find('li').first().outerWidth();

                // Make the old tab inactive.
                $active.removeClass('active');
                $content.hide();

                // Update the variables with the new link and content
                $active = $(this);
                $content = $(this.hash);
                $links = $this.find('li.adore_tab a');

                // Make the tab active.
                $active.addClass('active');
                var $prev_index = $index;
                $index = $links.index($(this));
                if ($index < 0) {
                  $index = 0;
                }
                // Change url to current tab
                // window.location.hash = $active.attr('href');

                $content.show();

                // Update indicator
                if (($index - $prev_index) >= 0) {
                  $indicator.velocity({"right": $tabs_width - (($index + 1) * $tab_width)}, { duration: 300, queue: false, easing: 'easeOutQuad'});
                  $indicator.velocity({"left": $index * $tab_width}, {duration: 300, queue: false, easing: 'easeOutQuad', delay: 90});

                }
                else {
                  $indicator.velocity({"left": $index * $tab_width}, { duration: 300, queue: false, easing: 'easeOutQuad'});
                  $indicator.velocity({"right": $tabs_width - (($index + 1) * $tab_width)}, {duration: 300, queue: false, easing: 'easeOutQuad', delay: 90});
                }

                // Prevent the anchor's default click action
                e.preventDefault();
              });
            });

            },
            select_tab : function( id ) {
              this.find('a[href="#' + id + '"]').trigger('click');
            }
          };

          $.fn.tabs = function(methodOrOptions) {
            if ( methods[methodOrOptions] ) {
              return methods[ methodOrOptions ].apply( this, Array.prototype.slice.call( arguments, 1 ));
            } else if ( typeof methodOrOptions === 'object' || ! methodOrOptions ) {
              // Default to "init"
              return methods.init.apply( this, arguments );
            } else {
              $.error( 'Method ' +  methodOrOptions + ' does not exist on jQuery.tooltip' );
            }
          };

          tabs.tabs();
        }
    }
});