(function($){
  $(function(){
    initDialog();
    initFlashMessage();
    initMailbox();

    initBlogRating();
    initVideoRequestEdit();
    initVideoRating();

    initTVShowRating();

    initVideoListRating();
    initTeaserSwitch();
    initPlaytubeUpload();
    initCommentEditorial();
    initCommentRating();
    initAjaxCommentForm();

    initSearchBoxing();
    initGameBoxing();
    initArchiveTooltip();
    initRegistration();  
    initCommentReply();
    initBrowserUpgradeCheck();
    
    initGameDetailTagNavi();
    initGameDescHide();
    initGameAmazonButton();
    
    initShowArchiveNavi();
    
    initTracking();
    initEmptyAdRemover();
    initReadabilityOption();
    initSpoilerWizard();
    //initAjaxifiedCommentsPagination();
    initFacebook();
    initTextEditor();
    initBlogGallery();
		initVotableBlogGallery();
    initForumTopicGamesPackShots();
  });

    function initForumTopicGamesPackShots () {
        $('li.game a.game_image img').tooltip({ 
            track: false, 
            delay: 0, 
            showURL: false, 
            showBody: false, 
            fade: 250,
            positionLeft: true
        });
    };

		function initVotableBlogGallery() {
			var options = {
        galTrackAction: '/gallery/',
        trackIVW: true,
        ivwTag: 'gallery',
        trackOmniture: true
      };

			// cropping and resize
			$('ul.votable li img').cjObjectScaler({ cropType : 'fit', binding : { vertical : 'center', horizontal : 'center' } });

			/* Apply fancybox to multiple items */
			$(".votable a.image_link").fancybox({
				'cyclic': true,
				'type': 'ajax',
				'titleShow': false,
				'autoScale': false,
				'height': 460,
				'autoDimensions': false
        //onComplete: function() {G1.Tracking.track(options)}
			});
			
			$("#fancybox-wrap a.rate_up, .overlay a.rate_up").live('click', function(event){ 
				var $this = $(this);
				var url = $this.attr("href") + ".js";
				var urlSplit = $this.attr("href").split("/");
				var galleryImageId = urlSplit[urlSplit.length-1];
				$.ajax({
				   url: url,
					 type: "PUT",
				   data: { rate: "true" },
					 success: function(message){
							var respondsElement = ($('#fancybox-wrap .caption').length > 0) ? $('#fancybox-wrap .caption') : $this.parents('.overlay');
							respondsElement.html(message);
							var $gallery_image_vote = $('.gallery_image_vote_' + galleryImageId);
							if (message.search(/\d+/)!==-1) {
								$gallery_image_vote.html(message.match(/\d+/)[0]);
							};
						}
				 });
				return false; 
			})
			
		};

		function initBlogGallery() {
			var options = {
        galTrackAction: '/gallery/',
        trackIVW: true,
        ivwTag: 'gallery',
        trackOmniture: true
      };

        $('div.gallery a.image_link img').cjObjectScaler({ cropType : 'fit', binding : { vertical : 'center', horizontal : 'center' } });
				$('div.gallery a.image_link').fancybox({
					'cyclic': true,
					'type': 'image',
					'titlePosition': 'over',
					'titleShow': true
          // onStart: function() {G1.Tracking.track(options)}
				});
    };
    
  function initTextEditor() {
        var $textArea = $('textarea.markitup');
        $textArea.markItUp(bbcodeSettings);
        
        $('.form_topic_preview_link:eq(0)').live('click', function(event){
          $('.markitup_form_topic:eq(0)').trigger('preview');
            event.preventDefault();
        });
  };
  
    function initFacebook () {
        if($("#fb-tabs").length>0){$("#fb-tabs").tabs();}
    };
    
  function initEmptyAdRemover(){
    if($("#wide_ad").length && $("#wide_ad")[0].clientHeight <= 31) $("#wide_ad").remove();
  };
  
  // replace a link with the content from the URL it points to
  $.fn.ajaxload = function () {
    return this.each(function () {
      var element = $(this);
      $.get(this.href, {}, function (result) {
        element.replaceWith('<div>' + result + '</div>');
      });
    });
  };
    
  function initTracking(){
    G1.Tracking.init({
      ivwPath: "http://gameone.ivwbox.de",
      ivwTag: "gameone_de",
      ivwTrackAction: document.location,
      trackIVW: true,
      galTrackAction: "gameone_de",
      trackOutGoingLinks: true
    });

    // ajax tracking
    $('body').ajaxSuccess(function(evt, request, settings){
      var options = {
          ivwPath: "http://gameone.ivwbox.de",
          ivwTag: "gameone_de",
        galTrackAction: "/ajax/" + settings.url,
        ivwTrackAction: "/ajax/" + settings.url,
                trackIVW: true
      };
			if (settings.url.search(/tracking_false/)>=0){
			}else{
				G1.Tracking.track(options);
			};
    });

    // readabillity plugin tracking
    $('a.readability').livequery('click', function(event) {
      var options = {
        galTrackAction: "/readability/" + document.location,
        ivwTrackAction: "/readability/" + document.location
      };
      G1.Tracking.track(options);
    });
  }

  function initDialog () {
    G1.dialog._init();
  }
    
  function initFlashMessage () {
    if ($('#flash').length > 0) {
      $('#flash').hide();
      
      var className = $('#flash').attr('class');
      var message = $('#flash').remove().html();

      $('.dialog').addClass(className);
      $('#flash_message').html('<p>' + message + '</p>');

      G1.dialog.openDialogTab($('.dialog #flash_message'));
    
      setTimeout(function () {
        if ($('.ui-dialog .' + className).length > 0) {
          G1.dialog.closeDialog();
          $('.dialog').removeClass(className);
        }
      }, 5000);
    }
  }
  
  function initSpoilerWizard () {
    $.fn.spoiler = function () {
      return this.each(function () {
        var $this = $(this);
        $this.find('span.warning').replaceWith('<span class="warning">Spoiler Warnung ! Klicke hier um den Text anzuzeigen</span>');
        $this.find('span.spoiler_text').toggle();
        
        $this.click(function(){
          $this.toggleClass('spoiler_show');
          if ($this.hasClass('spoiler_show')) {
            $this.find('span.spoiler_text').show();
          }else{
            $this.find('span.spoiler_text').hide();
          };
        });
      });
    };
    
    $('.spoiler').spoiler();
  }
  
  function initRegistration () {
    if ($('#show_pw').length === 0) {
      return;
    }
    
    if (jQuery.browser.msie) {
      $('#show_pw').remove();
      return;
    }

    $('#show_pw').show();

    var pwConf = $('#user_password_confirmation').parent()[0];

    $('#show_pw').click(function (event) {    
      if ($('#user_password')[0].type == 'password') {    
        $('#user_password')[0].type = 'text';
        $('#user_password_confirmation').parent().remove();
        $('#show_pw small').text('Passwort verstecken');
      } else {
        $('#user_password').parent().after(pwConf);
        $('#show_pw small').text('Passwort anzeigen');
        $('#user_password')[0].type = 'password';
        $('#user_password_confirmation').parent().show();    
      }
    });
  }

  function initRaterFor(elements) {
      if (elements.length > 0) {
          var average = parseFloat(elements.attr('rel')).toFixed(1);
          var count = parseInt(elements.attr('rev'));
          var url_path = jQuery.url.attr('path') + "/rate";
          elements.rater(url_path, { curvalue: average, count: count });
      }
  }
  
  function initBlogRating () {
      initRaterFor($('#blog_post_rater #rating'));
  }

  function initVideoRequestEdit () {
        $('.my_videos .actions .request_edit_link').ajaxified_video_request_edit();
    }

  function initVideoRating () {
      initRaterFor($('#playtube_video .video #rating'));
  }

  function initVideoListRating() {
        $('#games_game .game_video_list .rating').each(function(){
          initSingleVideoListRating($(this));
        });
  }
  
  function initTVShowRating() {
        $('#actions .meta .rating').each(function(){
          initSingleVideoListRating($(this));
        });
        $('#tv_shows #actions .meta .rating').each(function(){
          initSingleVideoListRating($(this));
        });
        $('#tv_shows #archive .aside .rating').each(function(){
          initSingleVideoListRating($(this));
        });
        $('#search_show .aside .rating').each(function(){
          initSingleVideoListRating($(this));
        });
  }
  
  function initSingleVideoListRating(object){
      initRaterFor(object);
  }
  
  // Handling of jqueryui-tabs on user-profile page
  $(function() {
    //$("#tabs.userprofile-tabs").tabs({selected: 3});
    //return false;
    var loc = document.location.href;
    
    if(loc.match(/tabs/) !== null && loc.match(/tabs/).length > 0){
      $("#tabs.userprofile-tabs").tabs();
      return false;
    }else{
      $("#tabs.userprofile-tabs").tabs({selected: 3});
      return false;
    }
  });
    
  // Handling of tabs / GameDetail Tag Navi
  
  function initGameDetailTagNavi() {
    if($('#tagnavi').length) {
      $('#tagnavi li').each(function() {
        if($(this).hasClass("active") && !$(this).hasClass("first")) {
          $(this).find("a:first").bind("click", TagNaviSwitch);
          $(this).find("a:first").click();
        }
        if(this.id == "playtube_navi") {
          $(this).prev("li").addClass("least");
        }
        var href = $(this).find("a:first").get(0).href;
        href = href.substring(href.lastIndexOf("#"), href.length);
        if($(href).children().length || href == "#all"){
          $(this).find("a:first").bind("click", TagNaviSwitch);
          $(href).parent(".game_video_list").find(".submit").hide();
          $(href).parent(".game_video_list").find("select").bind("change", function(){
            $(this).parent("form").submit();
          });
        } else {
          $(href).prev("h3").remove();
          $(href).prev("form").remove();
          var text = $(this).find("a:first").text();
          $(this).find("a:first").remove();
          $(this).html('<span>'+text+'</span>');
          $(this).addClass("empty");
        };
      });
    };
  };
  
  function TagNaviSwitch() {
    if($('#game_videos').length) {
      var $videos = $('#game_videos');
      var $trailer_uls = $("#game_videos .game_video_list > ul");
      var className = this.href.substring(this.href.lastIndexOf("#") + 1, this.href.length);

      $("#tagnavi li").removeClass("active");
      $("#tagnavi li").removeClass("almost");
      $(this).parent("li").addClass("active");
      if($(this).parent("li").prev("li").length) {
        $(this).parent("li").prev("li").addClass("almost");
      }
      if(className == "playtube_videos") {
        className = "game_playtube";
      }
      if(className == "all") {
        $trailer_uls.children("li").show();
        $videos.find("h3").show();
      } else {
        $videos.find("h3").hide();
        $videos.find("form").hide();
        $("#"+className).prev("h3").show();
        $("#"+className).prev("h3").prev("form").show();
        $trailer_uls.children("li").hide();
        $trailer_uls.children("li."+className).show();
      }
    }
    return false;
  };
  
  function initGameDescHide() {
    if($("#games_game #game_description #desc_text").length && $("#games_game #game_description #desc_text").text().length >= 300) {
      var $textObject = $("#games_game #game_description #desc_text");
      var actualText = $textObject.text();
      var showText = actualText.substring(0,300);

      $textObject.hide();
      $textObject.after('<div class="clone"></div>');
      $textObject.next("div.clone").css("margin-bottom","1.5em");

      showText = showText.replace(/<.+?>/, showText);
      showText = showText.replace(/<\/.+?>/, showText);
      
      $textObject.next("div.clone").html(showText);
      $textObject.next("div.clone").append('&nbsp;&hellip;<br /><a href="#desc_text">Weiterlesen</a>');
      $textObject.next("div.clone").find("a").bind("click", showGameDesc);
    }
    return false;
  }
  
  function showGameDesc() {
    var $textObject = $("#games_game #game_description #desc_text");
    $textObject.next("div.clone").remove();
    if(!$textObject.find("a.toggle").length){
      $textObject.append('<br /><a class="toggle" href="#desc_text">Verkleinern</a>');
      $textObject.find("a").bind("click", initGameDescHide);
    }
    $textObject.show();
    return false;
  }
  
  function initGameAmazonButton() {
    if($('#amazon_links').length){
      var $mother = $('#amazon_links');
      $mother.find("ul li a").attr("target","_blank");
      $mother.find("a").bind("click",togglePlatformList);  
      $('#amazon_links h3').hide();
      $('#amazon_links ul').hide();
    }
    
    function togglePlatformList() {
      if($('#amazon_links').length){
        var $list = $('#amazon_links ul');
        var $heading = $list.prev("h3");
        if($list.css("display") == "inline") { 
          $list.hide();
          $heading.hide();
        } else {
          $list.css("display","inline");
          $heading.css("display","inline");
          $list.find("a").bind("click",togglePlatformList); 
        }
        if(this.id == "amazon_button") return false; 
        else return true;
      }
    }
    
  };
  
  // TV-Show Archive Navi
  
  function initShowArchiveNavi(){
    var $archive = $("#archive");
    if($archive.length){
      $archive.find("form select").bind("change", function(){
        $(this).parent("form").submit();
      });
      
      if($archive.find("h4.active").length) {
        var height = $archive.find("h4.active").next("ul")[0].clientHeight;
        var $active = $archive.find("h4.active");
        $archive.addClass("init");
        $archive.css("height",height+100+"px");
        $archive.find("ul").hide();
        $archive.find("h4").removeClass();
        $active.addClass("active");    
        $active.next("ul").show();
        $archive.find("h4").bind("click",ArchiveSwitch);
      } else {
        var height = $archive.find("ul:first")[0].clientHeight;
        $archive.addClass("init");
        $archive.css("height",height+100+"px");
        $archive.find("h4:first").addClass("active");
        $archive.find("h4:first").next("ul").show();
        $archive.find("h4").bind("click",ArchiveSwitch);
        $archive.find("h4:first").click();  
      }
    }    
  };
  
  
  function ArchiveSwitch() {
    var $archive = $("#archive");
    var year = $(this).text();
    $("#input_year").val(year.replace (/^\s+/, '').replace (/\s+$/, ''));    
    $archive.find("ul").hide();
    $archive.find("h4").removeClass();
    $(this).addClass("active");    
    $(this).next("ul").show();
    var height = $(this).next("ul")[0].clientHeight;
    $archive.css("height",height+100+"px");
  }
  
  
  // g2 player functions
  function thisMovie (movieName) {
    if (navigator.appName.indexOf('Microsoft') != -1) {
      return window[movieName];
    } else {
      return document[movieName];
    }
  }

    function playVideo (player_id, clipurl, annos, img, available_profiles, playlist, start, end) {
        thisMovie(player_id).playVideo(clipurl, annos, img, available_profiles, playlist, start, end);
    }
    
    function setPlaylist (player_id, playlist) {
        thisMovie(player_id).setPlaylist(playlist);
    }
    
    function toggle_controls (player_id) {
        thisMovie(player_id).toggleControls();
    }
    
    function toggle_mute (player_id) {
        thisMovie(player_id).toggleMute();
    }
    
    function seekTo (secs) {
        thisMovie(player_id).seekTo(secs);
    }
  
  function initTeaserSwitch(){  
        if ($('#video_teaser_wrapper img').length > 0){
          $('#video_teaser_wrapper img').click(function (event) {
            $('#video_teaser_wrapper').addClass('expanded');
            $('#video_teaser_wrapper img').hide();
            toggle_mute('flash_container_sequence_home');
            toggle_controls('flash_container_sequence_home');
        });
    }
  }
  
  function initPlaytubeUpload(){
    $('#upload_accept_link').click(function (event) {
          $('#upload_accept').show();
          $('#upload_disclaimer_buttons').hide();
      });

    $('#upload_deny_link').click(function (event) {    
          top.location.href = '/videos';
      });
  }

  function initCommentRating (url_path) {
    $('.comments .rating').ajaxified_rating();
    G1.AjaxifiedPaging.init();
  }
  
  function initAjaxifiedCommentsPagination(){
    G1.AjaxifiedCommentsPagination.init();
  };
  
  
  function initCommentEditorial (url_path) {
    $('.comments .editorial').ajaxified_editorial();
  }
  
  function initAjaxCommentForm () {
    if (G1.CommentsForm) { G1.CommentsForm.init(); }
  }

  function initSearchBoxing (url_path) {
    $('#search_col a.search_more').ajaxified_search();
  }
  
  function initGameBoxing (url_path) {
    $('#games_game a.game_more').ajaxified_game();
  }

  function initArchiveTooltip () {
    if ($('#archive ul li a').length === 0 ) {
      return;
    }
    
    // $('#archive ul li a').tooltip({ 
    //   delay: 0, 
    //   showURL: false,
    //   extraClass: 'show_tip'
    // });
  }

  function initCommentReply () {
    if ($('.comments .comment, ol.posts li.post').length > 0) {
      $('.comments .comment, ol.posts li.post').reply();
    }
  }
  
  function initBrowserUpgradeCheck () {
    var isIE6 = jQuery.browser.msie ? (jQuery.browser.version === '6.0' ? true : false) : false;
    var home = jQuery.url.attr('path');
    
    if (isIE6 && home === '/' ) {
      
    } else if (isIE6 && home === '/blog') {
      
    } else {
      return;
    }

    var upgrade_message = '<div class="row">' +
                '<div class="upgrade_message clearfix">' + 
                '<div class="text">' +
                '<h3>Modernisiere Deinen Browser!</h3>' +
                '<p>Du nutzt eine alte Version des Internet Explorer. Aktualisiere oder wechsel jetzt zu einem schnelleren und sichereren Browser !</p>' +
                '</div>' +
                '<div class="links">' +
                '<a target="_blank" href="http://www.microsoft.com/windows/internet-explorer/default.aspx" class="ie_8">Download Internet Explorer 8</a>' +
                '<a target="_blank" href="http://de.www.mozilla.com/de/" class="firefox">Download Firefox 3.5</a>' +
                '</div>' +
                '</div>' +
                '</div>';

    $('.row.navigation:eq(0)').after(upgrade_message);  
  }
  
    // --------
    // everything related to direct_messages / mailbox
    function initMailbox () {
      var isIE7 = jQuery.browser.msie ? (jQuery.browser.version === '7.0' ? true : false) : false;
      
      $("#tabs.mailbox-tabs").tabs();
      
      if($("input#direct_message_recipient_name").length && $("input#direct_message_recipient_name").val() != '') checkUsernameExists($("input#direct_message_recipient_name"));
      
      if(isIE7) {
        var width = 0;
        $('#tabs .ui-tabs-nav li').each(function(){
          width = width + this.clientWidth;
        });
        width = width - 17;
        $('#tabs .ui-tabs-nav').css('width',width+'px')
      }
    };
    
        // opens the create new message tab
      $("a#open-new-msg-tab").live("click", function(e){ // bind click event to link      
          $("#tabs.mailbox-tabs").tabs('select', 0); // switch to third tab
          return false;
      });

      // cancel a new msg and jump to first tab
      $("a#cancel_message").live("click", function(){
        $('#direct_message_recipient_name').attr('value', "");
        $('#direct_message_subject').attr('value', "");
        $('#direct_message_body').attr('value', "");
        $("#tabs.mailbox-tabs").tabs('select', 2); // switch to third tab
        return false;
      });

     // de- / select all messages for deletion
    $('input[type=checkbox][id^=select_all_msgs]').live('click', function(e){
      var ele = $(e.target);
      var table = ele.parents('table');
      $('input[type=checkbox][id*=direct_message]', table).attr('checked', this.checked);
    });


      // answer a specific message, copy all needed infos to new msg tab & jump to third tab
      $('a[id^=answer_message]').live('click', function(e){
        var ele = $(e.target);    
        var msg_id = ele[0].id.split("_")[2];
        var sender = $('#message_sender_'+msg_id)[0].innerHTML;
        sender = $.trim(sender);
        var subject= $('#mbox_show_message_'+msg_id)[0].innerHTML;
        subject = $.trim(subject);
        var body = $('#message_body_'+msg_id)[0].innerHTML;
        body = $.trim(body);


        $('#direct_message_recipient_name').attr('value', sender);
        $('#direct_message_subject').attr('value', "Re: "+subject);
        //$('#direct_message_body').attr('value', body);

        $("#tabs.mailbox-tabs").tabs('select', 0); // switch to third tab
        if($("input#direct_message_recipient_name").length && $("input#direct_message_recipient_name").val() != '') checkUsernameExists($("input#direct_message_recipient_name"));
        return false;
      });

      // all mailbox / direct_message stuff: simply show a message
      $('a[id^=mbox_show_message]').live('click', function(e){
        // find id of msg that should be shown
        var ele = $(e.target);
        var msg_id = ele[0].id.split("_")[3];
        // find currently opened msg if there is any 
        var old_ele = $(".mailbox tr[id^=message]:not([style*='display: none'])");

        if(old_ele.size() > 0) {
          var old_ele_id = old_ele.attr('id').split("_")[1];
        }

        // three cases to solve when opening a msg:
        if(old_ele.size() === 0) {
          $('.mailbox #message_' + msg_id).toggle(); // open only one msg, no other message to close
          ele.removeClass('msg-closed').addClass('msg-opened');
        }else if(old_ele.attr('id').split("_")[1] !== msg_id){ // close old msg, open new msg
          old_ele.toggle(); // close old msg
          $('a#mbox_show_message_'+old_ele_id).removeClass('msg-opened').addClass('msg-closed');
          $('.mailbox #message_' + msg_id).toggle(); // open new msg
          ele.removeClass('msg-closed').addClass('msg-opened');
        }else if(old_ele.attr('id').split("_")[1] === msg_id){
          old_ele.toggle(); // close current msg, open no other
          $('a#mbox_show_message_'+old_ele_id).removeClass('msg-opened').addClass('msg-closed');
        }

        // remove class 'unread' and ...
        ele.parents('tr.unread').removeClass('unread').each(function(){
          // ...decrease unread count by 1
          var count = $('span#unread_count');
          var old_count = count.text();
          count.text(old_count - 1);
          $('span#top_unread_count').text(old_count - 1);
          if(old_count - 1 === 0) {
            $('span#top_mailbox_header').removeClass('blinky fatty');
          }
          
          // ... do ajax call to backend to mark msg as read
          $.ajax({
            url: "/direct_messages/"+msg_id+"/mark_as_seen",
            type: "POST",
            dataType: 'json',
            data: {id: msg_id },
            cache: false,
            success: function(data, textStatus, XMLHttpRequest) {
              // nothing to do here...
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              console.log("ERROR");
              console.log(textStatus);
              console.log(XMLHttpRequest);
            }
          });
        });

        return false;
      });

     // ajax check if direct_message recipient-name really exists
     

     
     $("input#direct_message_recipient_name").livequery('blur', function(){
       checkUsernameExists($(this));
       $(this).addClass('msg-status-loading');
     });

     function checkUsernameExists(ele) {
       $.ajax({
            url: "/direct_messages/username_exists",
            type: "GET",
            dataType: 'json',
            data: {name: ele.val() },
            cache: false,
            success: function(text, data) {
              ele.removeClass('msg-status-loading');
              if(text.status === 'ok') {
                ele.removeClass('msg-status-error');
                ele.addClass('msg-status-ok');
                $('span#msg-status-error-text').html('');
                $('#direct_message_recipient_id').attr('value', text.user_id);
              } else {
                ele.removeClass('msg-status-ok');
                ele.addClass('msg-status-error');
                $('span#msg-status-error-text').html(text.text);
              }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
              console.log("ERROR");
              console.log(textStatus);
              console.log(XMLHttpRequest);
            }
          });
     }
     
// ---------------------------

    $('a#add_consoles').live('click', function() {
      return !$('#all_consoles option:selected').remove().appendTo('#user_consoles');  
    });

    $('a#remove_consoles').live('click', function() {
      return !$('#user_consoles option:selected').remove().appendTo('#all_consoles');  
    });

    $('#edit_user_submit').live('click', function(e) {
      $('#user_consoles option').attr('selected', 'selected');
    });

  function initReadabilityOption() {
    if( $('.blog_post_show .main.col h2:eq(0), #specials_content h2:eq(0)').length == 0 ) return;
    
    $('.main.col h2:eq(0)').prepend( '<a href="#" title="Im Vollbildmodus anzeigen" alt="Im Vollbildmodus anzeigen" class="readability">Im Vollbildmodus anzeigen</a>' );
    
    $('a.readability-close').live('click', function(event) { 
      $('#readability-underlay').remove();
      $(document.body).removeClass('readable-blog-post');
      event.preventDefault();
    });
    
    $('.readTools a').live('click', function(event) {
      var link = $(this);

      switch ( link.attr('class') ) {
        case "readability-bigger":
        $('#readability-overlay').attr('class', 'big');
        break;
        case "readability-medium":
        $('#readability-overlay').attr('class', 'medium');
        break;
        case "readability-smaller":
        $('#readability-overlay').attr('class', 'small');
        break;
        default:
        break;
      }
      event.preventDefault();
    });

    $('.row .main.col a.readability').click(function(){
      var underlay = $('<div id="readability-underlay"></div>');
      var overlay = $('<div id="readability-overlay" class="medium"></div>');
    
      // create links
      var toolLinks = $('<div class="readTools">' + 
        '<a title="Vollbildmodus Schließen" alt="Vollbildmodus Schließen" class="readability-close" href="#close">close</a>' +
        '<a title="Große Schriftgröße" alt="Große Schriftgröße" class="readability-bigger" href="#">Große Schriftgröße</a>' +
        '<a title="Mittlere Schriftgröße" alt="Mittlere Schriftgröße" class="readability-medium" href="#">Mittlere Schriftgröße</a>' +
        '<a title="Kleine Schriftgröße" alt="Kleine Schriftgröße" class="readability-smaller" href="#">Kleine Schriftgröße</a>' +
      '</div>');
    
      underlay.append(toolLinks);
    
      overlay.append( $('.row .main.col').html() );
    
      underlay.append(overlay);
      underlay.appendTo(document.body);
      $(document.body).addClass('readable-blog-post');
    });
  };
}(jQuery));