$(function() {
    /* name of the selected album, in the top right combo box */
    var album	= '';
    /* mode is small or expanded, depending on the picture size  */
    var mode = 'small';
    /* this is the index of the last clicked picture */
    var current = 2;
	var $imageo = '';
    /* first, let's build the thumbs for the selected album */
    //buildThumbs();
	var substr1 = '';
	
    /*
    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
    */
	
	//alert('asdf');
	if ($.address.path() == '') {
		//alert('book');
		
		//$('#loading').hide();
		//$('#albumbar').hide();
		//$('#albumSelect').hide();
		//$('#albumlist').hide();
		
		$('#wrapper').css('visibility','visible').fadeIn(2000, function () {
																				buildCollage();
																				
																				//$('#horizon').css('visibility','visible').fadeIn(2000, function () {
									
																				//});
																				//});
		});
		
	 
	}else{
		$.address.init(function(event) {
							 //alert(event.value);
							 
							 $imageo = event.value;
							  //loadPhoto($imageo,'cursorPlus');
							  
								substr1 = $imageo.split('/');
								// substr[0] contains "something"
								 //alert(substr1[3]);
							album	= substr1[3];
							pagenumber = substr1[1];
							current = 2;
								/* mode is small or expanded, depending on the picture size  */
							//alert(substr1[2]);
								/* first, let's build the thumbs for the selected album */
							if (!substr1[2]){
								openvideo();
							}else if (!album && substr1[2] != 'Contact'){
								openpage();
							}else if (substr1[2] == 'Contact'){
								
								opencontactpage();
							}else{
							buildThumbs2();
							}
                    // do something depending on the event.value property, e.g.
                    // $('#content').load(event.value + '.xml');
                });
	}
	function GCD(nums)
{
        if(!nums.length)
                return 0;
        for(var r, a, i = nums.length - 1, GCDNum = nums[i]; i;)
                for(a = nums[--i]; r = a % GCDNum; a = GCDNum, GCDNum = r);
        return GCDNum;
}
 
//alert(GCD([12, 8]));
	 function buildCollage(){
		$('#pageWrapper').hide();
		 album = 16;
        current = 0;
        $('#imageWrapper').empty();
        $('#loading').show();
		//alert(($(window).height()/200)*($(window).width()-270));
		//var amountincollage = Math.round(($(window).height()/200))*Math.round((($(window).width()-270)/200));
		//alert(amountincollage);
		var amountincollage = 150;
		var finalW2 = $(window).width()+470;
		var finalW3 = '';
		var goo = $(window).height()-(Math.floor($(window).height()/150)*150);
					//alert(goo);
					var heighto = (goo/(Math.floor($(window).height()/150)));
					//alert(heighto);
					var heighta = heighto+152;
					//alert(200+heighto);
					var endamount = Math.floor(($(window).width()-270)/heighta)*Math.round(($(window).height())/heighta);
        $.get('/ajax/thumbs_collage.php?amount='+amountincollage+'&album='+album, function(data) {
																						  
            var countImages = data.length;
			
            var count = 0;
			$('#thumbsWrapper').hide();
            var $tContainer = $('<div/>',{
                id	: 'thumbsContainer2',
                style	: 'visibility:hidden;'
            })
			var position;
			//position.top = 0;
			var dobreak = false;
            //for(var i = 0; !dobreak && i < countImages; ++i){
                //alert(i+'a');
				var finalW = 0;
				boom();
				
			function boom(){	
			var i = 0;
			//alert(count);
				try{
                    var description = data[count].desc;
					var linkage = data[count].alt;
					
					$('#description').hide();
                }catch(e){
                    description='';
                }
                if(description==undefined)
                    description='';
					//ar heightofcollage = ($(window).height()/200)-Math.round($(window).height()/200);
					
					//var heightofcollage = sumptin.split('.');
								// substr[0] contains "something"
								 //alert(substr1[3]);
					//alert(Math.round($(window).height()/200));
					//alert(($(window).height()/200)*200);
					
					
					//alert(endamount);
					//alert(data[count].alt);
                $('<img title="'+description+'" alt="'+data[count].alt+'" height="'+heighta+'px" />').load(function(){
																										
                    var $this = $(this);
					
                    
					
					$tContainer.append($this);
					 $('#collageWrapper').empty().append($tContainer);
					finalW+=$this.width();
					//alert($(window).width()-270+'-'+finalW);
					if (finalW > $(window).width()-270-150) {
							finalW3 = finalW;
							//alert(finalW);
							//var $div = $('<div class="error"></div>').html('No more foo allowed')
                                        // .append('<br />');
							//$tContainer.html($div);
							//$($tContainer).html('No more foo allowed').append('<br />');
							$('#thumbsContainer2').append('<br />');
							
							
							if (position.top > $(window).height()){
								//alert('boom');
							}
							//if (finalW > finalW2) {
							//finalW2 = finalW;
							//}
							//alert($(window).width()+'and'+finalW);
							finalW = 0;
							
						}
						
						
					$tContainer.css('visibility','visible');
					position = $this.show().position();
					//alert(position.top);
					//alert(finalW);
					//alert('finalW '+finalW+'  total width '+($(window).width()-270));
					
							//alert(finalW2);
					
					
					 
                        //thumbsDim($tContainer);
						
					
						$tContainer.find('img').each(function(count){
															  
							var $img 		= $(this);
							//finalW+=$img.width()+0;
							
							//random fade in
							//alert($img.position.top);
							var v = $("#thumbsContainer2 img").css('visibility', 'hidden'), cur = 0;
						    //end random fade in
							
						//plus 5 -> 4 margins + 1 to avoid rounded calculations
						});
						
						$('#thumbsWrapper img').css('margin','0px');
						//alert($tContainer.position.top);
						//$tContainer.css('width',finalW2+'px').css('visibility','visible');
						//alert($('#collageWrapper').height());
                        //makeScrollable($('#thumbsWrapper'),$tContainer,15);
					//$this.hide();
					//$this.fadeIn();
                    ++count;
					//alert(count);
					//alert($this.attr('alt')+$imageo);
					var $imageo2 = $this.attr('alt');
					var substr2 = $imageo2.split('/');
						
								// substr[0] contains "something"
								 //alert(substr1[2]);
                    //alert(count);
					//alert(i);
					//if(count==1){
						newloadwidth = 215/endamount*count;
						$('#loading').css('width',newloadwidth+'px');
						//$('#loading').hide();
                        /* load 1 image into container*/
                       // $('<img id="displayed" style="display:block;" class="cursorPlus"/>').load(function(){
                         //   var $first = $(this);
                           // $('#loading').hide();
                            //resize($first,0);
							
                            //$('#imageWrapper').append($first);
							
							//$('#description').html($this.attr('title'));
							//$('#description').fadeIn(1000);
							//$.address.value('/'+linkage);
							
                            
                        //}).attr('src',$this.attr('alt'));
                   // }
					//alert($(window).width()-270-150'this is the width');
					windowwidth = $(window).width()-270-150;
					//alert(finalW+' asdf '+windowwidth);
					if(count==endamount || count==countImages){
						$('#loading').fadeOut();
                    //if(position.top > $(window).height()-heighta-20 && finalW == 0){
						$('#wrapper').css('visibility','visible').fadeOut(2000, function () {	
																						  $('#horizon').hide();
																				$('#albumSelect').fadeIn(200, function () {
																				$('#albumlist').fadeIn();
																				//$('#albumSelect').fadeIn();
																				
																					
						//dobreak = true;
						$('#thumbsContainer2').css('width', finalW3).css('float', 'right');
						v = $("#thumbsContainer2 img").css('visibility', 'hidden'), cur = 0;
					for(var j, x, i = v.length; i; j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x);
							function fadeInNextLI() {
								//var v = $("#thumbsContainer2 img").css('visibility', 'visible');
							  v.eq(cur++).css('visibility','visible').hide().fadeIn(500);
							  if(cur != v.length) setTimeout(fadeInNextLI, 200);
							}
							fadeInNextLI();
                        //$('#thumbsWrapper').empty().append($tContainer);
                       // thumbsDim($tContainer);
                       // makeScrollable($('#thumbsWrapper'),$tContainer,15);
					   });
																				});
                    }else{
						
						//i = count;
						//++i
						//alert(i);
						boom();
					}
					
					//alert(i+'b');
                }).attr('src',data[count].src);
				$tContainer.css('width',finalW2+'px');
				
				//alert(i+'-'+finalW2);
				//alert(finalW2);
				//$tContainer.css('width','270px').css('overflow','hidden');
				
            }
        },'json');
		
		
    }
	$('#thumbsContainer2 img').live('click',function(){
		var $this   = $(this);
		
		
		$('.active').stop().animate({
            'opacity':'0.4'
        },200);
		$('.active').removeClass('active');
		$(this).addClass('active');
					$('#description').hide();
        //loadPhoto($(this),'cursorPlus');
		$.address.value('/'+$(this).attr('alt'));
		$('#collageWrapper').hide();
		$('#thumbsWrapper').show();
		
		  $imageo = '/'+$(this).attr('alt');
							  //loadPhoto($imageo,'cursorPlus');
							  
								substr1 = $imageo.split('/');
								// substr[0] contains "something"
								 //alert(substr1[3]);
							album	= substr1[3];
							current = 2;
								/* mode is small or expanded, depending on the picture size  */
							
								/* first, let's build the thumbs for the selected album */
							buildThumbs2();
                        
    }).live('mouseover',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'0.4'
        },200);
    }).live('mouseout',function(){
        var $this   = $(this);
		if ($(this).hasClass('active') == false) {
        $this.stop().animate({
            'opacity':'1.0'
        },200);
		}
    });
    $('#thumbsContainer img').live('click',function(){
		var $this   = $(this);
		$('.active').stop().animate({
            'opacity':'0.4'
        },200);
		$('.active').removeClass('active');
		$(this).addClass('active');
					$('#description').hide();
        loadPhoto($(this),'cursorPlus');
		$.address.value('/'+$(this).attr('alt'));
		
		
                        
    }).live('mouseover',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'1.0'
        },200);
    }).live('mouseout',function(){
        var $this   = $(this);
		if ($(this).hasClass('active') == false) {
        $this.stop().animate({
            'opacity':'0.4'
        },200);
		}
    });
    /* 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 */
   jQuery.fn.initMenu = function() {  
    return this.each(function(){
        var theMenu = $(this).get(0);
        $('.acitem', this).hide();
        $('li.expand > .acitem', this).show();
        $('li.expand > .acitem', this).prev().addClass('active');
        $('li a', this).click(
            function(e) {
				
                e.stopImmediatePropagation();
                var theElement = $(this).next();
                var parent = this.parentNode.parentNode;
                if($(parent).hasClass('noaccordion')) {
                    if(theElement[0] === undefined) {
                        window.location.href = this.href;
						//alert('asdf');
						
                    }
                    $(theElement).slideToggle('normal', function() {
                        if ($(this).is(':visible')) {
                            $(this).prev().addClass('active');
                        }
                        else {
                            $(this).prev().removeClass('active');
                        }    
                    });
                    return false;
                }
                else {
					
                    if(theElement.hasClass('acitem') && theElement.is(':visible')) {
						
                        if($(parent).hasClass('collapsible') || $(parent).parent().parent().hasClass('collapsible')) {
                            $('.acitem:visible', parent).first().slideUp('normal', 
                            function() {
                                $(this).prev().removeClass('active');
                            }
                        );
                        return false;  
                    }
                    return false;
                }
                if(theElement.hasClass('acitem') && !theElement.is(':visible')) {   
				
                    $('.acitem:visible', parent).first().slideUp('normal', function() {
                        $(this).prev().removeClass('active');
                    });
                    theElement.slideDown('normal', function() {
                        $(this).prev().addClass('active');
                    });
                    return false;
                }else{
					$('.acitem:visible', parent).first().slideUp('normal', function() {
                        $(this).prev().removeClass('active');
                    });
                    theElement.slideDown('normal', function() {
                        $(this).prev().addClass('active');
                    });
					
					
					if($(this).hasClass('pages')) { 
					//alert($(this).attr('id'));
					//$('#preview').show();
					$.address.value('/'+$(this).attr('id')+'/'+$(this).attr('alt'));
					$('#description').hide();
							//var $this 	= $(this);
							//album 		= $this.attr('id');
							//buildThumbs();
							$('#loading2').hide();
							$('#pageWrapper').empty().hide();
						   $('#collageWrapper').hide();
						   $('#imageWrapper').hide();
						   $('#thumbsWrapper').hide();
							$('#albumSelect li a').removeClass('selected');
							$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					$('#pageWrapper').load("/ajax/page.php?pageid="+$(this).attr('id')).fadeIn(function(){
											$('#pageWrapper').css('height',$(window).height()-105).css('overflow','auto');
																										});
					
					}else if($(this).hasClass('video')) { 
					//alert($(this).attr('id'));
					//$('#preview').show();
					$.address.value('/'+$(this).attr('id'));
					$('#description').hide();
					$('#pageWrapper').fadeOut();
							//var $this 	= $(this);
							//album 		= $this.attr('id');
							//buildThumbs();
							$('#loading2').hide();
							$('#pageWrapper').empty().hide();
						   $('#collageWrapper').hide();
						   $('#imageWrapper').hide();
						   $('#thumbsWrapper').hide();
							$('#albumSelect li a').removeClass('selected');
							$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					 var winH      = $(window).height()-200;
        			var winW      = $(window).width()-370;
					$('#pageWrapper').load("/ajax/video.php?winh="+winH+"&winw="+winW+"&pageid="+$(this).attr('id')).fadeIn();
					
					}else if($(this).hasClass('contact')) { 
					//alert($(this).attr('id'));
					//$('#preview').show();
					$.address.value('/'+$(this).attr('id')+'/'+$(this).attr('alt'));
					$('#description').hide();
							//var $this 	= $(this);
							//album 		= $this.attr('id');
							//buildThumbs();
							 $('#loading2').hide();
							$('#pageWrapper').empty().hide();
						   $('#collageWrapper').hide();
						   $('#imageWrapper').hide();
						   $('#thumbsWrapper').hide();
							$('#albumSelect li a').removeClass('selected');
							$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					 var winH      = $(window).height()-200;
        			var winW      = $(window).width()-370;
					$('#pageWrapper').load("/ajax/contact.php?winh="+winH+"&winw="+winW+"&pageid="+$(this).attr('id')).fadeIn(function(){
											$('#pageWrapper').css('height',$(window).height()-105).css('overflow','auto');
																										});
					
					}else{
						 $('#description').hide();
							var $this 	= $(this);
							album 		= $this.attr('id');
							buildThumbs();
							$('#pageWrapper').empty().hide();
						   $('#collageWrapper').fadeOut();
						   
						   $('#imageWrapper').show();
							$('#albumSelect li a').removeClass('selected');
							$('#albumSelect ul.acitem').removeClass('selected');
							$this.addClass('selected');
					}
				}
            }
        }
    );
});
};

$(document).ready(function() {$('.menu').initMenu();});
    //$('#albumSelect ul > li').bind('click',function(){
    //    $('#description').hide();
	//	var $this 	= $(this);
    //    album 		= $this.attr('id');
    //    buildThumbs();
   //    $('#collageWrapper').hide();
	//   $('#thumbsWrapper').show();
	//	$('#albumSelect ul > li').removeClass('selected');
    //    $this.addClass('selected')
   // });
	
    /*
	when hovering the main image change the mouse icons (left,right,plus,minus) 
	also when clicking on the image, expand it or make it smaller depending on the mode
	*/
    $('#displayed').live('mousemove',function(e){
        var $this 	= $(this);
        var imageWidth 	= parseFloat($this.css('width'),10);
		
        var x = e.pageX - $this.offset().left;
        if(x<(imageWidth/3))
            $this.addClass('cursorLeft')
            .removeClass('cursorPlus cursorRight cursorMinus');
        else if(x>(2*(imageWidth/3)))
            $this.addClass('cursorRight')
            .removeClass('cursorPlus cursorLeft cursorMinus');
        else{
            if(mode=='expanded'){
                $this.addClass('cursorMinus')
                .removeClass('cursorLeft cursorRight cursorPlus');
            }
            else if(mode=='small'){
                $this.addClass('cursorPlus')
                .removeClass('cursorLeft cursorRight cursorMinus');
            }
        }
    }).live('click',function(){
        var $this = $(this);
        if(mode=='expanded' && $this.is('.cursorMinus')){
            mode='small';
            $this.addClass('cursorPlus')
            .removeClass('cursorLeft cursorRight cursorMinus');
            $('#thumbsWrapper').stop().animate({
                'bottom':'0px'
            },300);
            resize($this,1);
        }
        else if(mode=='small' && $this.is('.cursorPlus')){
            mode='expanded';
            $this.addClass('cursorMinus')
            .removeClass('cursorLeft cursorRight cursorPlus');
            $('#thumbsWrapper').stop().animate({
                'bottom':'-105px'
            },300);
            resize($this,1);
        }
        else if($this.is('.cursorRight')){
			
            var $thumb = $('#thumbsContainer img:nth-child('+parseInt(current+1)+')');
            if($thumb.length){
                ++current;
                loadPhoto($thumb,'cursorRight');
            }
        }
        else if($this.is('.cursorLeft')){
            var $thumb = $('#thumbsContainer img:nth-child('+parseInt(current-1)+')');
            if($thumb.length){
                --current;
                loadPhoto($thumb,'cursorLeft');
            }
        }
    });
    /*
    function to build the thumbs container
    An AJAX request is made to retrieve the
    photo locations of the selected album
    */
	
    function buildThumbs(){
        current = 0;
		$('#thumbsWrapper').empty().show();
        $('#imageWrapper').empty();
        $('#loading').show();
        $.get('/ajax/thumbs.php?album='+album, function(data) {
            var countImages = data.length;
			//alert(data.length);
			if (data.length == 0){
				$('#pageWrapper').show().html('nothing in this gallery yet!');
			}
            var count = 0;
            var $tContainer = $('<div/>',{
                id	: 'thumbsContainer',
                style	: 'visibility:hidden;'
            })
            for(var i = 0; i < countImages; ++i){
                try{
                    var description = data[i].desc;
					var linkage = data[i].alt;
					
					$('#description').hide();
                }catch(e){
                    description='';
                }
                if(description==undefined)
                    description='';
                $('<img title="'+description+'" alt="'+data[i].alt+'" height="75" />').load(function(){
                    var $this = $(this);
                    $tContainer.append($this);
					 $('#thumbsWrapper').empty().append($tContainer);
                        thumbsDim($tContainer);
                        makeScrollable($('#thumbsWrapper'),$tContainer,15);
					$this.hide();
					$this.fadeIn();
                    ++count;
					//alert($this.attr('alt')+$imageo);
					var $imageo2 = $this.attr('alt');
					var substr2 = $imageo2.split('/');
								// substr[0] contains "something"
								 //alert(substr1[2]);
                    if(count==1){
                        /* load 1 image into container*/
                        $('<img id="displayed" style="display:block;" class="cursorPlus"/>').load(function(){
                            var $first = $(this);
                            $('#loading').hide();
                            resize($first,0);
                            $('#imageWrapper').append($first.fadeIn(1000, function () {
																					}));
							$('#description').html($this.attr('title'));
							$('#description').fadeIn(1000);
							$.address.value('/'+$imageo2);
							//alert(substr1[4]);
							//substr1 = substr2[3];
							//alert(substr2[3]);
							selectedthumb = substr2[3].split('.');
							$("img[src*='"+selectedthumb[0]+"_thumb.jpg']").addClass('active');
                            $('.active').stop().animate({
								'opacity':'1.0'
							},200);
                            
                        }).attr('src',$this.attr('alt'));
                    }
                    //if(count == countImages){
                        //$('#thumbsWrapper').empty().append($tContainer);
                       // thumbsDim($tContainer);
                       // makeScrollable($('#thumbsWrapper'),$tContainer,15);
                    //}
                }).attr('src',data[i].src);
            }
        },'json');
    }
	function openpage(){
		$('#albumSelect').fadeIn(200, function () {
																				$('#albumlist').fadeIn();
																														});
			//$('#loading2').hide();
							//$('#pageWrapper').empty().css('width',$(window).width()-270+'px');
						//   $('#collageWrapper').hide();
						 //  $('#imageWrapper').hide();
						 //  $('#thumbsWrapper').hide();
						//	$('#albumSelect li a').removeClass('selected');
							//$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					$('#pageWrapper').load("/ajax/page.php?pageid="+pagenumber).fadeIn(function(){
											$('#pageWrapper').css('width',$(window).width()-300+'px').css('height',$(window).height()-105).css('overflow','auto');
																										});
	}
	function openvideo(){
		$('#albumSelect').fadeIn(200, function () {
																				$('#albumlist').fadeIn();
																														});
			//$('#loading2').hide();
							//$('#pageWrapper').empty().css('width',$(window).width()-270+'px');
						//   $('#collageWrapper').hide();
						 //  $('#imageWrapper').hide();
						 //  $('#thumbsWrapper').hide();
						//	$('#albumSelect li a').removeClass('selected');
							//$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					 var winH      = $(window).height()-200;
        			var winW      = $(window).width()-370;
					$('#pageWrapper').load("/ajax/video.php?winh="+winH+"&winw="+winW+"&pageid="+pagenumber).fadeIn();
	}
	function opencontactpage(){
		$('#albumSelect').fadeIn(200, function () {
																				$('#albumlist').fadeIn();
																														});
			//$('#loading2').hide();
							$('#pageWrapper').empty().hide();
						//   $('#collageWrapper').hide();
						 //  $('#imageWrapper').hide();
						 //  $('#thumbsWrapper').hide();
						//	$('#albumSelect li a').removeClass('selected');
							//$(this).addClass('selected');
					$('#preview').css('visibility','visible').css('color','#000000');
					 var winH      = $(window).height()-200;
        			var winW      = $(window).width()-370;
					$('#pageWrapper').load("/ajax/contact.php?pageid="+pagenumber).fadeIn(function(){
											$('#pageWrapper').css('width',$(window).width()-300+'px').css('height',$(window).height()-105).css('overflow','auto');
																										});
	
	}
	function buildThumbs2(){
        $('#albumSelect').fadeIn(200, function () {
																				$('#albumlist').fadeIn();
																														});
        $('#imageWrapper').empty();
        $('#loading2').show();
        $.get('/ajax/thumbs.php?album='+album, function(data) {
            var countImages = data.length;
            var count = 0;
            var $tContainer = $('<div/>',{
                id	: 'thumbsContainer',
                style	: 'visibility:hidden;'
            })
            for(var i = 0; i < countImages; ++i){
                try{
                    var description = data[i].desc;
					var linkage = data[i].alt;
					$('#description').hide();
                }catch(e){
                    description='';
                }
                if(description==undefined)
                    description='';
                $('<img title="'+description+'" alt="'+data[i].alt+'" height="75" />').load(function(){
                    var $this = $(this);
                    $tContainer.append($this);
					 $('#thumbsWrapper').empty().append($tContainer);
                        thumbsDim($tContainer);
                        makeScrollable($('#thumbsWrapper'),$tContainer,15);
					$this.hide();
					$this.fadeIn();
                    ++count;
					//alert($this.attr('alt')+$imageo);
					var $imageo2 = $this.attr('alt');
					var substr2 = $imageo2.split('/');
								// substr[0] contains "something"
								 //alert(substr1[2]);
                    if(substr2[3]==substr1[4]){
						
						//alert(selectedthumb[0]);
						
						//$('#thumbsContainer img').(selectedthumb[0]+'_thumb.jpg').css('visibility','hidden');
                        /* load 1 image into container*/
                        $('<img id="displayed" style="display:block;" class="cursorPlus"/>').load(function(){
                            var $first = $(this);
                            $('#loading').hide();
                            resize($first,0);
                            $('#imageWrapper').append($first.fadeIn(1000, function () {
																					}));
							$('#description').html($this.attr('title'));
							$('#description').fadeIn(1000);
							$.address.value('/'+$imageo2);
							selectedthumb = substr1[4].split('.');
							$("img[src*='"+selectedthumb[0]+"_thumb.jpg']").addClass('active');
                            $('.active').stop().animate({
								'opacity':'1.0'
							},200);
                        }).attr('src',$this.attr('alt'));
                    }
                    //if(count == countImages){
                        //$('#thumbsWrapper').empty().append($tContainer);
                        //thumbsDim($tContainer);
                        //makeScrollable($('#thumbsWrapper'),$tContainer,15);
                    //}
                }).attr('src',data[i].src);
            }
        },'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($thumb,cursorClass){
		 current		= $thumb.index()+1;
        $('#imageWrapper').empty();
        $('#loading2').show();
        $('<img id="displayed" title="'+$thumb.attr('title')+'" class="'+cursorClass+'" style="display:none;"/>').load(function(){
            var $this = $(this);
			
            $('#loading2').hide();
            resize($this,0);
            if(!$('#imageWrapper').find('img').length){
                $('#imageWrapper').append($this.fadeIn(1000));
				$('#description').fadeIn(1000);
                $('#description').html($this.attr('title'));
            }
        }).attr('src',$thumb.attr('alt'));
    }
    //functions to control the albums combos
    function closeAlbumCombo(){
       
    }
    function openAlbumCombo(){
      
    }
    function orderCombo($ul){

    }
    //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 to resize an image based on the windows width and height */
    function resize($image, type){
        var widthMargin     = 50
        var heightMargin    = 10;
        if(mode=='expanded')
            heightMargin = 50;
        else if(mode=='small')
            heightMargin = 160;
        //type 1 is animate, type 0 is normal
        var windowH      = $(window).height()-heightMargin;
        var windowW      = $(window).width()-widthMargin-270;
        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({
				'margin-top':windowH/2-theImage.height/2+'px',
                'width':theImage.width+'px',
                'height':theImage.height+'px'
            },1000);
			$('#descriptionWrapper').css('width',theImage.width+'px').css('padding-left', '270px').css('margin', 'auto');
		}else{
            $image.css({
				'margin-top':windowH/2-theImage.height/2+'px',
                'width':theImage.width+'px',
                'height':theImage.height+'px'
            });
			//alert(theImage.width);
			$('#descriptionWrapper').css('width',theImage.width+'px').css('padding-left', '270px').css('margin', 'auto').css('text-align', 'right');
		}
    }
});
