/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global $, window, location, CSInterface, SystemPath, themeManager*/
if(!Promise){
    var Promise = require('promise');
}

var csInterface = new CSInterface();

var markSpans;
var currentMarkIndex = 0;
var scrollToElementOffset = 0;
var oldScrollTop = 0;

var incDecCurrentMarkIndex = function(incDec){
    if (incDec === undefined){incDec = 1}
    var curScrollTop = $('#maincontent').scrollTop()
    if(Math.abs(curScrollTop-oldScrollTop)>100){
        currentMarkIndex = getNearestMarkIndex() + incDec;
    }else{
        currentMarkIndex = currentMarkIndex + incDec;
    }
    if(currentMarkIndex >= markSpans.length){currentMarkIndex = 0;}
    if(currentMarkIndex < 0){currentMarkIndex = markSpans.length -1;}
    oldScrollTop = curScrollTop
    return currentMarkIndex
}

var showPrevNextBtn = function(){
    $("#previousSearchResult").removeClass("displaynone")
    $("#nextSearchResult").removeClass("displaynone")
}
var hidePrevNextBtn = function(){
    $("#previousSearchResult").addClass("displaynone")
    $("#nextSearchResult").addClass("displaynone")
}

var markText = function(text){
    if(text.length > 1){
    currentMarkIndex = 0;
    var searchContext = $("#maincontent")
    searchContext.unmark()
    searchContext.mark(text, {separateWordSearch: false})
    markSpans = searchContext.find('mark');
    closeAllCollapseDivs()
    markSpans.each(function(){
        openCollapsedDivs($(this))
    })
    hidePrevNextBtn()
    if(markSpans.length > 1){
        showPrevNextBtn()
    }
    scrollToMarkIndex(0);
    highlightMarkIndex(0);
    highlightNav(markSpans);
    }else{
        closeAllCollapseDivs()
        hidePrevNextBtn()
        $('.nav a').removeClass('activecolor')
        $("#maincontent").unmark()
        currentMarkIndex = 0;
        markSpans = [];
    }
}

var highlightNav = function(markSpans) {
    var curChapterAndSubchapter
    var chapters = []
    var subchapters = []

    markSpans.each(function(index){
        curChapterAndSubchapter = getContainingChapterAndSubchapterIds($(this));
        if(chapters.indexOf(curChapterAndSubchapter.chapter)==-1){
            chapters.push(curChapterAndSubchapter.chapter)
        }
        if(curChapterAndSubchapter.subchapter){
            if(subchapters.indexOf(curChapterAndSubchapter.subchapter)==-1){
                subchapters.push(curChapterAndSubchapter.subchapter)
            }
        }
    })
    $('.nav a').removeClass('activecolor')
    chapters.concat(subchapters).forEach(function(chapterId){
        $('.nav a[href$="#' + chapterId + '"]').addClass("activecolor")
    })

}

var openCollapsedDivs = function(mark){
    if(mark.parents('.collapse').length){
        mark.parents('.collapse').each(function(){
            $(this).addClass("in")
        })
    }
}

var closeAllCollapseDivs = function(){
    $('.collapse').removeClass("in")
}

var getContainingChapterAndSubchapterIds = function(mark){
    var answer = {}
    if(mark.parents('.chapter').length){
        answer.chapter = $(mark.parents('.chapter').eq(0)).attr('id');
    }
    if(mark.parents('.subchapter1').length){
        answer.subchapter = $(mark.parents('.subchapter1').eq(0)).attr('id');
    }
    return answer
}

var getNearestMarkIndex = function(){
    var nearestIndex = 0;
    if(markSpans.length > 1){
        markSpans.each(function(index){
            if($(this).offset().top - $('#maincontent').scrollTop() <= 0){nearestIndex = index}
        })
    }
    return nearestIndex
}

var scrollToMarkIndex = function(index){
    if(markSpans.length > 0){
        var mark = markSpans.eq(Math.min(markSpans.length, index));
        scrollToElement(mark, $('#maincontent').height()/1.5)
        //scrollToElement(mark)
        oldScrollTop = $('#maincontent').scrollTop()
    }
}

var highlightMarkIndex = function(index){
    if(markSpans.length > 0){
        markSpans.removeClass("active")
        $(markSpans.eq(Math.min(markSpans.length, index))).addClass("active");
    }
}

var getMarkOffsetTop = function(mark){
    return mark.offset().top+$('#maincontent').scrollTop()
}

var scrollToElement = function(mark, withinRange){
    if(!withinRange){
        $('#maincontent').scrollTop(getMarkOffsetTop(mark))
    }else{
        var oldPos = $('#maincontent').scrollTop();
        var newPos = getMarkOffsetTop(mark);
        if(!(newPos > oldPos && newPos < oldPos + withinRange)){
            $('#maincontent').scrollTop(getMarkOffsetTop(mark))
        }
    }
}

var mainNgApp = angular.module("mainNgApp", ['ui.bootstrap-slider', 'vs-repeat', 'ui.bootstrap', 'dndLists', 'pr.longpress', 'pr.rightclick']);

mainNgApp.controller("baseController", ["$scope", function ($scope) {
    $scope.safeApply = function(fn) {
      var phase = this.$root.$$phase;
      if(phase == '$apply' || phase == '$digest') {
        if(fn && (typeof(fn) === 'function')) {
          fn();
        }
      } else {
        this.$apply(fn);
      }
    };
    $scope.iconClasses = iconClasses
    $scope.mapcompSyncGlobally = true
    $scope.hiddenPrefs = function(evt){
        if (evt.altKey){
            $scope.showHiddenPrefs = true
        }
    }
}])

function init() {
    $('body').removeClass("displaynone")
    $(document.body).on("dragover drop", function(event){
        event.preventDefault()
    })

    themeManager.init();
    $("#searchInput").on('input', function(e){
        markText($("#searchInput").val())
    })

    $("#previousSearchResult").on('click', function(e){
        scrollToMarkIndex(incDecCurrentMarkIndex(-1));
        highlightMarkIndex(currentMarkIndex)

    })
    $("#nextSearchResult").on('click', function(e){
        scrollToMarkIndex(incDecCurrentMarkIndex(1));
        highlightMarkIndex(currentMarkIndex)
    })

    var searchInput = $('#searchInput')
    searchInput.focus();
    searchInput.select();
}

$(document).ready(function(){init()});
