$(function() {
    /* name of the selected album, in the top right combo box */
    var album	= $('#albumSelect li:first').data('album');
    /* this is the index of the last clicked picture */
    var current = 1;
		var autohide_thumbs = true;
		var use_iscroll = !$.browser.msie; // iscroll throws errors and shit in IE
		var last_url = null;
	
		//buildThumbs();
	
		// Info popup
		$('#popup').hide();
	
		$('#info').live('click',function(){
			$('#popup').fadeToggle();
			album = 'info';
			setLocation();
			return false;
		});
		$('#closePopup').live('click', function(){
			$('#popup').fadeOut();
		});
		
		// autohide thumbs area
		if (!Modernizr.touch && autohide_thumbs){
			setTimeout(hideThumbs, 500);
			$('#bottombar').live('mouseenter', function(){
				showThumbs();
			});
			$('#bottombar').live('mouseleave', function(){
				$('#thumbsWrapper').stop().delay(500).animate({bottom: -85});
			});
		}
		
		function hideThumbs(){
			$('#thumbsWrapper').animate({bottom: -85});
		}
		function showThumbs(){
			$('#thumbsWrapper').stop().animate({bottom: 0});
		}
		
		
    /*
    clicking on a thumb loads the image
    (alt attribute of the thumb is the source of the large image);
    mouseover and mouseout for a nice spotlight hover effect
    */
    $('#thumbsContainer img').live('click',function(){
        current = $(this).data('num');
				setLocation();
    })

    /* when resizing the window resize the picture */
    $(window).bind('resize', function() {
        resize($('#displayed'),0);
    });
    /* Album Combo Events to open, close, and select an album from the combo */
    $('#albumSelect ul li').bind('click',function(){
        var $this 	= $(this);
				if (!$this.hasClass('selected')){
					$this.addClass('selected').siblings().removeClass('selected');
					current = 1;
	        album = $this.data('album');
					setLocation();
				}
    });

		var $iscroll;

		// respond to AJAX address changes 
		//   * calling setLocation() triggers this!	
		$(window).hashchange(function(){
			debug('hash_change:',last_url, location.hash);
			if (last_url == location.hash) return;
			last_url = location.hash;
			var params = location.hash.match(/(\w+)\/?(\w+)?$/);  // like #!/album_name/23
			if (params && params[1]) album = params[1];
			if (params && params[2]) current = parseInt(params[2]);
			if (album=='info'){
				$('#thumbsWrapper').fadeOut();
				$('#albumSelect li').removeClass('selected');
				loadPhoto('assets/info.png','Tom');				
			} else {
				$('#thumbsWrapper').show();
				$('#popup').fadeOut();
				debug('  build with params:',album,current);
				var $li = $('#albumSelect li[data-album="'+album+'"]');
				$li.addClass('selected').siblings().removeClass('selected');
				hilightThumb();
				buildThumbs();
			}
		});

		// start up, init!
		$(window).trigger('hashchange');

	
		$('#imageWrapper').live('mousemove', function(e){ 
			setNavClass(e); 
		});

    $('#imageWrapper').live('click',function(e){
			var $wrapper = $('#imageWrapper');
			if ($wrapper.is('.cursorRight')){
        goRight();
      }
      else if ($wrapper.is('.cursorLeft')){
				goLeft();
      }
			setNavClass(e);
    });
		
		$('#imageWrapper *').disableSelection();
		
		function hilightThumb(){
			var $img = $('#thumbsContainer img:nth-child('+current+')');
			$img.stop().animate({'opacity':'1.0'},200);
			$img.siblings().stop().animate({'opacity':'0.4'},200);			
		}
		
		function setNavClass(e){
			var $image 	= $('#displayed');
			var $wrapper = $('#imageWrapper');
      var imageWidth 	= parseFloat($image.css('width'),10);
			if ($image.offset() === null) return;

      var x = e.pageX - $image.offset().left;
      if (x < (imageWidth/2))
          $wrapper.addClass('cursorLeft').removeClass('cursorRight');
      else if (x > (imageWidth/2)){
          $wrapper.addClass('cursorRight').removeClass('cursorLeft');
      }  		
		}

		function goRight(){
			var count = $('#thumbsContainer img').length;
			if (count > 1){
	      current++;
	      if (current > count){
					current = 1;
				}
				setLocation();
				debug('goRight',current);				
			}
		}

		function goLeft(){
			var count = $('#thumbsContainer img').length;
			if (count > 1){
      	current--;
      	if (current < 1){
					current = $('#thumbsContainer img').length;
				}
      	setLocation();
				debug('goLeft',current);
			}
		}
		
		function setLocation(){
			location.hash = "#!/"+album+'/'+current;
			debug('set loc');
		}


    /*
    function to build the thumbs container
    An AJAX request is made to retrieve the
    photo locations of the selected album
    */
    function buildThumbs(){
				if ($('#thumbsContainer').data('album') == album){
					var $thumb = $('#thumbsContainer img:nth-child('+parseInt(current)+')');
					loadPhoto($thumb.attr('alt'), $thumb.attr('title'));
					return;
				}
        current=1;
        $('#displayed').remove();
        $('#loading').show();
        $.get('ajax/thumbs.php?album='+album, function(data) {
            var countImages = data.length;
            var loaded = 0;
            var $tContainer = $('<div/>',{
                id	: 'thumbsContainer',
                style	: 'visibility:hidden;'
            }).data('album',album);
            for(var i = 0; i < countImages; i++){
                try{
                    var description = data[i].desc;
                }catch(e){
                    description='';
                }
                if(description==undefined) description='';
                if(i==0){
                    /* load 1 image into container*/
                    var $first = $('<img id="displayed" style="display:block;" />');
										$first.load(function(){
                   		$('#loading').fadeOut();
                      resize($first,0);
	                    $('#imageWrapper').append($first).hide().fadeIn(200);
	                    $('#description').html(description);
										}).attr('src',data[i].alt);
                }
                var $img = $('<img title="'+description+'" data-num="'+(i+1)+'" alt="'+data[i].alt+'" height="75" />');
								$img.load(function(){
										loaded++;
                    if(loaded == countImages){
												if (use_iscroll && $iscroll){
													$iscroll.destroy();
												}
                        $('#thumbsWrapper').html($tContainer);
                        thumbsDim($tContainer);                        
												var $thumb = $('#thumbsContainer img:nth-child('+parseInt(current)+')');
												loadPhoto($thumb.attr('alt'), $thumb.attr('title'));
												if (use_iscroll){
													setTimeout(function(){													
														$iscroll = new iScroll('thumbsWrapper',{snap:'img'});
													},10);													
												} else {
													makeScrollable($('#thumbsWrapper'),$tContainer,15);
												}
                    }
                }).attr('src',data[i].src).appendTo($tContainer).css({opacity:0}).delay(50*i).animate({opacity:0.4},400);
            }
        },'json');
    }


    /* adjust the size (width) of the scrollable container
    - this depends on all its images widths
    */
    function thumbsDim($elem){
        var finalW = 0;
        $elem.find('img').each(function(i){
            var $img 		= $(this);
            finalW+=$img.width()+5;
        //plus 5 -> 4 margins + 1 to avoid rounded calculations
        });
        $elem.css('width',finalW+'px').css('visibility','visible');
    }
    /*
    loads a picture into the imageWrapper
    the image source is in the thumb's alt attribute
    */
    function loadPhoto(src, title){
        $('#displayed').remove();
        $('#loading').show();
        $('<img id="displayed" title="'+title+'" style="display:none;"/>').load(function(){
            var $this = $(this);
            $('#loading').hide();
            resize($this,0);
            if(!$('#imageWrapper').find('img').length){
                $('#imageWrapper').append($this.fadeIn(600));
                $('#description').html($this.attr('title'));
								$('#imageWrapper *').disableSelection();
            }
						hilightThumb();
        }).attr('src',src);
    }
    //functions to control the albums combos
    function closeAlbumCombo(){
        var $combo = $('#albumSelect div');
        $combo.addClass('down').removeClass('up');
        $combo.prev().hide();
    }
    function openAlbumCombo(){
        var $combo = $('#albumSelect div');
        $combo.addClass('up').removeClass('down');
        $combo.prev().show();
    }
    function orderCombo($ul){
        var items = $ul.find('li').get();
        items.sort(function(a,b){
            var keyA = $(a).text();
            var keyB = $(b).text();

            if (keyA < keyB) return -1;
            if (keyA > keyB) return 1;
            return 0;
        });
        $.each(items, function(i, li){
            $ul.append(li);
        });
    }
    //Get our elements for faster access and set overlay width
    function makeScrollable($wrapper, $container, contPadding){
        //Get menu width
        var divWidth = $wrapper.width();

        //Remove scrollbars
        $wrapper.css({
            overflow: 'hidden'
        });

        //Find last image container
        var lastLi = $container.find('img:last-child');
        $wrapper.scrollLeft(0);
        //When user move mouse over menu
        $wrapper.unbind('mousemove').bind('mousemove',function(e){

            //As images are loaded ul width increases,
            //so we recalculate it each time
            var ulWidth = lastLi[0].offsetLeft + lastLi.outerWidth() + contPadding;

            var left = (e.pageX - $wrapper.offset().left) * (ulWidth-divWidth) / divWidth;
            $wrapper.scrollLeft(left);
        });
    }

		function placeArrows(){
			var h = $(window).height() - $('#bottomBar').height();
			var $left = $('#arrowLeft');
			var $right = $('#arrowRight');
			var top = h/2 - $left.height();
			$left.css({top: top});
			$right.css({top: top});			
		}

    /* function to resize an image based on the windows width and height */
    function resize($image, type){
			// debug('resize', $image, type);
        var widthMargin     = 10
        var heightMargin    = 150;
        //type 1 is animate, type 0 is normal
        var windowH      = $(window).height()-heightMargin;
        var windowW      = $(window).width()-widthMargin;
        var theImage     = new Image();
        theImage.src     = $image.attr("src");
        var imgwidth     = theImage.width;
        var imgheight    = theImage.height;

        if((imgwidth > windowW)||(imgheight > windowH)){
            if(imgwidth > imgheight){
                var newwidth = windowW;
                var ratio = imgwidth / windowW;
                var newheight = imgheight / ratio;
                theImage.height = newheight;
                theImage.width= newwidth;
                if(newheight>windowH){
                    var newnewheight = windowH;
                    var newratio = newheight/windowH;
                    var newnewwidth =newwidth/newratio;
                    theImage.width = newnewwidth;
                    theImage.height= newnewheight;
                }
            }
            else{
                var newheight = windowH;
                var ratio = imgheight / windowH;
                var newwidth = imgwidth / ratio;
                theImage.height = newheight;
                theImage.width= newwidth;
                if(newwidth>windowW){
                    var newnewwidth = windowW;
                    var newratio = newwidth/windowW;
                    var newnewheight =newheight/newratio;
                    theImage.height = newnewheight;
                    theImage.width= newnewwidth;
                }
            }
        }
        if ((type==1) && (!$.browser.msie)){
            $image.stop(true).animate({
                'width':theImage.width+'px',
                'height':theImage.height+'px'
            },600);
        } else {
            $image.css({
                'width':theImage.width+'px',
                'height':theImage.height+'px'
            });
				}
				setTimeout(function(){ placeArrows(); }, 200);
    }

		// foz: enhancements

		// hotkeys
		$(document).bind('keydown', function(e){
			debug('keydown', e.which);
			if (e.which == 37){
				goLeft();				
			}
			if (e.which == 39){
				goRight();				
			}			
		});
		

});


// foz: enhancements


function debug(){
   if (typeof console != "undefined"){if (console.log){if (arguments.length == 1){
   console.log(arguments[0]);} else {console.log(arguments);}}}
}

/* disable user selections */
jQuery.fn.disableSelection = function(){
  $(this).each(function(){
		$(this).attr('unselectable', 'on')
           .css('-moz-user-select', 'none')
           .each(function() { 
               this.onselectstart = function() { return false; };
            });
	});
	
};


