/* Harnesslink Website Builder New Gallery
    YS Edward Hsiao 2007-11-08
    http://www.harnesslink.com
    copyright @ Harnesslink Limited
*/
var photo_per_page=9;    // Photo per page (Gallery)
var totalPage=0;         // Total page (Gallery)
var currentPage=1;       // Current page (Gallery)
var totalPhoto=0;        // Total Photo 
var ss_current_photo=0;  // Current Photo (Slides)
var timer=0;             // Timer (Slides)
var photo_height=200;
var photo_width=200;
var photo_original = new Array();
var $gallery;
var $container
var $photoDetails;
var $slides;
var $slidesHeader;
var $slidesDescription;
var $slidesLoader;
var row;
var col;
var init = 0;
var options;

function HLGallery(options) {
    
    this.draw = function() {
        this.setOptions(options);
        $container = $('.container');
        $container.css({ width: photo_width, height: photo_height + 45});
        totalPhoto =  $container.length;
        totalPage=Math.ceil(totalPhoto/photo_per_page);
        row = Math.ceil(Math.sqrt(photo_per_page));
        col = Math.ceil(photo_per_page / row );

        // Gallery
        $gallery = $('.gallery');
        $gallery.prepend($('<div id="selector"></div>').append($('<span id="ss"><a href="#" onclick="hl.slides();return false;">Slide Show</a></span>')));
        for (var i=0 ; i < totalPage; i++) {
              $('#selector').append($('<a href="#" onclick="hl.change('+ (i+1) + ');return false;">'+ (i+1) +'</a>'));
        }
        $photoDetails = $('<div class="detailsBorder"></div><div class="details"></div>').appendTo($(document.body));
        // Slides
        $slides = $('<div class="previous"><a href="#" onclick="hl.update_slide_previous();return false;"><</a></div><div class="next"><a href="#" onclick="hl.update_slide_next();return false;">></a></div>');
        $slidesHeader = $('<div class="header"><div class="ss_selector"></div><div class="auto"></div><div class="ga"><a href="#" onclick="hl.gallery();return false;">Gallery</a></div></div>');
        $slidesLoader = $('<div class="loader">Click to enlarge</div>');
        $slidesDescription = $('<div class="sstitle"></div><div class="ssdescription"><div class="text"></div></div>');
        $gallery.append($slides);
        $gallery.prepend($slidesHeader);
        $gallery.append('<div class="window"></div>');
        $gallery.append($slidesLoader);
        $gallery.append($slidesDescription);
        $container.find('li.information').each(function(i) {
            var size = $(this).text().split('x');
            photo_original[i] = { width : parseInt(size[0]), height : parseInt(size[1]) };
        });
        if (options.type == 0) this.gallery();
        else if (options.type == 1) this.slides();
    };

    this.setOptions = function(options) {
        this.options = options;
        photo_per_page = options.photo_per_page;
        photo_width = options.photo_size;
        photo_height = options.photo_size;
    };

    // change page 
    this.change = function(page) {
        currentPage = page;
        this.update_gallery();
    };
    
    // update the gallery
    this.update_gallery = function() {
        $("#selector").find("a").eq(currentPage).addClass('selected');
        $("#selector").find("a").eq(currentPage).siblings().not(':contains(Slide)').removeClass('selected');
        var object = this;
        $container.hide();
        $container.slice((currentPage-1) * photo_per_page , currentPage *photo_per_page).show();
        var $img = $container.find('li.thumbnail');

        if (init == 0) {
            $img.each(function(i) {
                init = 1;
                var $el = $(this);
                $el.find("a").removeAttr('href');
                var $load = $('.popup').eq(i);
                $load.css({ left: (photo_width - 110) /2, top: (photo_height - 14) /2});
 
                $el.find('img').hover(function() {
                          $load.show();                        
                }, function() {
                          $load.hide();
                });     
                $load.hover(function() {
                          $load.show();
                }, function() {
                }).click(function() { $load.hide();object.details(i);return false;  });
            
            });
        }
        $img.slice((currentPage-1) * photo_per_page , currentPage *photo_per_page).each(function(i) {
              $(this).find('a').unbind().css('cursor', 'pointer');
              $(this).find('a').click(function() {
                            object.details((currentPage-1)* photo_per_page + i);
                        });
        });

        $img.find('img').slice((currentPage-1) * photo_per_page , currentPage *photo_per_page).each(function(i) {
            var $el = $(this);
            var inWidth = photo_original[i + ((currentPage-1) * photo_per_page)].width;
            var inHeight = photo_original[i + ((currentPage-1) * photo_per_page) ].height;

            if (inWidth >= inHeight) {
                var newHeight = (photo_width/inWidth) * inHeight;
                var newWidth = photo_width;
                $el.css({ width : newWidth, height : newHeight });
            }
            else {
                var newHeight = photo_height;   
                var newWidth = (photo_height/inHeight) * inWidth;
                var leftMargin = (photo_width - newWidth) /2;
                $el.css({ width: newWidth, height : newHeight, marginLeft : leftMargin });
            }
        });
    };
    
    // show as a gallery
    this.gallery = function() {
        this.slides_auto(0);
        $gallery.removeClass("slideshow").addClass("gallery");
        $('.scroll').find('a').eq(ss_current_photo).css({  opacity: '1.0' });
        var $img = $('.scroll').find("a");
        $('.scrollDiv').children().remove();
        $img.each(function(i) {
            var $el = $(this);
            $el.removeAttr('href');
            $container.find('ul').eq(i).find('li.thumbnail').append($el);
        });
        $container.show();
        $gallery.width( ($container.width() + 26) * col);
        $gallery.height( ($container.height() + 7 ) * row);
        $('.window').empty();
        $slides.hide();
        $slidesHeader.hide();
        $slidesDescription.hide();
        $('#selector').show();
        $('.scrollDiv').hide();
        $('.loader').hide();
        this.update_gallery();
    };

    // show the details of the photo.
    this.details = function(id) {
        var $detailsBorder = $('.detailsBorder');
        var $details = $('.details');
        var $photo = $container.eq(id).find('ul');

        ($(document).width() > $(window).width()) ? width = $(document).width() : width = $(window).width();
        ($(document).height() > $(window).height()) ? height = $(document).height() : height = $(window).height();

        $detailsBorder.width(width).height(height).show();

        var arrPageScroll =getPageScroll();
        var arrPageSizes = getPageSize();

        var item_title =  $photo.find('li.item_title').html();
        var mi_title =  $photo.find('li.mi_title').html();
        var mi_caption =  $photo.find('li.mi_caption').html();
        var mi_description =  $photo.find('li.mi_description').html();
        var description =  $photo.find('li.description').html();
        var ecommerce = $photo.find('li.ecommerce').html();
        var image = $photo.find('li.thumbnail').clone().html();

        $details.empty()
        .css({
                top:    arrPageScroll[1] + (arrPageSizes[3] / 10),
                left:   arrPageScroll[0] + arrPageSizes[2] / 10,
                height:  'auto'
        })
        .append('<div class="header"><span style="float:left";>'+ (parseInt(id)+1) + ' / ' +  totalPhoto +'</span><span style="float:right;"><a href="#" onclick="hl.detailsClose();return false;">Close</a></span></div>')
        .append('<div class="media"><div class="previous" onclick="hl.details_previous('+id+');"><</div><div class="image">Loading.....</div><div class="next" onclick="hl.details_next('+id+');">></div></div>');
        $details.prepend('<div class="loader">Click to enlarge</div>')
        var $loader = $details.find('.loader');

        $details.find('.image').empty().prepend(image);
        $details.show();
        $details.find('.image').find('a').attr('href', '/www/MediaViewer.cgi?ID=' + $details.find('.image').find('a').attr('id')).attr('target', '_blank');
        $details.find('.image').find('img').css({height : photo_original[id].height, width : photo_original[id].width, marginLeft:0 })
        .hover(function() {
                $loader.show().css({left: (photo_original[id].width - $loader.width() ) /2 + 60 , top: ( photo_original[id].height - $loader.height() )/2 + 30 + 35});
            },
            function() {
                $loader.hide();
            });

        $loader.click(function() { window.open('/www/MediaViewer.cgi?ID=' +  $details.find('.image').find('a').attr('id')); return false;  } ).hover(function() {
                    $loader.show().css({left: (photo_original[id].width - $loader.width() ) /2 + 60 , top: ( photo_original[id].height - $loader.height() )/2 + 30 + 35});
                },
                function() {
                });

        $details.append('<div class="extra"></div>');
        
        $details.find('.extra').append(item_title + '<br />');
        if (mi_title) $details.find('.extra').append(mi_title + '<br />');
        if (description) $details.find('.extra').append(description + '<br />');
        if (mi_caption) $details.find('.extra').append('Caption : '+mi_caption+'<br />');
        if (mi_description) $details.find('.extra').append('Description : '+mi_description+'<br />');
        if (ecommerce)  $details.append(ecommerce);
        $details.width( $details.find('img').width() + 120);
        $details.find('.next').css('top', $details.find('img').height() /2 + $details.find('.header').height() + 25);
        $details.find('.previous').css('top', $details.find('img').height() /2 + $details.find('.header').height()+ 25);

        ($(document).width() > $(window).width()) ? width = $(document).width() : width = $(window).width();
        ($(document).height() > $(window).height()) ? height = $(document).height() : height = $(window).height();

        $detailsBorder.width(width).height(height);
    };

    // next photo
    this.details_next = function(id ) {
        id++;
        if (id >= totalPhoto) id = 0;
        this.detailsClose();
        this.details(id);
    };
    // previous photo
    this.details_previous = function( id) {
        id--;
        if (id < 0) id = totalPhoto-1;
        this.detailsClose();
        this.details(id);
    };

    // close the details
    this.detailsClose = function() {
        $('.details').empty().hide();
        $('.detailsBorder').hide();
    }
    
    // Slides //
    this.slides = function() {
        $gallery.css({width: '500px', height: '440px'});
        $(".scrollDiv").append($('<div class="scrollContainer"></div>').append('<div class="scroll"></div>')).show();
        $container.hide();
        $gallery.find('#selector').hide();
        $slides.show();
        $slidesHeader.show();
        $slidesDescription.show();

        var $img = $container.find('li.thumbnail').find('a');
        $img.each(function(i) {
            $(this).unbind();
            $(this).css('cursor', 'pointer').click(function() { hl.update_slide(i);return false });
        });
        $(".scroll").prepend($img);
        $('.scroll').find('img').css({width:50, height:50, marginLeft : 0, marginTop :0});
        $('.scroll').width($img.width() * totalPhoto);
        $gallery.removeClass("gallery").addClass("slideshow");
        this.update_slide(ss_current_photo);
    };

    // slideshow
    this.slides_auto = function(trigger) {
        if (trigger) {
            $('.scroll').find('a').eq(ss_current_photo).css({  opacity: '1.0' });
            $('.auto').html('<a href="#" onclick="hl.slides_auto(0);return false;">Stop</a>');
            ss_current_photo++;
            if (ss_current_photo >= totalPhoto)
                ss_current_photo = 0;
            this.update_slide(ss_current_photo, 1);
    
            var object = this;
            timer = setTimeout(function() {
                object.slides_auto(1); 
            }, 2000);
        }
        else {
            $('.auto').html('<a href="#" onclick="hl.slides_auto(1);return false;">Auto</a>');
            clearTimeout(timer);
            timer=0;
        }
    };

    // next slide
    this.update_slide_next = function() {
        $('.scroll').find("a").eq(ss_current_photo).css({  opacity: '1.0' });
        ss_current_photo++;
        if (ss_current_photo >= totalPhoto) 
            ss_current_photo = 0;
        this.update_slide(ss_current_photo);
    };

    // previous slide
    this.update_slide_previous = function() {
        $('.scroll').find("a").eq(ss_current_photo).css({  opacity: '1.0' });
        ss_current_photo--;
        if (ss_current_photo < 0)
            ss_current_photo = totalPhoto-1;
        this.update_slide(ss_current_photo);
    };

    // update the slide
    this.update_slide = function(current, hasTimer) {
        var $window = $('.window');

        hasTimer = typeof(hasTimer) != 'undefined' ? hasTimer : 0;
        if (!hasTimer) this.slides_auto(0);

        $('.scroll').find('a').eq(ss_current_photo).css({  opacity: '1.0' });
        ss_current_photo = current;
        var height = $gallery.css('height');
        height = height.substring(0,height.length -2);
        var width = $gallery.css('width');
        width = width.substring(0,width.length -2);
        var $img = $('.scroll').find("a").eq(ss_current_photo).clone();
        $('.scroll').find("a").eq(ss_current_photo).css({  opacity: '0.3' });

        $gallery.find('.next').css('top',height/2);
        $gallery.find('.previous').css('top',height/2);

        
        var id = $img.attr('id');
        $img.find('img').css({ width : photo_original[ss_current_photo].width , height : photo_original[ss_current_photo].height  });
        $img.attr('href', '/www/MediaViewer.cgi?ID=' + id);
        $img.attr('target', '_blank');
        $img.removeClass('image').appendTo($('.window').empty());
        $slidesLoader.unbind();

        $slidesLoader.hover(
            function() { $slidesLoader.show(); },
            function() {}
        ).click(function(){ window.open('/www/MediaViewer.cgi?ID=' + id); return false;});

        $('.ss_selector').html(ss_current_photo+1 + ' / ' + totalPhoto);
        var item_title = $container.eq(ss_current_photo).find('li').filter('[class=item_title]').html();
        var mi_title = $container.eq(ss_current_photo).find('li').filter('[class=mi_title]').html();
        var mi_caption = $container.eq(ss_current_photo).find('li').filter('[class=mi_caption]').html();
        var mi_description = $container.eq(ss_current_photo).find('li').filter('[class=mi_description]').html();
        var description = $container.eq(ss_current_photo).find('li').filter('[class=description]').html();
        var ecommerce = $container.eq(ss_current_photo).find('li').filter('[class=ecommerce]').html();
        $('.sstitle').empty();
        if (mi_title) $('.sstitle').append(item_title + '<br />');
        if (description) $('.sstitle').append(description + '<br />');
        
        $('.ssdescription').empty().removeClass('destext');
        if (ecommerce) $('.ssdescription').append(ecommerce);
        if (mi_title) $('.ssdescription').append(mi_title + ' <br />');
        if (mi_caption) $('.ssdescription').append(mi_caption + ' <br />');
        if (mi_description) $('.ssdescription').append(mi_description);
        if ($('.ssdescription').text().length > 0 && !ecommerce) $('.ssdescription').addClass('destext');
        // scroll selected photo to the center;
        $('.scrollContainer').animate({ scrollLeft: ($('.scroll').find('img').width()) * ss_current_photo }, "slow");
        // move the image to centre of the slides
        $('.window').css("top", (height - $window.find("img").height() )/2);
        $('.window').css("left", (width - $window.find("img").width() )/2);

        $window
        .hover (
            function() {
                $slidesLoader.show().css('top', height /2 ).css("left", (width- $slidesLoader.width()) /2);
            },
            function() {
                $slidesLoader.hide();
            }
        );
    };

    /* getPageScroll() by quirksmode.com */
    function getPageScroll() {
        var xScroll, yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
            xScroll = self.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft; 
        }
        arrayPageScroll = new Array(xScroll,yScroll) 
        return arrayPageScroll;
    };
    /* getPageSize() by quirksmode.com */
    function getPageSize() {
        var xScroll, yScroll;
        if (window.innerHeight && window.scrollMaxY) {  
            xScroll = window.innerWidth + window.scrollMaxX;
            yScroll = window.innerHeight + window.scrollMaxY;
        } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
            xScroll = document.body.scrollWidth;
            yScroll = document.body.scrollHeight;
        } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
            xScroll = document.body.offsetWidth;
            yScroll = document.body.offsetHeight;
        }
        var windowWidth, windowHeight;
        if (self.innerHeight) { // all except Explorer
            if(document.documentElement.clientWidth){
                windowWidth = document.documentElement.clientWidth; 
            } else {
                windowWidth = self.innerWidth;
            }
            windowHeight = self.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowWidth = document.documentElement.clientWidth;
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowWidth = document.body.clientWidth;
            windowHeight = document.body.clientHeight;
        }   
        // for small pages with total height less then height of the viewport
        if(yScroll < windowHeight){
            pageHeight = windowHeight;
        } else { 
            pageHeight = yScroll;
        }
        // for small pages with total width less then width of the viewport
        if(xScroll < windowWidth){  
            pageWidth = xScroll;        
        } else {
            pageWidth = windowWidth;
        }
        arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
        return arrayPageSize;
    };
}

