
$(function(){






        // images length
        var max = $(images).length;
        // at least 1 image exist
        if(max>0)
        {
                // create the UL element
                var ul = $('<ul id="portfolio"></ul>');
                       // append to div#wrapper
                $(ul).appendTo($('#wrapper'));

                // load the first image
                var ulwidth = 0;

                initLayout(0,max);


        }


        // function of loading image
        // params: (int) index of image in array, (int) length of images array




        function LoadImage(index,max)
        {
                // if current index is lower then max element (max-1)
                if(index<max)
                {
                        var img = new Image();
                               // image onload
                        $(img).load(function ()
                        {

                                var curr = $("ul#portfolio li#portfolio_"+index);
                                var img = new Image();// new image object
                                $(this).css('display','none');
                                $(curr).removeClass('loading');
                                $(curr).find(".boxgrid").prepend(this);
                                $(this).fadeIn('fast',function()
                                {
                                        // once the current loaded, trigger the next image
                                        LoadImage(index+1,max);
                                },

                                        ulwidth = $(ul).width() - 300 + this.width+1,
                                               $(curr).find(".boxgrid").css('width',this.width+1),
                                        //set the width of the covering div, to maximize compatibility to IE6
                                        $(this).parent().parent().find("div").css('width',this.width+1),
                                        $(ul).css('width',ulwidth+1));

                        }).error(function ()
                                {
                                        // on error remove current
                                        $(curr).remove();
                                        // trigger the next image
                                        LoadImage(index+1,max);
                        }).attr('src', images[index]);
                        adjustDragContainment(); 
                }
                if(index == max)
                       {
                                        adjustDragContainment();
                }

        };

         function initLayout(index,max){


                if(index<max)
                {
                        // create the LI, add loading class
                              var list = $('<li id="portfolio_'+index+'"></li>').attr('class','loading');
                              // append to UL
                               $('ul#portfolio').append(list);
                        //create boxgrid
                        var bgrid = $('<div class="boxgrid captionfull"></div>');
                        //Caption
                        var captop = $('<div class="coverT boxcaptionup"></div>').append('<div class="zoom">ZOOM</div>');
                        // create the linkboxes
                        var infobox = $('<div class="infobox"></div>').append('<img src="gfx/bbl.png" class="buttonleft">').append('<img src="gfx/bblogo.png">');
                        var zoombox = $('<div class="zoombox"></div>').append('<img src="gfx/btl.png" class="buttonleft">').append('<img src="gfx/btlogo.png">');

                        // current LI
                               var curr = $("ul#portfolio li#portfolio_"+index);
                               $(curr).append(zoombox).append(bgrid).append(infobox);
                        $(bgrid).append(this).append(captop);
                        createContent(bgrid,index);


                        $(ul).css('width',($(ul).width()+bgrid.width())+"px");

                        initLayout(index+1,max);

                }

                if(index == max)
                       {

                        addHover();
                        initLightbox();
                        initializeDrag();
                        adjustDragContainment();
                               LoadImage(0,max);
                }

         }
        function initLightbox()
        {
                var links = $('div[class^=zoombox]');
                var overlay = $(jQuery('<div id="overlay" style="display: none"></div>'));
                  var container = $(jQuery('<div id="lightbox" style="display: none"></div>'));
                  var close = $(jQuery('<a href="#close" class="close">&times; Close</a>'));
                  var target = $(jQuery('<div class="target"></div>'));
                  var prev = $(jQuery('<a href="#prev" class="prev">&laquo; Previous</a>'));
                  var next = $(jQuery('<a href="#next" class="next">Next &raquo;</a>'));
                $('body').append(overlay).append(container);
                container.append(close).append(target);//.append(prev).append(next);
                container.show().css({'top': Math.round((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - container.outerHeight()) / 2) + 'px', 'left': Math.round(($(window).width() - container.outerWidth()) / 2) + 'px', 'margin-top': 0, 'margin-left': 0}).hide();

                  close.click(function(c)
                  {
                            c.preventDefault();
                            overlay.add(container).fadeOut('normal');
                  });


                links.each(function(index)
                {
                        var link = $(this);
                            link.click(function(c)
                            {
                                      c.preventDefault();
                                      open(large[index]);
                                links.filter('.selected').removeClass('selected');
                                link.addClass('selected');
                              });
                              link.attr({'lb-position': index});
                    });

                var open = function(url)
                {
                            if(container.is(':visible'))
                            {
                                      target.children().fadeOut('normal', function()
                                      {
                                                target.children().remove();
                                                loadImage(url);
                                      });
                            } else
                            {
                                      target.children().remove();
                                      overlay.add(container).fadeIn('normal',function()
                                      {
                                                loadImage(url);
                                      });
                            }
                  };

                var loadImage = function(url)
                {
                            if(container.is('.loading')) { return; }
                            container.addClass('loading');
                            var img = new Image();
                            img.onload = function()
                            {
                                      img.style.display = 'none';
                                      var maxWidth = ($(window).width() - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'), 10)) - 100;
                                      var maxHeight = (($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'), 10)) - 100;
                                if(img.width > maxWidth || img.height > maxHeight)// One of these is larger than the window
                                {
                                                var ratio = img.width / img.height;
                                        var browserRatio = maxWidth / maxHeight;
                                                if(ratio<=browserRatio)
                                                {
                                                  img.height = maxHeight;
                                                  img.width = maxHeight * ratio;
                                          } else {
                                                  img.height = maxWidth / ratio;
                                                  img.width = maxWidth;
                                                  }


                                      }

                              container.animate({'width': img.width,'height': img.height, 'top': Math.round((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - img.height - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + 'px', 'left': Math.round(($(window).width() - img.width - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2) + 'px'},'normal', function(){
                                target.append(img);
                                $(img).fadeIn('normal', function()
                                {
                                  container.removeClass('loading');
                                });
                              })
                            }
                        img.src = url;
                  }

        };
         function initializeDrag()
         {
                $(ul).draggable({axis: 'x'});
         };
         function adjustDragContainment()
         {
                $(ul).draggable('option', 'containment', [(-($(ul).width()-$(window).width()-300-($(ul).children().size()))),0,0,2000]);


         };

        function addHover()
        {
                //Hover for Zoombox
                $('.zoombox').hover(function()
                {
                        $(".coverT", $(this).next()).stop().animate({top:'0px'},{queue:false,duration:240});
                }, function()
                {
                        $(".coverT", $(this).next()).stop().animate({top:'-120px'},{queue:false,duration:240});
                });

                $('.zoombox').hover(function()
                {
                        $(this).find("img").next().attr('src', 'gfx/btlogoi.png');
                },function()
                {
                        $(this).find("img").next().attr('src', 'gfx/btlogo.png');
                });

                //Hover for Infobox
                $('.infobox').hover(function()
                {
                        $(".coverB", $(this).prev()).stop().animate({top:'120px'},{queue:false,duration:240});
                }, function()
                {
                        $(".coverB", $(this).prev()).stop().animate({top:'302px'},{queue:false,duration:240});
                });

                $('.infobox').hover(function()
                {
                        $(this).find("img").next().attr('src', 'gfx/bblogoi.png');
                },function()
                {
                        $(this).find("img").next().attr('src', 'gfx/bblogo.png');}
                );
        };
        function createContent(element,index){


        element.append(
                $('<div class="coverB boxcaption"></div>').append(
                        $('<table style="width:100%;"></table>').append(
                                $('<tbody style="width:100%;"></tbody>').append(
                                        $('<tr></tr>').append('<td class="category">title</td>').append('<td class="info">'+titles[index]+'</td>')).append(
                                        $('<tr></tr>').append('<td class="category">date taken</td>').append('<td class="info">'+dates[index]+'</td>')).append(
                                        $('<tr></tr>').append('<td class="category">tags</td>').append('<td class="info">'+specs[index]+'</td>')).append(
                                        $('<tr></tr>').append('<td class="category">C-Print Size</td>').append('<td class="info">'+printsize[index]+'</td>')).append(
                                        $('<tr></tr>').append('<td class="category">&nbsp;</td>').append('<td class="info">&nbsp;</td>')
                                            )
                                )
                        )
                );



        };
});