/*
Operation sequence

1. A menu point is clicked -> returns loadimg()

2. In loadimg() unconverted links are processed, -> returns loadimages()

3. When loadimages() has loaded all images -> returns showall()

4. Showall() displays content and -> returns navigation()

5. Navigation() assigns navigation arrows and handlers and -> returns imgdesc()

6. Imgdesc() assigns window resize function and image description mouseover handlers.


the "If opera" statements somewhat fixes operas irrational way of displaying jquery's show/hide blind effect

*/


$(document).ready(function() {
    
    if ($.browser.opera) {
        $('#keysimg').css('margin-top', '83px');
        $('.maincontent').css('display', 'none');
    }
    
$('html, body').scrollTop(0); // reset scrolltop position as Firefox does not seem to reset on page reload.

    $('.imgcontent, #keysimg').hide(); // hide image content wrappers
    $('.imgcontent div:empty').remove(); // remove empty project descriptions, meaning the first box in a row of images
    $('.maincontent').show(); // show project description so it appears while images are loading
    
    $('.sectionheader').each(function(index) { // set each menupoint (MP) to a width of the MP text, so that loaderbar, will be the same distance from all MPs
      $(this).width($(this).children('span').width());

    });

    $('<div id="navinfo">You can use the arrow keys to navigate</div>').insertAfter('#menu #keysimg'); // append the navigation info to appear when hovering on keysimg
    
    $('#keysimg').mouseenter(function() { // declare handlers for keysimg
        $('#navinfo').fadeTo(400, 1);
    });
    
    $('#keysimg').mouseleave(function() {
        $('#navinfo').fadeTo(400, 0);
    });
    
    $('.sectionheader:last').css('padding-top', 20); // give Contact MP extra padding
    

    $(window).resize(function() {  // window resize function to adjust position of right arrow and keysimg
          var docW = $(window).width();
            $('.next').css('left', docW-55);
            
          	if ($('body').height() < $(window).height()) {  
	            $('html').css('overflow-y', 'auto'); 
			} 
        
		
		$('#keysimg').css('left', docW-$('#keysimg').outerWidth()-20);	
    });


function loadlogo(){ // function to fade in logo, keysimg and then MP's as callback
  
  $('.logo').fadeIn(1000, function() {
  $('.sectionheader, #keysimg').fadeTo(1000, 1);
	var keysimgmargin = $(window).width() - $('#keysimg').outerWidth();

	
  $('#keysimg').css('left', keysimgmargin-20);
  });
}    





$(window).load(function() { // run loadlogo on window load so fontface fonts are preloaded and do not flicker
loadlogo();
	});


    $('.logo').click(function() { // when logo is clicked, close active MP
    $('.sectionheader.active').trigger('click');
	     $('.logo').css('cursor', 'auto');
});



    

function loadimg(containerindex){  // main function called when clicking a MP
    var activepoint = containerindex;  // todo: could this be replaced with containerindex variable?
    
    function imgdesc(){  // handles image descriptions and related mouseenter/leave handlers
        keynav(activepoint); // assign keyboard and menu navigation now that content is loaded
        menuclick();

    if ($('html').outerHeight() > $(window).height()) {
            $('html').css('overflow-y', 'auto');
             var docW = $(window).width();
                $('.next').css('left', docW-55);

    } else {
        $('html').css('overflow-y', 'auto');
    }

         if ($(window).height() < $('body').height()) { // function to adjust scroll position so images are always viewable when scrollbar is present. 

			var scrollpos = parseFloat($('.logo').outerHeight());
			scrollpos += parseFloat($('.logo').css('margin-top'));
			scrollpos += parseFloat($('#content').css('margin-top'));
			scrollpos += parseFloat($('.sectionheader.active').css('margin-top'));
			scrollpos -= 45; // make the previous MP visible

			$('.sectionheader.active').prevAll('.sectionheader').each(function(index) {
				scrollpos += parseFloat($(this).outerHeight());
				scrollpos += parseFloat($(this).css('margin-top'));
				scrollpos += parseFloat($(this).css('margin-bottom'));
			});

            $('body').css('padding-bottom', (scrollpos+70)); //  add padding to body so we have more scrollable area.

                $('html, body').animate({'scrollTop': scrollpos}, 200, function() {
                    $('html').css('overflow-y', 'auto');
                });
            
            } else {
                $('body').css('padding-bottom', 0);
                $('html').css('overflow-y', 'auto');
            }
       

        
        $('.imgdesc').hide().removeClass('active'); // reset potential visible image descriptions... necessary?
        
        var maincontheight = $('.imgcontent.active .maincontent').next('div').height(); // set height of project description in first div, so it can be clicked like images
   
        if (maincontheight > 0) {
            $('.imgcontent.active .maincontent').height(maincontheight);
            
        } else {
            $('.sectionheader.active .maincontent').height(400); // default height of 400
        }
        
        $('.imgcontent div:not(.imgdesc)').mouseenter(function() { // handlers to display image descriptions and Fadup of arrows depending of direction a click will lead to (very messy)
                $(this).children('.imgdesc:not(:empty)').addClass('active').fadeTo('fast', 0.65);
                if ($(this).next('div:not(.imgdesc)').children('img').css('cursor') == 'auto' && $('.imgcontent.active').css('left') != '0px') { // if we hover over the first image on the left and it is not the very first image
                    $('.prev').css('opacity', 1);
            
                } else if ($(this).children('img').css('cursor') == 'pointer') { // or else if we hover over any other image that indicates being clickable
                        $('.next').css('opacity', 1);
                    } 
            });
            
            $('.imgcontent div:not(.imgdesc)').mouseleave(function() {  // on mouseleave restore proper opacities.... a whole lot of if statements here :-(

            if ($('.imgcontent.active').css('left') == '0px') {
                $('.next').css('opacity', 0.5);
                } else if ($(this).prev('div:not(.imgdesc)').children('img').css('cursor') == 'auto' && $(this).nextAll('div:not(.imgdesc)').length === 0){
                    $('.next, .prev').css('opacity', 0.5);
                } else if ($(this).children('img').css('cursor') == 'auto' && $(this).next('div').children('img').length === 0){
                    $('.next').css('opacity', 0);
                    $('.prev').css('opacity', 0.5);
            	} else if ($(this).children('img').css('cursor') == 'pointer' && $(this).next('div').children('img').length === 0) {
                    $('.next').css('opacity', 0.5);
				} else if ($(this).next().children('img').css('cursor') == 'auto'){
                $('.prev').css('opacity', 0.5);
				} else if ($(this).children('img').css('cursor') != 'auto'){
                    $('.next').css('opacity', 0.5);
                }   else if ($(this).children('img').css('cursor') == 'auto'){
                        $('.prev').css('opacity', 0.5);
                    }
                $('.imgdesc.active').fadeOut('fast').removeClass('active');
                    });
                }



    function navigation(index, windowW, contentW){
        
        var increment = 0;

    	$('.imgcontent.active div:not(:has(.imgdesc, .prev, .next)) img').each(function(index) {  // append image descriptions and position them
            var descpos = 0;
            var descwidth = 0;
            var descmarg = 0;
            
            var description = $(this).attr('description');
            
            if (description != ""){
                $('<div class="imgdesc">'+description+'</div>').insertBefore(this);
            
                var descW = $(this).attr('width');
                    descW -= parseFloat($(this).prev('.imgdesc').css('padding-left'));
                    descW -= parseFloat($(this).prev('.imgdesc').css('padding-right'));
            
                
                $(this).prev('.imgdesc').width(descW);
    
        
            descpos = $(this).height() - $(this).prev('.imgdesc').outerHeight();

            descwidth = $(this).width() - parseFloat($('.imgdesc').css('padding-right'));
            descmarg = $(this).width();
            
            $(this).prev('.imgdesc').css({'margin-top': descpos, 'margin-bottom':-($(this).attr('height')), 'margin-right': -(descmarg) }).width(descW);
            
            }
        });
    
    $('.imgcontent:eq('+index+') div:last').css('margin-right',0);  // remove margin on the last image/div
        
            var currentimage = 0;
            increment = parseFloat($('.imgcontent.active').css('left'));

                    function navfade(item){
                        $(item).css('opacity', 1);
                    }

                    function navfadeout(item){
                        $(item).css('opacity', 0.5);
                    }


        if (contentW > windowW) { // if images are overflowing window, append previous, next navigation arrows, position them and fade them in.
    
            	$('.imgcontent.active div:first img, .maincontent').css('cursor', 'auto');  
            
                $('<div class="prev"></div>').insertAfter('.imgcontent.active');
                $('<div class="next"></div>').insertAfter('.prev');
                
                var navtop = ($('.imgcontent.active').height()+$('.prev').height()) / 2;
                navtop += 30;
                var navtopnext = $('.prev').height();
                $('.prev').css({'top': -navtop});
                $('.next').css({'top': -(navtop+navtopnext), 'margin-bottom': -(navtopnext*2)});


                
                $('.next').css('left', windowW-55); 
                $('.prev').delay(500).css('opacity', 0);
                $('.next').delay(1000).fadeTo('slow', 0.5);
                
                $('.next').mouseover(function() {
                    navfade(this);
                    
                    $(this).mouseout(function() {
                        navfadeout(this);
                    });
                });
                
                
                    
				$('.imgcontent.active div:not(.imgdesc)').click(function() { // handler for navigating via clicking an image.
                $('.imgcontent.active img, .imgcontent.active .maincontent').css('cursor', 'pointer');
                
                if ($(this).is('.maincontent') === true) {
                    $(this).css('cursor', 'auto');
                }
                $(this).children('img').css('cursor', 'auto');
                
               	$('.imgcontent.active').stop();
                var scrolladjust = 0;
                var currentcompare = currentimage;
                currentimage = $(this).prevAll('div:not(.imgdesc)').length;
                
            	nextimages = $(this).nextAll('div:not(.imgdesc)').length;

                $(this).prevAll().each(function(index) {
                    
                    scrolladjust += $(this).outerWidth() + parseFloat($(this).css('margin-right'));
                });
                
                if (currentimage === 0) {
                    scrolladjust = 0;
                    $('.prev').css({'opacity': 0, 'cursor':'auto'}).unbind('mouseover').unbind('mouseout');
                } else {
                          $('.prev').unbind('mouseover').unbind('mouseout').mouseover(function() {
                                navfade(this);

                                $(this).mouseout(function() {
                                    navfadeout(this);
                                });
                            });
                    $('.prev').css({'opacity': 0.5, 'cursor':'pointer'});
                    scrolladjust = scrolladjust;
                
                        if (currentcompare < currentimage) {
                            $('.next').css('opacity', 1);
        
                        } else {
                            $('.prev').css('opacity', 1);
                        }
                }
                $('.imgcontent.active').animate({'left': -scrolladjust}, 400, function() {
                  if (currentimage === 0) {
                    $('.next').css('opacity', 0.5);
                    } else {
              
                        if (nextimages !== 0) {
                          $('.next').css('opacity', 0.5);
                        }
                    }
                      if (nextimages === 0) {
                            $('.next').css({opacity: 0, cursor: 'auto'});
                        }
                    
                });
                
                increment = -scrolladjust;
            
            if (nextimages === 0) {
                $('.next').css({opacity: 0, cursor: 'auto'}).unbind('mouseover').unbind('mouseout');
            } else {
                    $('.next').css({cursor: 'pointer'}).unbind('mouseover').unbind('mouseout').mouseover(function() {
                                    navfade(this);

                                 $(this).mouseout(function() {
                                        navfadeout(this);
                                    });
                                });
            }
            
                


            }); 
                                
            $('.next, .prev').unbind('click');
                
            $('.next').click(function() {  //  handler for clicking next arrow
                    var prevlength = $('.imgcontent:eq('+index+') div:not(.imgdesc, .prev, .next)').length;
                    $('.imgcontent.active img, .maincontent').css('cursor', 'pointer');
                    
                    
                    if (currentimage < (prevlength-1)) {
                        navfade(this);
                    $('.imgcontent.active').stop();
                    $('.prev').unbind('mouseover').unbind('mouseout').css({'opacity': 0.5, 'cursor':'pointer'});
                    $('.prev').mouseover(function() {
                            navfade(this);

                            $(this).mouseout(function() {
                                navfadeout(this);
                            });
                        });
                 
                    if (currentimage === 0) {
                        increment = 0;
                    }
        
                    increment -= parseFloat($('.imgcontent.active div:not(.imgdesc):eq('+currentimage+')').css('margin-right'));
                    increment -= ($('.imgcontent.active div:not(.imgdesc):eq('+currentimage+')')).width();
          
                currentimage += 1;
                $('.imgcontent.active div:eq('+currentimage+'):not(.imgdesc) img').css('cursor', 'auto');   
                $('.imgcontent.active').animate({left: increment}, 400, function() {
                            if (currentimage == (prevlength-1)) {

                                        $('.next').unbind('mouseover').unbind('mouseout').css({'opacity': 0, 'cursor':'auto'});
                                        $('.imgcontent.active div:last').css('cursor', 'auto');
                                } else {
                                    
                    navfadeout('.next');}
                });
            
                
              
        
                    
            } 
            
            
        });
                
                $('.prev').click(function() { //  handler for clicking prev arrow
                    
                    if (currentimage > 0) {
                        navfade(this);  
                        currentimage -= 1;
                        $('.imgcontent.active img').css('cursor', 'pointer');
                        $('.imgcontent.active div:eq('+currentimage+'):not(.imgdesc) img').css('cursor', 'auto');   
                        $('.imgcontent.active').stop(); 
                
                        increment += parseFloat($('.imgcontent:eq('+index+') div:not(.imgdesc):eq('+currentimage+')').css('margin-right'));
                        increment += ($('.imgcontent.active div:not(.imgdesc):eq('+currentimage+')')).width();
                
                    

                        if (currentimage === 0) {
                            increment = 0;
                            $('.prev').unbind('mouseover').unbind('mouseout');
                            $('.maincontent').css('cursor', 'auto');
                        }
                
                        $('.imgcontent.active').animate({left: increment}, 400, function() {
                            if (currentimage === 0) {
                            $('.prev').css({'opacity': 0, 'cursor': 'auto'});   
                            } else {
                                $('.prev').css('cursor', 'pointer');
                                $('.next').css({opacity: 0.5, cursor: 'pointer'}).unbind('mouseover').unbind('mouseout').mouseover(function() {
                                        navfade(this);

                                        $(this).mouseout(function() {
                                            navfadeout(this);
                                        });
                                    });
                                    
                                
                                navfadeout('.prev');
                            }
                            
                        });
                    } 
                        });
                    
                        } else {
                            $('.imgcontent.active div img').css('cursor', 'auto');
                        } 

                
    
                    imgdesc();
                
    
                }
    
    function showall(index) {
        
        var windowW = $(window).width();
    
       // $('.imgcontent.active div:not(.maincontent)').hide(); // hide divs containing images
            
        var contentW = 0;
    //    $('.imgcontent.active div img').css('display', 'block'); // show images in the hidden wrapper divs so width can be calculated

        $('.imgcontent:eq('+containerindex+') div:not(.imgdesc)').each(function(index) { // get total width of content
            contentW += $(this).outerWidth() + parseFloat($(this).css('margin-right'));
        });
                
                $('.imgcontent.active div:not(.imgdesc)').show();
     
                return navigation(index, windowW, contentW);  // TODO, fix it so images display after counter is gone?
            }
    
    
 
    
    function preloader(loadedPics, totalPics) { // function to drive loading-progress bar
    var totalWidth = 200;
    var percentage = loadedPics / totalPics;
    var loadedWidth = totalWidth * percentage;
    return loadedWidth; // return
    }
    
    
    $('.imgcontent:eq('+containerindex+')').each(function(index) { // stupid to iterate over one element?
    
        
        var totalcount = $(this).children('a.jqlinks').length; // How many links are there to be converted to images?
        
        var imgcounter = $(this).children('#imgcounter').length; // Does imagecounter already exist?
        
        if (imgcounter === 0 && totalcount !== 0){ // If there are links to be converted and imgcounter does not exist....
        $('<span id="imgcounter"><span></span></span>').prependTo(this);
        $('#imgcounter').css('left', ($('.sectionheader.active span').width()+20));
    }

function loadimages(containerindex){
    var loadstate = false;  
    var loadcount = 0; 
    
    if ($('.imgcontent:eq('+containerindex+') div img').length === 0) {
        keynav(activepoint);
    
    }
    
    $('.imgcontent.active div img').each(function(index) {
    loadstate = false;  
        
    loadstate = $(this).attr('complete');

    if (loadstate === 'true') {
        loadcount += 1;
        $('#imgcounter span').width(preloader(loadcount, totalcount));
        if (loadcount == totalcount) {
            $('#imgcounter').fadeOut('fast', function() { // function to fadeout imgcounter and display images
                $(this).remove();
            
                showall(containerindex);
                });
            
        }

    } else {
        
        $(this).load(function() {

            loadcount += 1;
        $('#imgcounter span').width(preloader(loadcount, totalcount));
                if (loadcount == totalcount) {
                            $('#imgcounter').fadeOut('fast', function() { // function to fadeout imgcounter and display images
                                $(this).remove();
                        
                               showall(containerindex);
                                });

                }
            });
        }

    });




}        
    
        

        if (totalcount > 0) {
            var linkcount = totalcount;
        $(this).children('a.jqlinks').each(function(index) {
            var src = $(this).attr('href');
            var title = $(this).attr('title');
            var alt = $(this).attr('rel');
            var imgW = $(this).attr('width');
            var imgH = $(this).attr('height');
            var margin = $(this).attr('margin');
            
    

            
            linkcount -= 1;
            
            if (margin === '0' || margin == '' || margin === null) {
              margin = 20;
            } else {
            margin = parseFloat(margin);
            }

            var image = $('<img>');
            $(image).attr({'src': src, 'title': title, 'description':alt, 'width':imgW, 'height':imgH}).appendTo($(this).parent()).wrap('<div></div>').parent().hide().css('margin-right', margin);
            $(this).remove();
            
            if (linkcount === 0) {
                loadimages(containerindex);
            }

            
            });
            
            } else  {
       
               showall(containerindex);
                
            }
        });
    }
    


function keynav(activepoint){   // ...enable navigation via arrow keys. 39 = rightArr, 37 = leftArr, 38 = upArr, 40 = downArr, 27 = esc 

    $(document).bind('keydown',function(e){
      
        if (e.which == 39) { // first next and previous keyboard navigation of images...
    
          $('.next').trigger('click');
                
        } else if (e.which == 37) {

          $('.prev').trigger('click'); 
          
        } else if (e.which == 40 && activepoint < ($('.sectionheader').length)-1) { // if downarrow is used and active MP is not the last one 
            e.preventDefault();
                activepoint += 1;
              $('.sectionheader:eq('+activepoint+')').trigger('click'); 
      
        } else if (e.which == 38 && activepoint > 0) { // if uparrow is used and active MP is not the first one 
        
        activepoint -= 1;
        $('.sectionheader:eq('+activepoint+')').trigger('click'); 
        e.preventDefault();
        
      } else if (e.which == 38 && activepoint === 0) { // if uparrow is used and active MP is the first one
            e.preventDefault();

            $('.prev, .next').remove();
            $(document).unbind('keydown');
                if ($.browser.opera) {
                    $('.imgcontent.active div').hide();
                }
            $('.imgcontent:first').hide('blind', '', 400, function() {
            
            $(this).removeClass('active').css('left', 0);
            $('.sectionheader.active').removeClass('active');
          
            activepoint = -1;
          keynav(-1); // assign keyboard nav again
            
        });
    }
    });
    }
    

keynav(-1); // assign keyboard navigation on page load
   $('#keysimg').css('left', $(window).width()-$('#keysimg').outerWidth()-30);
    
    function menuclick() {
  
    $('.sectionheader').click(function() {  // A menupoint (MP) is clicked....
if ($.browser.opera) {

    $('.imgcontent.active div').hide();
}
    $(document).unbind('keydown'); // disbable keyboard during processing....


    $('.sectionheader').unbind('click');
    var activemargin = 0; 
    var sectionheaderprev = $(this).prevAll('.sectionheader').length;
    var sectionheadernext = $(this).nextAll('.sectionheader').length;
         $('.logo').css('cursor', 'pointer');
        $('.prev, .next').remove(); // remove navigation arrows
    
    if (sectionheaderprev > 0 && $(this).attr('class') != 'sectionheader active' && sectionheadernext !== 0) { // determine if MP should have an animated margin/padding-top
        activemargin = 20;
    } else {
        activemargin = 0;
    }
    
    $('.sectionheader.active').animate({'margin-top': 0}, 300); // animate a 0 margin on the currently active MP
    
    $(this).animate({'margin-top': activemargin}, 300, function() { // animate a set margin on the clicked MP.
        
        if (sectionheadernext == 1 && $(this).attr('class') != 'sectionheader active')  {  // remove extra padding on contact MP if the second to last MP was clicked
            $('.sectionheader:last').animate({'padding-top': 0}, 300);
        } else {
            $('.sectionheader:last').animate({'padding-top': 20}, 300); // else if it was closed or any other MP was clicked, reset the default padding on contact MP.
        }
    
    
        
     $('html').css('overflow-y', 'auto'); // default document scroll to auto
    
        $('#imgcounter span').width(0); // set counter bar to zero
        
        $('.imgcontent img').unbind('click'); // unbind click on images...

        $('.imgcontent div').unbind('mouseenter').unbind('mouseleave'); // ...and unbind handlers on image descriptions
        
        $('.imgdesc').hide().removeClass('active'); // reset potential visible image descriptions... necessary?
    
    
        
        var clickedindex = $(this).prevAll('.sectionheader').length; // determine index of clicked MP
        
        $('.imgcontent.active').hide('blind', '', 400, function() { // hide active content
            if ($.browser.opera) {
                $('.imgcontent.active div').hide();
            }
            $(this).removeClass('active').css('left', 0);
        });
        
        if ($(this).hasClass('active') === true) { // in case we click an active MP...
            $(this).removeClass('active'); //... make it inactive...
            keynav(-1); // ... and reassign keyboard input
            menuclick();
                $('body').css('padding-bottom', 0);
     $('.logo').css('cursor', 'auto');
        
        } else { 
            
            $('.sectionheader.active').removeClass('active'); 
            // if MP is not active, make it so, give content plenty of width, and show it, running loadimg() as a callback
            $(this).addClass('active').next('.imgcontent').addClass('active').width(30000).show('blind', '', 400, function() {
            loadimg(clickedindex);
            $(window).trigger('resize');
        });}

        });
    });}
    
    

    
menuclick(); // assign menu navigation on page load     

    
    
});

