// requires jquery.ba-dotimeout.min.js

$(document).ready(function() {

   /* SOCIAL */
   window.fbAsyncInit = function() { FB.init({status: true, cookie: true, xfbml: true}); }; // appId: 'XXXXXXXXXXXXXXX',
   window.___gcfg = {lang: 'de'}; // g+
   (function() {
      var s = document.getElementById('social-embed');
      var gplus = document.createElement('script');
      gplus.type = 'text/javascript';
      gplus.async = true;
      gplus.src = 'https://apis.google.com/js/plusone.js';
      s.appendChild(gplus);
      var e = document.createElement('script');
      e.async = true;
      e.type = 'text/javascript';
      e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
      s.appendChild(e);
   })();


   /* AUDIO */
   /*
   var PP_CONFIG = {
      flashVersion: 9,       // version of Flash to tell SoundManager to use - either 8 or 9. Flash 9 required for peak / spectrum data.
      useMovieStar: true,    // Flash 9.0r115+ only: Support for a subset of MPEG4 formats.
      useVideo: true         // show video when applicable
   }
   soundManager.useFlashBlock = true;
   soundManager.url = '/sm/';
   soundManager.bgColor = '#000000'; // for full-screen
   soundManager.debugMode = true;
   */


   /* VIDEO */
   /* VideoJS.setupAllWhenReady(); */


   /* carousel for images */
/*    $('#mycarousel').jcarousel({
      scroll: 2,
      visible: 4
   });  */
 

   /* lightbox for images */
/*    $('#sub_images a').lightBox();
   $('#main_image a').lightBox(); */


   /* popup-windows */
   $('a.popup').live('click', function(e) {
      var link = $(this);
      var title = $(this).attr('title');
      if( title.trim() == '' )
         title = $(this).text();
      var offsetX = $(window).scrollLeft();
      var offsetY = $(window).scrollTop();
      var previousFocusOwner = document.activeElement;
      var previousOpacity = $('.ui-widget-content').css( "opacity" );
      var previousAlpha = $('.ui-widget-content').css( "filter" );
      var heightWaitingPopup = 110;
      var initialHeight = 0;
      var width = 700; // default AnnotatedObjectWidth
      if( link.attr('href').indexOf( 'uri/Video' ) != -1 ) {
         width = 730;
      }
      var fadeDuration = 500;
      var maxHeight = 500;
      var dialogLoading = $('<div><div class="popup_loading">&nbsp;</div></div>');
      /*$.doTimeout( 'loading', 750, function() {
    	 console.log('doing timeout')
         dialogLoading.dialog({
            autoOpen: false,
            width: width,
            height: heightWaitingPopup,
            modal: false,
            show: {
               effect: 'fold'
            },
            hide: {
               effect: 'fade',
               duration: fadeDuration
            },
            title: title,
            position: [e.pageX-offsetX+5, e.pageY-offsetY+5],
            open: function(event, ui) {
               $('.ui-dialog-titlebar-close').attr('title', 'Zum Schließen die ESC-Taste betätigen');
            }
         }).dialog( 'open' );
      });*/
      var image_width;
      var popup_width;
      var click_source = this;
      $(this).addClass("learnbg");
      var dialog = $('<div></div>');
      dialog.load(link.attr('href'), function() {
    	 console.log('loading now')
         dialog.dialog({
         autoOpen: false,
            width: width,
            height: initialHeight,
            modal: false,
            show: {
               effect: 'fold',
               complete: function() {
                  /*if( $.doTimeout( 'loading' ) == undefined ) // cancels timeout, returns undefined, if nothing left to cancel anymore (already executed)
                     dialogLoading.dialog( 'close' ); // thus we have to close the dialog now*/
                  $(this).focus(); // cf. http://stackoverflow.com/questions/3603854/why-does-my-jquery-ui-dialog-lose-the-focus-when-it-finishes-the-open-effect
                  $( '.ui-dialog-content', this ).animate( { height: Math.min( $('.box', this ).height(), maxHeight ) }, 'fast' );
                  //FB.XFBML.parse( $( this ).closest( "#popup_fb").get( 0 ) ); // makes sure, the FB button gets rendered
                  FB.XFBML.parse( ); // makes sure, the FB button gets rendered
                  // on blur let all dialogs lose their highlighting
                  $(this).blur( function( e ) {
                     $(".ui-dialog")
                        .find(".ui-dialog-titlebar")
                        .removeClass("focused_popup");
                     $(".ui-dialog.ui-widget-content")
                        .removeClass("focused_popup");
                  });
               }
            },
            hide: 'fold',
            title: title,
            position: [e.pageX-offsetX+5, e.pageY-offsetY+5],
            open: function(event, ui) {
               $('.ui-dialog-titlebar-close').attr('title', 'Zum Schließen die ESC-Taste betätigen');
               if( link.attr('href').indexOf( 'uri/Video' ) != -1 ) {
                  // we must set opacity to 1, so the video is not translucent
                  $('.ui-widget-content').css( "opacity", "1.0" );
                  $('.ui-widget-content').css( "filter", "Alpha(Opacity=100)" );
               }
            },
            close: function(event, ui) {
               $('.ui-widget-content').css( "opacity", previousOpacity );
               $('.ui-widget-content').css( "filter", previousAlpha );
               previousFocusOwner.focus(); // restore focus owner so stacked popups can be closed nicely
               $(previousFocusOwner).dialog( "moveToTop" );
               $(previousFocusOwner).find(".ui-dialog-titlebar")
                  .addClass("focused_popup");
               $(previousFocusOwner).dialog( "widget" )
                  .addClass("focused_popup");
                  $(click_source).removeClass("learnbg");
            },
            focus: function (event, ui) {
               $(".ui-dialog")
                  .find(".ui-dialog-titlebar")
                  .removeClass("focused_popup");
               $(".ui-dialog.ui-widget-content")
                  .removeClass("focused_popup");
               $(this).parents(".ui-dialog:first")
                  .find(".ui-dialog-titlebar")
                  .addClass("focused_popup");
               $(this).dialog( "widget" )
                  .addClass("focused_popup");
            },
            resizeStart: function(event, ui) {
               if( dialog.find( 'img.image' ) != null ) {
                  image_width = dialog.find( 'img.image' ).width();
                  popup_width = dialog.parent().find( '.ui-dialog-content' ).width();
               }
            },
            resizeStop: function(event, ui) {
               if( dialog.find( 'img.image' ) != null ) {
                  var additional_width = dialog.parent().find( '.ui-dialog-content' ).width() - popup_width;
                  var new_width = image_width + additional_width;
                  var src = dialog.find( 'img.image' ).attr( 'src' );
                  var new_src = src.replace( /w\d+/, 'w' + new_width );
                  dialog.find( 'img.image' ).attr( 'src', new_src );
                  dialog.find( 'img.image' ).width( new_width );
               }
            }
         }).dialog('open');
      });
      return false;
   });


   // required?
   $('.popup').live('hover', function( e ) {
      var offsetX = $(window).scrollLeft();
      var offsetY = $(window).scrollTop();
      $('.popup').dialog( "option", { position: [e.pageX-offsetX+5, e.pageY-offsetY+5] } );
   });


   /* ANNOTATE */

   // annotate-window
   $('a.annotate').live('click', function(e) {
      var link = $(this);
      var title = $(this).attr('title');
      if( title.trim() == '' )
         title = $(this).text();
      var offsetX = $(window).scrollLeft();
      var offsetY = $(window).scrollTop();
      var previousFocusOwner = document.activeElement;
      var heightWaitingAnnotate = 110;
      var initialHeight = 0;
      var width = 675;
      var maxHeight = 500;
      var fadeDuration = 500;
      var dialogLoading = $('<div><div class="annotate_loading">&nbsp;</div></div>');
      /*$.doTimeout( 'loading', 750, function() {
         dialogLoading.dialog({
            autoOpen: false,
            width: width,
            height: heightWaitingAnnotate,
            modal: false,
            show: {
               effect: 'fold'
            },
            hide: {
               effect: 'fade',
               duration: fadeDuration
            },
            title: title,
            position: [e.pageX-offsetX+5, e.pageY-offsetY+5],
            open: function(event, ui) {
               $('.ui-dialog-titlebar-close').attr('title', 'Zum Schließen die ESC-Taste betätigen');
            }
         }).dialog( 'open' );
      });*/
      var dialog = $('<div id="annotation_dialog"></div>');
      dialog.load(link.attr('href'), function() {
         dialog.dialog({
         autoOpen: false,
            width: width,
            height: initialHeight,
            modal: false,
            show: {
               effect: 'fold',
               complete: function() {
                  /*if( $.doTimeout( 'loading' ) == undefined ) // cancels timeout, returns undefined, if nothing left to cancel anymore (already executed)
                     dialogLoading.dialog( 'close' ); // thus we have to close the dialog now*/
                  $(this).focus(); // cf. http://stackoverflow.com/questions/3603854/why-does-my-jquery-ui-dialog-lose-the-focus-when-it-finishes-the-open-effect
                  var height = Math.min( $('.box', this ).height(), maxHeight );
                  $( '.ui-dialog-content', this ).animate( { height: height }, 50 );
                  $( '.box', this ).css( 'height', height );
                  $( '#AnnotationsText', this ).elastic();
                  $( '#AnnotationsText', this ).closest( 'form' ).submit( function() {
                     return false; // prevent regular form submission
                  });
                  $( '#AnnotationsText', this ).keydown( function( event ) {
                     var code = ( event.keyCode ? event.keyCode : ( event.charCode ? event.charCode : -1 ) ); // Work around bug in event.which
                     if( code == 13 ) { // enter
                        $( this ).closest( 'form' ).submit(); // trigger submit event, which we can pick up and process in the page
                     }
                  });
                  FB.XFBML.parse( $( this ).closest( "#annotation_fb").get( 0 ) ); // makes sure, the FB button gets rendered
                  // on blur let all dialogs lose their highlighting
                  $(this).blur( function( e ) {
                     $(".ui-dialog")
                        .find(".ui-dialog-titlebar")
                        .removeClass("focused_popup");
                     $(".ui-dialog.ui-widget-content")
                        .removeClass("focused_popup");
                  });
                  createTableColumnPseudoClasses();
               }
            },
            hide: 'fold',
            title: title,
            position: [e.pageX-offsetX+5, e.pageY-offsetY+5],
            open: function(event, ui) {
               $('.ui-dialog-titlebar-close').attr('title', 'Zum Schließen die ESC-Taste betätigen');
            },
            close: function(event, ui) {
               previousFocusOwner.focus(); // restore focus owner so stacked annotations can be closed nicely
               $(previousFocusOwner).dialog( "moveToTop" );
               $(previousFocusOwner).find(".ui-dialog-titlebar")
                  .addClass("focused_popup");
               $(previousFocusOwner).dialog( "widget" )
                  .addClass("focused_popup");
            },
            focus: function (event, ui) {
               $(".ui-dialog")
                  .find(".ui-dialog-titlebar")
                  .removeClass("focused_popup");
               $(".ui-dialog.ui-widget-content")
                  .removeClass("focused_popup");
               $(this).parents(".ui-dialog:first")
                  .find(".ui-dialog-titlebar")
                  .addClass("focused_popup");
               $(this).dialog( "widget" )
                  .addClass("focused_popup");
            }
         }).dialog('open');
      });
      return false;
   });


   /*
   // Hover-Effect via JS
   $('body').removeClass( 'use-hover' );
   $('a').live( 'mouseover mouseout', function( e ) {
      var color = $(this).data( 'pauxcolor' );
      if( color == null ) {
         color = $(this).css( 'color' );
         $(this).data( 'pauxcolor', color );
         //alert( "storing color: "+color );
      }
      if ( e.type == "mouseover" ) {
         $(this)
         .css('color', color )
         .animate( {'color': 'red'}, 400 );
      } else {
         $(this)
         .animate( {'color': color}, 400 );
      }
   });
   */

   /*
   // VORSCHAU FUER BILDER onMouseOver
   var xOffset = 10;
   var yOffset = 30;
   $("a.vorschau img").live( 'mouseenter', function( e ) {
      this.t = this.title;
      this.title = "";
      var c = (this.t != "") ? "<br/>" + this.t : "";
      // quite crude way to get the correct uri, but works for now...
      $("body").append("<p id='vorschau'><img src='"+ this.src.replace(/w\d+/,'w'+Math.round($( window ).width()*0.7)).replace(/h\d+/,'h'+Math.round($( window ).height()*0.7)) +"' alt='Vorschau'/>"+ c +"</p>");
      $("#vorschau")
         .css("top",(e.pageY - xOffset) + "px")
         .css("left",(e.pageX + yOffset) + "px")
         .fadeIn("fast");
   }).live( 'mouseleave', function() {
      this.title = this.t;
      $("#vorschau").remove();
   });
   $("a.vorschau").live( 'mousemove', function( e ) {
      $("#vorschau")
         .css("top",(e.pageY - xOffset) + "px")
         .css("left",(e.pageX + yOffset) + "px");
   });
   */

});


function attach2ndNaviTo1stNavi() {
   $("#PrimaryNavigation span").live( 'mouseover', function( e ) {
      var span = $(this);
      jQuery.ajax( {
         type: 'POST',
         data: {
            lektion: span.attr("id")
         },
         url: '/menu/sub',
         success: function( data, textStatus ) {
            $('#SecondaryNavigation').html( data );
            var offset = span.offset();
            $('#SecondaryNavigation').css( 'left', offset.left - parseFloat( span.find('a').css( 'padding-left' ) ) + 'px' );
            $('#SecondaryNavigation').show( 'fast' );
         },
         error: function( XMLHttpRequest, textStatus, errorThrown ) {}
      } );
   });
   $("#SecondaryNavigation div.Item a span span").live( 'mouseover', function( e ) {
      var div = $(this).parents( 'div.Item' );
      jQuery.ajax( {
         type: 'POST',
         data: {
            lektion: div.attr( 'id' )
         },
         url: '/menu/sub',
         success: function( data, textStatus ) {
            var subid = 'sub_' + div.attr( 'id' );
            $('#SecondaryNavigation').html( data );
            /*
            $('#SecondaryNavigation').append( '<div id="' + subid + '">' + data + '</div>' );
            var offset = div.parent('span').offset();
            $('#'+subid).css( 'left', offset.left - parseFloat( div.find('a').css( 'padding-left' ) ) + 'px' );
            $('#'+subid).css( 'top', offset.top - parseFloat( div.find('a').css( 'padding-top' ) ) + 'px' );
            $('#'+subid).show( 'fast' );
            */
         },
         error: function( XMLHttpRequest, textStatus, errorThrown ) {}
      } );
   });
   $("#Header").live( 'mouseenter', function( e ) {
      $('#SecondaryNavigation').hide( 'fast' );
   });
   $("#main").live( 'click', function( e ) {
      $('#SecondaryNavigation').hide( 'fast' );
   });
}



/* LERNEBENEN */

function show_antwort() {
   if( $("#richtig_falsch_button") != null ) $("#richtig_falsch_button").css( "display", "inline" );
   $("#antwort").css( "display", "block" );
   if( $("#antwort_kuerzen_button_wrapper") != null ) $("#antwort_kuerzen_button_wrapper").css( "display", "block" );
   if( $("#zwischenweiter") != null ) $("#zwischenweiter").html( "" );
   if( $("#antwort_zeigen_link") != null ) $("#antwort_zeigen_link").html( "" );
}

function show_zwischenantwort( nr, total ) {
   $("#zwischenantwort"+nr).css( "display", "block" );
   var tmp = nr + 1;
   if( $("#zwischenfrage"+tmp) == null ) {
      $("#zwischenweiter").html( '<a href="#" onClick="show_antwort(); return false;" class="navigational">weiter</a>' );
   } else {
      $("#zwischenweiter").html( '<a href="#" onClick="show_zwischenfrage( '+tmp+' ); return false;" class="navigational">weiter</a>' );
   }
   for ( i = 1; i <= total; i++ ) {
      if( i == nr ) {
         $("#zwischenantwortanchor"+i).removeClass( "navigational" );
         $("#zwischenantwortanchor"+i).addClass( "navigational_active" );
      }
      else {
         $("#zwischenantwortanchor"+i).removeClass( "navigational_active" );
         $("#zwischenantwortanchor"+i).addClass( "navigational" );
      }
      $("#zwischenfrageanchor"+i).removeClass( "navigational_active" );
      $("#zwischenfrageanchor"+i).addClass( "navigational" );
   }
}

function show_zwischenfrage( nr, total ) {
   $("#zwischenfrage"+nr).css( "display", "block" );
   var tmp = nr * 2 - 1;
   $("#zwischenweiter").html( '<a href="#" onClick="show_zwischenantwort( '+nr+' ); return false;" class="navigational">weiter</a>' );
   for ( i = 1; i <= total; i++ ) {
      if( i == nr ) {
         $("#zwischenfrageanchor"+i).removeClass( "navigational" );
         $("#zwischenfrageanchor"+i).addClass( "navigational_active" );
      }
      else {
         $("#zwischenfrageanchor"+i).removeClass( "navigational_active" );
         $("#zwischenfrageanchor"+i).addClass( "navigational" );
      }
      $("#zwischenantwortanchor"+i).removeClass( "navigational_active" );
      $("#zwischenantwortanchor"+i).addClass( "navigational" );
   }
}



/* ANNOTATE */

function resize_annotation_popup( domelement ) {
   var dialog = domelement.parents( '#annotation_dialog' );
   var dialog_content = domelement.parents( '.ui-dialog-content' );
   var box = dialog_content.find( '.box' );
   if( parseFloat( dialog_content.css( 'height' ) ) < dialog_content.attr( 'scrollHeight' ) ) {
      var newheight = Math.min( jQuery( window ).height(), dialog_content.attr( 'scrollHeight' ) + dialog.prev().height() );
      dialog.dialog( 'option', 'height', newheight );
      dialog.dialog( 'option', 'position', 'center' );
      box.css( 'height', dialog_content.attr( 'scrollHeight' ) );
   }
   dialog.focus();
}

function createTableColumnPseudoClasses() {
   $("tr").each( function()  {
      var counter = 1;
      $(this).children("td,th").each( function()  {
         $(this).addClass("column-" + counter);
         counter++;
      });
   });
}

/*  Show and Hide the AnnotationButton*/
function showAnnotationButton( hreftext ){
	$('a[href*="index/' + hreftext + '"]').parent().css("visibility", "visible");
}
function hideAnnotationButton( hreftext ){
	$('a[href*="index/' + hreftext + '"]').parent().css("visibility", "hidden");
	$('a[href*="http://"]').parent().css("visibility", "visible");
}
function hideAllNewAnnotationButtons(){
	$('a[class*="NewAnnotationLink"]').parent().css("visibility", "hidden");
}
/*  Show and Hide the AnnotationRow*/
function showAnnotationRow( hreftext ){
	$('input[name="info_' + hreftext + '"]').parent().css('display', 'block');
}
function hideAnnotationRow( hreftext ){
	$('input[name="info_' + hreftext + '"]').parent().css('display', 'none');
}
function hideAllNewAnnotationRow(){
	$('div[class*="AnnotationSmallForm"]').parent().css('display', 'none');
}

// MY onload function
function myOnloadFunction(){
	hideAllNewAnnotationButtons();
	
	// these function is keeping the site upTo date
    myUpdater();
}

function jumpToPage(){
	jQuery.ajax({
		   url: '/jumpToPage/' + $('#jumpInput').val(),
		   success: function(data){
			   window.location = data;
		   }
		 });
}

function myUpdater(){
	
	updateWorker('updateAllAnnotations()', 10000);
	updateWorker('updateFacebookLikeCounts()', 10000);
}

// updating everthing
function updateWorker(jsfunction, delay){
	
	eval(jsfunction);
	setTimeout('updateWorker(\'' + jsfunction + '\', ' + delay + ')', delay);				
}


// memories if an update is running
var annotationUpdateIsRunning = 0;

//get all AnnotationUpdateElements and trigger ajax update
function updateAllAnnotations(){
	
	if(annotationUpdateIsRunning == 0){
		annotationUpdateIsRunning = 1;
		var elements = $('div[id^="AnnotationUpdateElement"]');
		
		var updateElements = '';
		if(elements.length > 0){
			for (var i = 0; i <  elements.length; i++) {
				
				var updateElement = elements[i];
				var pictureUpdate = false;
				
				if(jQuery(updateElement).closest('div[class="AnnotationAnWrapper"]').children('div[class="AnnotationAnAvatar"]').children('img').attr('src') == '/images/avatar.png'){
					pictureUpdate = true;	
				}
				
				var element = updateElement.id.substring('AnnotationUpdateElement_'.length);
				
				if(updateElements.indexOf(element) == -1){
					if(i > 0)
						updateElements = updateElements.concat('+');
				
					updateElements = updateElements.concat(pictureUpdate ? 'x_' : '').concat(element);
				}
			}
			refreshAnnotationAn(updateElements);
		}
		elements = null;
		updateElements = null;
		annotationUpdateIsRunning = 0;
	}else{
		console.log('AnnotationUpdate is already running.')
	}
}

/* Updates the annotations */
function refreshAnnotationAn(updateElements){
	jQuery.ajax({
		  type: 'POST',
		  url: '/annotation/updateAnnotations/' + updateElements,
		  beforeSend:function(){
			  // here we can show an loading  image or something else
		  },
		  success:function(data){		    // successful request; do something with the data
			if(data != null && data.trim().length > 0){
				var div = document.createElement('div');
			    div.innerHTML = data.trim();
			    
			    var elements = $(div).children('div');
			    var element = null;
			    
			    //console.log('found: ' + elements.size());
			    for(var i = 0; i < elements.size(); i++){
			    	if(element == null)
			    		element = elements.first('div');
			    	else
			    		element = element.next('div');
			    	
			    	var parents = $('div[id^="AnnotationUpdateElement_' + element.attr('id') +'"]')
			    	
			    	if(jQuery(element).find('div[id^="AnnotationUpdateElement_' + element.attr('id') +'"]').size() > 0){
			    		// i found a new Picture in database, lets update
			    		
			    		element.children('div').children('div[class="AnnotationAnAvatar"]').replaceAll(parents.closest('div[class="AnnotationAnWrapper"]').children('div[class="AnnotationAnAvatar"]')).slideDown('slow');
			    		
			    		var newUsername = element.children('div').children('div[class^="AnnotationAnBox"]').children('div[class="AnnotationAnEigeneAnnotation"]').children('div[class="AnnotationAnHeader"]').children('div[class="AnnotationAnUser"]');
			    		var oldUsername = parents.closest('div[class="AnnotationAnWrapper"]').children('div[class^="AnnotationAnBox"]').children('div[class="AnnotationAnEigeneAnnotation"]').children('div[class="AnnotationAnHeader"]').children('div[class="AnnotationAnUser"]');
			    		newUsername.replaceAll(oldUsername);
			    		
			    	}else{			    	
				    	//add a new annotation
				    	element.children('div').hide().prependTo(parents).slideDown('slow');
				    	
				    	// update all other numbers for the popup
				    	for(var j = 0; j < parents.size(); j++){
				    		updateElementNumbers(parents[j]);
				    		
				    		var attributes = jQuery(parents[j]).attr('id').substring('AnnotationUpdateElement_'.length).split('_')
				    		
				    		updateElementButtons(attributes[0], attributes[1], 1);
				    	}
			    	}
			    }
			}
		  },
		  error:function(){
		    // failed request; give feedback to user
		    console.log("Update of Annotations: '" + updateElements + "' failed.");
		  }
		});
}

function updateElementNumbers(element){
        // update number of annotations in the titlebar
		var popUpHeader = jQuery(element).closest('div[class*="ui-dialog "]');
        var title = popUpHeader.find('#ui-dialog-title-annotation_dialog');
        
        var number = popUpHeader.find('div[id^="AnnotationUpdateElement"]').size() - 1;
        
        if(title.children('span').size() > 0){
            title.children('span').html(number);
        }else{
            var titleHtml = title.html() + ' (bisher <span>' + number + '</span> Kommentar';
            if(parseInt(number) > 1)
                titleHtml = titleHtml + 'e';
             
            title.html(titleHtml + ')');
        }
}

function updateElementButtons(id, annotationObject, annotationsOnPage){
	
	var buttons = $('a[href="/annotation/index/' + id + '/' + annotationObject + '"]');
	
	for (var i = 0; i <  buttons.length; i++) {
		
		if(annotationsOnPage > 0){
		    jQuery(buttons[i]).attr('class', 'AnnotationLink annotate');
		    jQuery(buttons[i]).parent().css("visibility", "visible");
		    var parentDiv = jQuery(buttons[i]).closest('div[onmouseover*="showAnnotation"]');
		    jQuery(parentDiv).attr('onmouseover', '');
		    jQuery(parentDiv).attr('onmouseout', '');
		}else{
			jQuery(buttons[i]).attr('class', 'NewAnnotationLink annotate');
			jQuery(buttons[i]).parent().css("visibility", "hidden");
			var parentDiv = jQuery(buttons[i]).closest('div[onmouseover*="showAnnotation"]');
		    jQuery(parentDiv).attr('onmouseover', 'showAnnotationButton(' + id + ')');
		    jQuery(parentDiv).attr('onmouseout', 'hideAnnotationButton(' + id + ')');
		}
	}
}

// get facebook like counts
function updateFacebookLikeCounts(){
	
	var counters = $('div[class="FacebookLikeCounter"]');
	var updateElements = '';

	for (var i = 0; i < counters.size(); i++) {
		
		var counter = jQuery(counters[i]).closest('div[id^="AnnotationUpdateElement"]');
		var likes = jQuery(counters[i]).children('input[name="likes"]').attr('value');
		var id	  = jQuery(counters[i]).children('input[name^="FacebookLikeCounter"]').attr('value');
		
	    var element = counter.attr('id').substring('AnnotationUpdateElement_'.length).concat('_').concat(id).concat('_').concat(likes);
	    
	    if(updateElements.indexOf(element) == -1){
			if(i > 0)
				updateElements = updateElements.concat('+');
		
			updateElements = updateElements.concat(element);
	    }
	}
	
	if(updateElements.length > 0)
		updateCounter(updateElements)
}

function updateCounter(updateCounters){
	
	var url = '/annotation/updateFacebookLikeCount/' + updateCounters;
    jQuery.ajax({
		  type: 'POST',
		  url: url,
		  success:function(data){		    // successful request; do something with the data
			if(data != null && data.trim().length > 0){
				var div = document.createElement('div');
			    div.innerHTML = data.trim();
			    
			    var elements = $(div).children('div');
			    var element = null;
			    
			    for(var i = 0; i < elements.size(); i++){
			    	if(element == null)
			    		element = elements.first('div');
			    	else
			    		element = element.next('div');
			    	
			    	var parents = $('input[name="FacebookLikeCounter_' + element.attr('id') + '"]').closest('div[class="FacebookLikeCounter"]');
			    	
			    	for(var j = 0; j < parents.size(); j++){

			    		jQuery(parents[j]).children('div[class="likesContent"]').html(jQuery(element).children('div[class="likesContent"]').html());
			    		jQuery(parents[j]).children('input[name="likes"]').attr('value', jQuery(element).children('input[name="likes"]').attr('value'));
			    		
			    	}
			    }   
			}
		  },
		  error:function(){
		    // failed request; give feedback to user
		    console.log("updateFacebookLikeCounts failed for : " + updateCounters);
		  }
		});
}

// autocomplete
$('input[id$="_autocomplete"]').autocomplete({
	autofocus: true,
	source: '/t',
	minLength: 2
}).data( "autocomplete" )._renderItem = function( ul, item ) {
	return $( "<li></li>" )
	.data( "item.autocomplete", item )
	.append( '<a>' + item.label + "</a>" )
	.appendTo( ul );
};

// load search results
var searchtext = '';
var activeSearch = false;
var lastKeyUp = null;
var waitForSearch = 15000;
$('#SearchText_autocomplete').keyup(function(event){
	lastKeyUp = new Date().getTime();
	
	if(searchtext != this.value.trim())
		searchtext = this.value
	
	if(event.keyCode == '13'){
		prepareSearch(true);
	}/*else if(!activeSearch){  
		activeSearch = true;
		setTimeout("search(false)", waitForSearch);
	}*/
	

});

function prepareSearch(){
	
	var activeTab = $('ul[class="tabs"]').children('li[class$="active"]');
	if(jQuery(activeTab).size() == 0){
		jQuery('#Content').load('/q/' + encodeURIComponent(searchtext));
		setTimeout("prepareSearch()", 500);
	}else{
		search(true);
	}
}

var searching = false
function search(pronto){
	if(new Date().getTime() - lastKeyUp > waitForSearch || pronto){
		if(searchtext.trim().length > 1 && !searching){
			searching = true
			var types = '';
			var activeTab = $('ul[class="tabs"]').children('li[class$="active"]');
			loadResults($('div[class="tab_container"]').children(jQuery(activeTab).children('a').attr('href')), 1);
		    searching = false;
		}
		activeSearch = false;
	}else{
		setTimeout("search(false)", waitForSearch);
	}
}

function loadResults (element, type){
	jQuery(element).load('/quest/' + type + '/' + encodeURIComponent(searchtext));
}
// update the counter when hitCounts are loaded
function updateFtsCounter(element){
	var hitCount = jQuery(element).children('input[name="totalHitCount"]').attr('value');
	var tab = jQuery(element).closest('div[class="ResultFrame"]').find('ul li a[href="#' + jQuery(element).attr('id') +'"]');
	
	if(jQuery(tab).children('span').size() > 0){
	    jQuery(tab).children('span').replaceWith('<span class="hitCount">(' + hitCount + ')</span>');
	}else{
	    tab.append('<span class="hitCount">(' + hitCount + ')</span>');
	}
}

// autoLoad Components
var startAutoLoad = 0;
var elementsfound = 0;
var elementsProcessed = 0;
function autoLoadComponents(){
	
	startAutoLoad = startAutoLoad + 1;
	// we only need one autoload Process per page
	if(startAutoLoad == 1){
		var elements = $('input[name^="autoload_"]');
		elementsfound = elements.size();
		
		for(var i = 0; i < elements.size(); i++){
			if(jQuery(elements[i]).parent().css('display') == 'block'){
				var type = elements[i].name.split('_')[1];
				var id = elements[i].name.split('_')[2];
				elements[i].name = 'in_progress';
				autoloadElement(elements[i], type, id);
			}
		}
		
		elements = $('input[name^="autoload_"]');
		for(var i = 0; i < elements.size(); i++){
			var type = elements[i].name.split('_')[1];
			var id = elements[i].name.split('_')[2];
			elements[i].name = 'in_progress';
			autoloadElement(elements[i], type, id);	
		}
		startAutoLoad = 0;
	}
}

function autoloadElement(element, type, id){
	$.ajax({url:'/autoload/' + type + '/' + id,
		success: function(data){
					jQuery(element).replaceWith(data);
					hideAllNewAnnotationButtons();
					elementsProcessed = elementsProcessed + 1;
					if(elementsProcessed == elementsfound){
						MathJax.Hub.Queue(['Typeset',MathJax.Hub]);
						elementsProcessed = 0;
					}
				},
		error: function(){jQuery(element).replaceWith('<div style="font-color: red;">Unable to load ' + type + ' with id: ' + id + '</div>')}
	});
}

function updateProgressbar(element, done){
	//console.log('updating Prgoressbar: ' + jQuery(element).attr('name') + ' ' + done);
}



