$(function() {
    
    /**
     * Search form validation
     */    
    $('#search').submit(function() {
    	if($('#search-query').val().length < 3){
    	  alert(srchVerAlert);
    	  return false;
    	}
    });
    
    $('#feedback a, #feedback-footer').click(function() {
        $.get(this.href, function(data) {$.modal(data, {opacity: 80, minHeight: 200, minWidth: 450});});return false;
    });
     
    /**
     * Function for adding help into input, textarea .. etc.
     */
    addHelpToInput = function(elm) {
    	if(($(elm).attr("origval") == $(elm).val()) || typeof $(elm).attr("origval") == 'undefined'){
    		
	    	$(elm).attr("origval", $(elm).val());
	
	        $(elm).bind('focus',function(event){
	            if($(this).val() == $(this).attr("origval")) $(this).val("");
	        }).bind('blur',function(event){
	            if($(this).val() == "") $(this).val($(this).attr("origval"));
	        });
    	}
    }
        

    /**
     * Set up maximim length of value of input
     */
    setMaxLength = function(input){
      $(input+'[maxlength]').keyup(function(){
    		var max = parseInt($(this).attr('maxlength'));
    		if($(this).val().length > max){
    			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
    		}	
    	});
    }

    /**
     * Set up tooltip elements
     */
    $('.hastooltip').each(function(){

       var obj = $(this);
       var title = obj.attr('title');
       var position = obj.position();
       if(title.length > 13){
           cls = 'big';
           position.left = position.left + obj.width()/2 - 133;
           position.top = position.top + 30;
       }else{
           cls = '';
           position.left = position.left + obj.width()/2 - 55;
           position.top = position.top + 20;
       }
       

       var tooltip = $('<div class="tooltip '+cls+'">'+title+'</div>').hide().css(position);
       if(title != ''){
           
           obj.after(tooltip);

           obj.bind('mouseover',function(e){
               tooltip.show();
           });

           obj.bind('mouseout',function(e){
               tooltip.hide();
           });
           
       }
    });

    /*
        if($('.aktuality-line-content')){
            $('.aktuality-line-content div:gt(0)').hide();
            setInterval( function(){
                $('.aktuality-line-content div:last').
                    insertBefore($('.aktuality-line-content div:first')).fadeIn();
                $('.aktuality-line-content div:visible:last').fadeOut();
            }, 5000);
        }
    */
   
    if($('.aktuality-line-content .element').length > 3){
        
        function newsLineForward(){

              $('.aktuality-line-content .element:last').
                                        insertBefore($('.aktuality-line-content .element:first')).animate({
                                            width: 'toggle'
                                          }, 'slow', function(){
                                              $('.aktuality-line-content .element:visible:last').hide();
                                          });

              return false;
        }

        function newsLineback(){
              $('.aktuality-line-content .element:hidden:first').show();
              $('.aktuality-line-content .element:first').animate({
                                            width: 'toggle'
                                          }, 'slow', function(){
                                              $('.aktuality-line-content .element:first').hide().insertAfter($('.aktuality-line-content .element:last'));
                                              
                                          });

              return false;
                                          
        }

        $('#aktuality-line').mouseenter(function(){
            //clearInterval (timer);
        })

        $('#aktuality-line').mouseleave(function(){
            //timer = setInterval( newsLineForward, 5000);
        })
        
        $('.aktuality-line-content .element:gt(2)').hide();

       // timer = setInterval( newsLineForward, 5000);

        $('#news-line-next').click(newsLineback);
        $('#news-line-prev').click(newsLineForward);
    }

    /**
     * Create search list dropdown item menu - onclick
     * Temporary disabled search list
     */
    $('#filter li').bind('click', function(event) {
        $('#filter ul').children().removeClass('disabled');

        if($(this).attr('id').replace('type_','') == $('#section').attr('value')) {

            if(!$(this).hasClass('control')) {
                $('#filter ul').children().removeClass('control').addClass('disabled');
                $(this).removeClass('disabled').addClass('control');
            } else $(this).removeClass('control');
            
        } else {

            $('#section').attr('value', $(this).attr('id').replace('type_',''));
            $('#filter ul').children().removeClass('control').addClass('disabled');
            $(this).removeClass('disabled').addClass('control');
            $('#typeForm').submit();
        }
        return false;
    });



    /**
     * Create
     *
     */
    if($('#sectionContent .hastoc').length > 0){
                
        templ = '';
        sel = '';
        
        $.each(tocsections, function(i,sect){
            if(i == tocselected) sel = 'selected'; else sel = 'hidden';

            templ += '<a class="toc-title '+sel+' node0" href="' + (i == tocselected ? 'javascript:tocOpen(\''+sect[1]+'\');' : i) + '" id="'+ sect[1] +'">'+sect[0]+'</a><div class="toc-body '+sel+'">'+sect[2]+'</div>';
        });

        templ = '<div class="toc">'+templ+'</div>';
        var container = $('#sectionContent .hastoc');
        var toc = $(templ).insertBefore('#sectionContent .hastoc').find('.toc-body.selected');

        $('<div class="tochelp"></div>').insertBefore('#sectionContent .hastoc');

        container.addClass('active');
        parind = '0';
        $('#sectionContent .hastoc').find('h3').each(function(ind,h3){
            
            $(h3).attr('id', 'shr3' + ind );

            var prh3 = $('<a class="node1" href="#shr3'+ ind +'">'+ $(h3).text() +'</a>');
            var parind = ind;

            cut(prh3,30);
            $(prh3).attr('id', 'hr3' + ind );

            toc.append(prh3);
            var ln = $(h3).next().find('h4').length;

            $(h3).next().find('h4').each(function(ind,h4){
                
                $(h4).attr('id', 'shr4' +  parind +  ind );
                var prh4 = $('<a class="node2" href="#shr4'+ parind +  ind +'">'+ $(h4).text() +'</a>');

                cut(prh4,30);
                
                toc.append(prh4);

                $(prh4).attr('id', 'hr4' + parind + ind );
                if(ln == (ind+1))
                    $(prh4).addClass('last');
            });
            
        });
        
        var anchs = $(toc).find('*[class^=node]');
        
        $(toc).find('*[id^=hr]').click(function(e){

            $.scrollTo('#s' + $(this).attr('id'),800);

            anchs.each(function(ind,el){cut(el,30);});

            clearTimeout(t);

            $("#sectionContent .toc").removeClass("active");


            return false;
        });
        
       

        $("#sectionContent .toc").mouseenter(function(e){
               

               if(!$(this).hasClass("active")){

                   t = setTimeout('$("#sectionContent .toc").find("*[class^=node]").each(function(ind,el){cut(el,60);});$("#sectionContent .toc").addClass("active");clearTimeout(t);',700);
/*
                   anchs.each(function(ind,el){
                        cut(el,60);
                   });


                   $(this).addClass("active");
  */
                   
               }
                

        }).mouseleave(function(e){



               anchs.each(function(ind,el){cut(el,30);});
               
               clearTimeout(t);
               
               $(this).removeClass("active");
               
               /*
               $(this).stop().animate({
                        width: '280px'
               }, 300, function(){$(this).removeClass("active");});
*/
            
               
        });

        function showPanel(){
            anchs.each(function(ind,el){cut(el,60);});toc.parent().addClass("active");
        }
        
        var $sidebar   = $(".toc"),
        $window    = $(window),
        offset     = $sidebar.offset(),
        topPadding = 25;
        //l(offset);
        $window.scroll(function() {
            if ($window.scrollTop() > offset.top) {

                if(($window.scrollTop() - offset.top + topPadding +  $sidebar.height()) < container.height())
                    $sidebar.stop().animate({
                        marginTop: $window.scrollTop() - offset.top + topPadding
                    }, 300);

            } else {
                $sidebar.stop().animate({
                    marginTop: 0
                }, 300);
            }
        });



    }

});

 var t;
 
function tocOpen(t){
    
    if( $('#'+t).hasClass('selected'))
        $('#'+t).removeClass('selected').next().slideUp().addClass('hidden');
    else
        $('#'+t).addClass('selected').next().slideDown().removeClass('hidden');
}

function l(s, e){
    
    if(e)
        console.warn(s);
    else
        console.info(s);
    
}

function cut(el,len){

   if($(el).attr('orig') == undefined)
       $(el).attr('orig', $(el).text());

   $(el).text(truncate($(el).attr('orig'), len));
}

function truncate(string, length, delimiter) {

   delimiter = delimiter || "...";
   
   if(string.length > length){

       var wordsArray = string.split(" ");
       // This will keep our generated text

       var cutted = "";
       var i = 0;
       var l = 0;
       while (l <= length){
          cutted += wordsArray[i] + " ";
          l = cutted + wordsArray[i+1] + " ";
          l = l.length;
          i++;
       }
       
       return $.trim(cutted) + delimiter;
   }else
        return string;
};

