$(document).ready(function(){
  
  // add a class for CSS-rules
  $('html').addClass('js-on');
  
  // remove logo-link title-text because it doesn't actually link to the homepage when JS is active, but only triggers the slide out/in of the content holder
  $('#logo a').attr('title','');

  // insert initial preloader outside content (as our content intially is collapsed)
  $('body').append('<span class="loading_initial">Moment!</span>');

  // insert preloader for both maximage and jQuery.load
  $('#header').append('<span class="loading">Moment!</span>');
  
  // insert expand/collapse-trigger
  $('#header').append('<p id="slidetrigger">Show/Hide</p>');
  
  $('#kontext').css("left","-405px");
    
  $("#kontext").mouseenter(function(event) {
    event.preventDefault();
    $('#kontext').stop().animate({left:"0"},100);
    $('#slidetrigger').css("background-position","-15px 0px");
  }).mouseleave(function(event){
    event.preventDefault();
    $('#kontext').stop().animate({left:"-405"},100);
    $('#slidetrigger').css("background-position","0px 0px");
  });
  
  if(jQuery.url.attr("path") != "/" && jQuery.url.attr("path") != "/k/" && jQuery.url.attr("path") != "/en/"){
    $('#kontext').css("left","0px");
    $('#slidetrigger').css("background-position","-15px 0px");
    //$('#slidetrigger').hide();
  }
  
  // set up jScrollPane for case: user access a html page (other than index) but has javascript active
  $('#content .container').jScrollPane({scrollbarWidth:10, scrollbarMargin:10, showArrows:true, arrowSize:14});
  
  // insert and hide container for the supersized plugin images
  $('#kontext').after('<div id="supersize"></div>');
  $('#supersize').hide();
  
  // set up the supersized plugin
  $.fn.supersized.options = {
		startwidth: 1280,
		startheight: 1024,
		slideshow: 1,
		slideinterval: 7000
	};

  // shuffle available images
	var images = [ '1', '2', '3', '4', '5', '6', '7', '8' ];
	var urls = $.shuffle(images);
	//var urls = [ 'xyz1', 'slide02', 'xyz2', 'xyz3', 'slide05', 'slide06', 'xyz4', 'xyz5', 'slide09', 'slide10', 'slide11', 'slide12', 'slide13', 'slide14' ];

	// preload images via the preload plugin
	$.preload( urls, {
		base:'/images/slides/',
		ext:'.jpg',
		onComplete:function( data ){
			var img = new Image();
			img.src = data.image;
			//console.log("processed " + data.image);
   		var insertedImage = $('#supersize').append(img);
      $(img).css('z-index','1');
      $(img).wrap("<span></span>");

			if(!(supersizeInterval) && data.loaded == 2){
			  //console.log("started supersize");
      	$('#supersize :first').addClass('activeslide');
        $('#supersize').supersized();
			  $('.loading_initial, .loading').fadeOut('fast');
    		$('#supersize').resizenow();
  	    $('#supersize').fadeIn('fast');
  			var supersizeInterval = setInterval("theslideshow()", 7000);
			}
			
			if(data.loaded > 2){
			  //console.log("image inserted");
        $('#supersize').resizenow();
			}
		},
		onFinish:function(){
      //console.log("finished");
		}
	});

	// rewrite navigation links from "/item-name.html" to "#item-name"
	$('#navigation ul li a').each(function(i){
	  var href = $(this).attr("href");
    $(this).attr("href","#"+href.substr(0,href.length-5));
  });
  
  // set up jquery.history
	$.historyInit(loadContent);
	// grab all the links with rel="history"
	$("#navigation ul li a").click(function(event){
    event.preventDefault();
    $('.loading').hide();
    
    // manage selected state of navigation items
    $('#navigation li a').removeClass();
    $(this).addClass('selected');

		var hash = this.href;
		hash = hash.replace(/^.*#/, '');

    // if there's a #content .container already, hide it, then load stuff, else just load
    if($('#content .container').length) {
      $('#content .container').fadeOut('normal',$.historyLoad(hash));
    } else {
      $.historyLoad(hash);
    }
	});

  $('#logo a').click(function(event) {
    event.preventDefault();
    var currentPos = $('#kontext').css('left');
    currentPos = currentPos.substr(0,currentPos.length-2);

    if(currentPos == 0){
      $('#kontext').stop().animate({left:"-405"},100);
      $('#slidetrigger').css("background-position","0px 0px");
    }else if(currentPos < 0){
      $('#kontext').stop().animate({left:"0"},100);
      $('#slidetrigger').css("background-position","-15px 0px");
    }
    // $('#content .container').jScrollPane();
    // $('#navigation li a.selected').removeClass();
    // //window.location.hash = "index";   
    // $('#content .container').fadeOut('normal');
    // updateTitleAndBodyClass("index");
    // $.historyLoad(hash);
    // return false;
  });
  
  function loadContent(hash) {
    //$("#slidetrigger").hide();
    $('#slidetrigger').css("background-position","-15px 0px");
    $('#kontext').animate({left:"0"}, 500);
    // let's see whats in #navigation before we load anything based on the hash
    var href = $('#navigation li a').each(function(){
      var href = $(this).attr('href');
      // load hash-defined target only if it matches the hrefs value (w/o .html)
      if(hash==href.substr(1,href.length)){
        // we don't want to load the whole html document, just the content stuff
        var toLoad = hash+'.html #content .container';
        // highlight matching navigation item
        $('#navigation li a').removeClass();
        $(this).addClass('selected');
        // finally load the stuff and let hideLoader() manage jScrollPane
        $('#content .container').remove(); //add to...
        $('.loading').fadeIn('fast');
        $('#content').load(toLoad,'',showNewContent);
        updateTitleAndBodyClass(hash);
      }
    });
  }
  
  function showNewContent() {
    $('#content .container').fadeIn('normal',hideLoader);
  }
  
  function hideLoader() {
    $('.loading').fadeOut('fast');
    $('#content .container').jScrollPane({scrollbarWidth:10, scrollbarMargin:10, showArrows:true, arrowSize:14});
  }
  
  function initialCap(string) {
    string = string.substr(0, 1).toUpperCase() + string.substr(1);
    return string;
  }
  
  function updateTitleAndBodyClass(string) {
    // update page title for bookmarks; default page title makes it less complicated
    defaultTitle = "Kontext Architektur";
    // take care of body.class
    $('body').removeClass().addClass(string);
    // set title
    if(string == "index"){
      document.title = defaultTitle;
    } else {
      document.title = initialCap(string) + " / " + defaultTitle;
    }
  }
  
});
