jQuery(document).ready(function($) {
    
    /* mode is small or expanded, depending on the picture size  */
    var mode = 'small';
    /* this is the index of the last clicked picture */
    var current = 0;
	
    /* first, let's build the thumbs for the selected album */
    
	$('.PortfolioRow').bind('click',function(){										 	
		$('.menu a').removeClass('selected');
		//$('.HomePagePad').removeClass('HomePagePad').addClass('PortfolioPagePad');
		$('div.RightPanel').hide();
		$('.RightPanelTextPad div.Overflow').html('');
		$('.ServicesRightPanelTextPad div.Overflow').html('');
		$('.AboutRightPanelTextPad div.Overflow div.Left').html('');
		$('.AboutRightPanelTextPad div.Overflow div.Right').html('');
		$('.loading').show();
		$('.PortfolioRow').children('.LeftText').removeClass('selected');
		$('.PortfolioRow').children('.RightImage').removeClass('selectedRightImage');
		$(this).children('.LeftText').addClass('selected');
		$(this).children('.RightImage').addClass('selectedRightImage');
		var cid = $(this).attr('id');
		mode = 'small';
		current = 0;
		$('.PortfolioRightPanel').fadeOut('slow', function(){			
			buildThumbs(cid);
		});
 	});
    /*
    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(){
        $('#desccontainercontent').hide();
		loadPhoto($(this),'cursorPlus');
    }).live('mouseover',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'0.7'
        },200);
    }).live('mouseout',function(){
        var $this   = $(this);
        $this.stop().animate({
            'opacity':'1.0'
        },200);
    });
    /* when resizing the window resize the picture */
    $(window).bind('resize', function() {
        resize($('#displayed'),0);
    });
   
    
	$('#previmg').bind('click',function(){
		var $thumb = $('#thumbsContainer div:nth-child('+parseInt(current-1)+')>img');
            if($thumb.length){
                --current;
                loadPhoto($thumb,'cursorLeft');
            }
	});
	$('#nextimg').bind('click',function(){
		var $thumb = $('#thumbsContainer div:nth-child('+parseInt(current+1)+')>img');
            if($thumb.length){
                ++current;
                loadPhoto($thumb,'cursorRight');
            }
	});
	$('#desccontainer').hover(function(){
		$('#desccontainerheading').slideUp("slow");
		$('#desccontainercontent').slideDown("slow");
	},function(){
		$('#desccontainerheading').slideDown("slow");
		$('#desccontainercontent').slideUp("slow");
	});
    /*
    function to build the thumbs container
    An AJAX request is made to retrieve the
    photo locations of the selected album
    */
    function buildThumbs(cid){		
        current=1;
        $('#imageWrapper').empty();
        $('#loading').show();
		var desc_content="";
        $.get('thumbs.php?cid='+cid, 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;
                }catch(e){
                    description='';
                }
				if(i==0)
				{
					desc_content = data[i].desc;
				}
				
                if(description==undefined)
                    description='';
				var $tImg = "";
				if(i==0){
					$tImg = $('<img />',{
						id : data[i].id,
						src	: data[i].src,
						width	: '80',
						height	: '60',
						style:'display: block;margin-bottom:3px;border: 2px solid red;width:80px;height:60px;'
					});
				}
				else
				{
					$tImg = $('<img />',{
						id : data[i].id,
						src	: data[i].src,
						width	: '80',
						height	: '60'
					});
				}
				var imageWidth = 80, imageHeight = 60, reflection, reflectionHeight, wrapper, context, gradient;
				reflectionHeight = Math.floor((2/3 > 1) ? Math.min(imageHeight, 2/3) : imageHeight * 2/3);
				
				desc = $("<input type='hidden' />")[0];
				$(desc).attr("id", "desc" + data[i].id).css({display: "none"}).val(data[i].desc);
				
				wrapper = $("<div />");
				wrapper.append($tImg);
				wrapper.append(desc);
				$(wrapper).css({width: 88, height: imageHeight + reflectionHeight, overflow: "hidden", float: "left"});
				
				$tContainer.append(wrapper);				
				++count;
				
				if(count == countImages){
					/* load 1 image into container*/					
						$('<img id="displayed" style="display:block;" class="cursorPlus1"/>').load(function(){
							var $first = $(this);
							resize($first,0);
							$('#imageWrapper').append($first);
							$('#desccontainercontent').html(data[0].desc);
							$('#thumbsWrapper').empty().append($tContainer);
							thumbsDim($tContainer);
							makeScrollable($('#thumbsWrapper'),$tContainer,15);								
						}).attr('src',data[0].src);	
					progress=0;
					$tContainer.children('div').children('img').load(function(){
						if(progress == count - 1)
						{
							$('#loading').hide();
							$('.loading').hide();
							$('.PortfolioRightPanel').fadeIn(3000);	
						}
						progress++;
					});
				}
            }			
        },'json');
    }
    /* adjust the size (width) of the scrollable container
    - this depends on all its images widths
    */
    function thumbsDim($elem){
        var finalW = 0;
        $elem.find('div').each(function(i){
            var $img = $(this);
            finalW+=$img.width();
        //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){
		//$('#imageWrapper').fadeOut(750);
		$("#desccontainerheading").empty();
		$('#desccontainercontent').hide();
		$('#thumbsContainer div img').css({border: "none"});		
        current		= parseInt($thumb.parent().index())+1;
		//$("#displayed").fadeOut(750);
		$('#thumbsContainer div:nth-child('+parseInt(current)+') img').css({border: "2px solid red"});
        $('#imageWrapper').empty();
        $('#loading').show();
        $('<img id="displayed" title="'+$thumb.attr('title')+'" class="'+cursorClass+'1" style="display:none;"/>').load(function(){
            var $this = $(this);
            $('#loading').hide();
            resize($this,0);
            if(!$('#imageWrapper').find('img').length){
                $('#imageWrapper').append($this.fadeIn(1500));
                $('#desccontainercontent').html($('#desc'+$thumb.attr('id')).val());
            }
        }).attr('src',$thumb.attr('src'));//$('#imageWrapper').fadeIn(750);
		//
    }
   
    //Get our elements for faster access and set overlay width
    function makeScrollable($wrapper, $container, contPadding){
        //Get menu width
        var divWidth = 633;//$wrapper.width();alert(divWidth);

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

        //Find last image container
        var lastLi = $container.find('div:last-child');//alert(lastLi);
        $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);
        });
		$("#nextimgthumb").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);
        });
		$("#previmgthumb").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     = 10
        var heightMargin    = 0;
        if(mode=='expanded')
            heightMargin = 60;
        else if(mode=='small')
            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==0)&&(!$.browser.msie))
            $image.css({//$image.stop(true).animate({
                'width':'640px',
                'height':'445px'
            },1000);
        else
            $image.css({
                'width':'639px',
                'height':'432px'
            });//theImage.width,theImage.height
		$("#desccontainerheading").html("<strong>+Description</strong>");
    }
});
