/* ------------------------------------------------------------------------
* 	Class: photoGallery
* 		Use: Lightbox clone for jQuery
* 			Author: Stephane Caron (http://www.no-margin-for-errors.com)
* 				Version: 2.5.5
* 				------------------------------------------------------------------------- */

(function($) {
    $.photoGallery = { version: '2.5.5' };
    var imagesList = new Array();
    var getNextImages = false;
    var getPreviousImages = false;
    var imagesCount, lnkNext, lnkPrevious, SID, template, OwnerId, IsClosed;
    var openNextImage = false;
    /************************************************** constructor    ***********************************************************/
    $.fn.photoGallery = function(settings) {
        settings = jQuery.extend({ animationSpeed: 'normal', opacity: 0.50, allowresize: true,
            default_width: 500, default_height: 344, counter_separator_label: '/',
            theme: 'light_rounded', modal: false,
            changepicturecallback: function() { }, callback: function() { },
            markup: GetLocalizedSlideShowContents(), image_markup: '<img id="fullResImage" src="" />', backUrl: ''
        }, settings);

        if ($.browser.msie && $.browser.version == 6) { settings.theme = "light_square"; }

        if (!$pp_overlay)
            _buildOverlay();

        $('#dialog').dialog({
            autoOpen: false,
            closeOnEscape: true,
            modal: true,
            width: 300,
            buttons: {
                "Ok": function() {
                    var method = GetRemovePhotoMethod();
                    method = method.replace("[ThreadId]", images[setPosition].ThreadId);
                    eval(method);
                    images.splice(setPosition, 1);
                    $.photoGallery.changePage('next');
                    $pp_pic_holder.show();
                    $pp_overlay.show();
                    $(this).dialog("close");
                    return false;
                    $(this).dialog("close");
                    $pp_pic_holder.show();
                    $pp_overlay.show();
                    return true;
                },
                "Cancel": function() {
                    $(this).dialog("close");
                    $pp_pic_holder.show();
                    $pp_overlay.show();
                }
            }
        });

        var doresize = true,
          percentBased = false,
           correctSizes,
            $pp_pic_holder,
             $ppt,
              $pp_overlay,
              pp_contentHeight,
               pp_contentWidth,
                pp_containerHeight,
                 pp_containerWidth,
                  windowHeight = $(window).height(), windowWidth = $(window).width(), setPosition = 0, scrollPos = _getScroll();

        $(window).scroll(function() { scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });

        var version = parseInt($.browser.version, 10);
        if (!($.browser.msie && version == 6)) {
            $(window).resize(function() { _centerOverlay(); _resizeOverlay(); });
        }

        //Handle key down events
        $(document).keydown(function(e) {
            if ($pp_pic_holder.is(':visible'))
                switch (e.keyCode) {
                case 37:
                    $.photoGallery.changePage('previous');
                    break;
                case 39:
                    $.photoGallery.changePage('next');
                    break;
                case 27:
                    if (!settings.modal)
                        $.photoGallery.close();
                    break;
            };
        });

        //Get image list including image path, caption, alt
        GetImages(this);


        $.photoGallery.updateImages = function(images) {
            GetImages(images);
            if (openNextImage) { $.photoGallery.open(); }
        };

        $.photoGallery.GetNextImages = function(getImages, count, lnkNextId, lnkPreviousId, sid, temp, ownerId, isClosed) {
            getNextImages = getImages;
            imagesCount = count;
            lnkNext = lnkNextId;
            lnkPrevious = lnkPreviousId;
            if (sid)
                SID = sid;
            if (temp)
                template = temp;
            if (ownerId)
                OwnerId = ownerId;
            if (isClosed)
                IsClosed = isClosed;
        };

        $.photoGallery.GetPreviousImages = function(getImages) {
            getPreviousImages = getImages;
        };

        function GetImages(images) {
            imagesList = new Array();
            $(images).each(function() {
                var threadId = $(this).find('img').attr('threadid');

                var originalImageUrl = $(this).attr('imgUrl');
                var mediumImageUrl = $(this).find('img').attr('scr');
                var caption = $(this).find('img').attr('caption');
                var canRemove = $(this).find('img').attr('canremove');
                var autherName = $(this).find('img').attr('authername');
                var canReport = $(this).find('img').attr('canreport');

                image = new ImageObject(threadId, originalImageUrl, mediumImageUrl, caption, canRemove, autherName, canReport);
                imagesList.push(image);

                $(this).bind('click', function() {
                    _self = this;
                    theRel = $(this).attr('rel');
                    galleryRegExp = /\[(?:.*)\]/;
                    theGallery = galleryRegExp.exec(theRel);
                    if (theGallery) {
                        $('a[rel*=' + theGallery + ']').each(function(i) {
                            if ($(this)[0] === $(_self)[0])
                                setPosition = i;
                        });
                    }

                    $.photoGallery.open();

                    return false;
                });
            });
        }
        /************************************************** open photo dialog  ***********************************************************/
        $.photoGallery.open = function() {
            openNextImage = false;
            if ($.browser.msie && $.browser.version == 6) {
                $('select').css('visibility', 'hidden');
            };

            images = $.makeArray(imagesList);
            image_set = ($(images).size() > 0) ? true : false;

            if (setPosition >= imagesList.length) {
                openNextImage = true;
                return;
            }

            _checkPosition($(images).size());
            $('.pp_loaderIcon').show();

            $pp_pic_holder.find('.currentTextHolder').text((setPosition + 1) + settings.counter_separator_label + $(images).size());
            if (images[setPosition].Caption) {
                $pp_pic_holder.find('.pp_description').show().html(unescape(images[setPosition].Caption));
            }
            else {
                $pp_pic_holder.find('.pp_description').hide().text('');
            };

            imgPreloader = "";
            imgPreloader = new Image();
            nextImage = new Image();

            if (image_set && setPosition > $(images).size()) nextImage.src = images[setPosition + 1].OriginalImageUrl;
            prevImage = new Image();

            if (image_set && images[setPosition - 1])
                prevImage.src = images[setPosition - 1].ImageUrl;

            $pp_pic_holder.find('#pp_full_res')[0].innerHTML = settings.image_markup;

            $pp_pic_holder.find('#fullResImage').attr('src', images[setPosition].OriginalImageUrl);
            imgPreloader.onload = function() {
                correctSizes = _fitToViewport(imgPreloader.width, imgPreloader.height);
                _showContent();
            };
            imgPreloader.onerror = function() {
                correctSizes = _fitToViewport(300, 300);
                _showContent();
            };

            imgPreloader.src = images[setPosition].OriginalImageUrl;

            if (images[setPosition].CanRemove == "false") {
                $pp_pic_holder.find('#remove_link').hide();
            }
            else {
                $pp_pic_holder.find('#remove_link').show();
                $pp_pic_holder.find('#remove_link').bind('click', function() {
                    $.photoGallery.remove();
                    return false;
                });
            }

            if (images[setPosition].CanReport == "false") {
                $pp_pic_holder.find('#report_link').hide();
            }
            else {
                $pp_pic_holder.find('#report_link').show();
                $pp_pic_holder.find('#report_link').bind('click', function() {
                    var backUrl = settings.backUrl;
                    if (backUrl == null || backUrl == '') {
                        backUrl = window.location;
                    }
                    var url = "/ReportPost.aspx?content_type_id=17&content_id=" + images[setPosition].ThreadId + "&thread_title=&author_name=" + images[setPosition].AutherName + "&back_url=" + escape(backUrl);
                    window.location = url;
                    return false;
                });                
            }

            if (!imgPreloader) {
                $pp_pic_holder.find('#pp_full_res')[0].innerHTML = toInject;
                _showContent();
            };
        };

        /********************************** change photo function (will be used with next/previous methods) *********************************/
        $.photoGallery.changePage = function(direction) {
            if (direction == 'previous') {
                setPosition--;
                if (setPosition < 0) {
                    setPosition = 0;
                    return;
                };
            }
            else {
                if ($('.pp_arrow_next').is('.disabled') || (setPosition >= $("#" + GetImagesContainerID() + " td").length - 1 && !getNextImages))
                    return;
                setPosition++;
            };

            _GetImages(direction, setPosition);

            if (!doresize)
                doresize = true;

            _hideContent(function() {
                $.photoGallery.open()
            });
        };

        /**************************************************** Delete Image ********************************************************/
        $.photoGallery.remove = function() {
            $pp_pic_holder.hide();
            $pp_overlay.hide();
            $('#dialog').dialog('open');
        };

        /************************************************** close photo dialog *****************************************************/
        $.photoGallery.close = function() {
            $pp_pic_holder.find('object,embed').css('visibility', 'hidden');
            $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animationSpeed);
            $pp_overlay.fadeOut(settings.animationSpeed,
           function() {
               $pp_pic_holder.attr('style', '').find('div:not(.pp_hoverContainer)').attr('style', '');
               _centerOverlay();

               if ($.browser.msie && $.browser.version == 6) {
                   $('select').css('visibility', 'visible');
               };

               setPosition = 0; settings.callback();
           });

            doresize = true;
        };

        /************************************************** bind image details function  *************************************************/
        _showContent = function() {
            $('.pp_loaderIcon').hide();
            projectedTop = scrollPos['scrollTop'] + ((windowHeight - correctSizes['containerHeight']) / 4);
            if (projectedTop < 0)
                projectedTop = 0 + $ppt.height();

            $pp_pic_holder.find('.pp_content').animate({ 'height': correctSizes['contentHeight'] }, settings.animationSpeed);
            $pp_pic_holder.animate({ 'top': projectedTop, 'left': (windowWidth / 2) - (correctSizes['containerWidth'] / 2), 'width': correctSizes['containerWidth'] },
                          settings.animationSpeed, function() {
                              $pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']); $pp_pic_holder.find('.pp_fade').fadeIn(settings.animationSpeed);

                              if (image_set) {
                                  $pp_pic_holder.find('.pp_hoverContainer').show();
                              }
                              else {
                                  $pp_pic_holder.find('.pp_hoverContainer').hide();
                              }
                          });
            $pp_overlay.show().fadeTo(settings.animationSpeed, settings.opacity);
        };

        /************************************************ hide image content function  *****************************************************/
        function _hideContent(callback) {
            $pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility', 'hidden');
            $pp_pic_holder.find('.pp_fade').fadeOut(settings.animationSpeed,
        function() {
            $('.pp_loaderIcon').show();
            if (callback) callback();
        });
            $ppt.fadeOut(settings.animationSpeed);
        }

        function _checkPosition(setCount) {
            if (setPosition == setCount - 1 && !getNextImages) {
                $pp_pic_holder.find('a.pp_next').css('visibility', 'hidden');
                $pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
            }
            else {
                $pp_pic_holder.find('a.pp_next').css('visibility', 'visible');
                $pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',
           function() {
               $.photoGallery.changePage('next');
               return false;
           });
            };

            if (setPosition == 0) {
                $pp_pic_holder.find('a.pp_previous').css('visibility', 'hidden');
                $pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
            }
            else {
                if (!getPreviousImages) {
                    $pp_pic_holder.find('a.pp_previous').css('visibility', 'visible');
                    $pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',
                  function() {
                      $.photoGallery.changePage('previous');
                      return false;
                  });
                };
            }
        };

        function _fitToViewport(width, height) {
            hasBeenResized = false;
            _getDimensions(width, height);
            imageWidth = width;
            imageHeight = height;
            if (((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
                hasBeenResized = true;
                notFitting = true;

                while (notFitting) {
                    if ((pp_containerWidth > windowWidth)) {
                        imageWidth = (windowWidth - 200);
                        imageHeight = (height / width) * imageWidth;
                    }
                    else if ((pp_containerHeight > windowHeight)) {
                        imageHeight = (windowHeight - 200);
                        imageWidth = (width / height) * imageHeight;
                    }
                    else {
                        notFitting = false;
                    };
                    pp_containerHeight = imageHeight; pp_containerWidth = imageWidth;
                };
                _getDimensions(imageWidth, imageHeight);
            };
            return { width: Math.floor(imageWidth),
                height: Math.floor(imageHeight) < Math.floor(((windowHeight * 65) / 100) - 50) ? Math.floor(imageHeight) : Math.floor(((windowHeight * 65) / 100) - 50),
                containerHeight: Math.floor(pp_containerHeight) < Math.floor((windowHeight * 70) / 100) ? Math.floor(pp_containerHeight) : Math.floor((windowHeight * 70) / 100),
                containerWidth: Math.floor(pp_containerWidth) + 40,
                contentHeight: Math.floor(pp_contentHeight) < Math.floor((windowHeight * 65) / 100) ? Math.floor(pp_contentHeight) : Math.floor((windowHeight * 65) / 100),
                contentWidth: Math.floor(pp_contentWidth),
                resized: hasBeenResized
            };
        };

        function _getDimensions(width, height) {

            width = parseFloat(width);
            height = parseFloat(height);
            $pp_details = $pp_pic_holder.find('.pp_details');
            detailsHeight = parseFloat($pp_details.css('marginTop')) + parseFloat($pp_details.css('marginBottom'));
            $pp_details = $pp_details.clone().appendTo($('body')).css({ 'position': 'absolute', 'top': -10000 });
            detailsHeight += $pp_details.height();
            detailsHeight = (detailsHeight <= 34) ? 36 : detailsHeight;
            if ($.browser.msie && $.browser.version == 7)
                detailsHeight += 8;

            $pp_details.remove();
            pp_contentHeight = height + detailsHeight;
            pp_contentWidth = width;
            $pp_details.width(pp_contentWidth);
            pp_containerHeight = pp_contentHeight + $ppt.height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
            pp_containerWidth = width;
            pp_containerWidth = pp_containerWidth < 300 ? 300 : pp_containerWidth;
        }

        function _centerOverlay() {
            if (doresize) {
                titleHeight = $ppt.height();
                contentHeight = $pp_pic_holder.height();
                contentwidth = $pp_pic_holder.width();
                projectedTop = (windowHeight / 2) + scrollPos['scrollTop'] - ((contentHeight + titleHeight) / 2);
                $pp_pic_holder.css({ 'top': projectedTop, 'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2) });
                $ppt.css({ 'top': projectedTop - titleHeight, 'left': (windowWidth / 2) + scrollPos['scrollLeft'] - (contentwidth / 2) + 20 });
            };
        };

        function _getScroll() {
            if (self.pageYOffset) {
                return { scrollTop: self.pageYOffset, scrollLeft: self.pageXOffset };
            }
            else if (document.documentElement && document.documentElement.scrollTop) {
                return { scrollTop: document.documentElement.scrollTop, scrollLeft: document.documentElement.scrollLeft
                };
            }
            else if (document.body) {
                return { scrollTop: document.body.scrollTop, scrollLeft: document.body.scrollLeft };
            };
        };

        function _resizeOverlay() {
            windowHeight = $(window).height();
            windowWidth = $(window).width();
            $pp_overlay.css({ 'height': $(document).height() });
        };

        function _buildOverlay() {
            $('body').append(settings.markup);
            $pp_pic_holder = $('.pp_pic_holder');
            $ppt = $('.ppt');
            $pp_overlay = $('div.pp_overlay');
            $pp_pic_holder.attr('class', 'pp_pic_holder ' + settings.theme);
            $pp_overlay.css({ 'opacity': 0, 'height': $(document).height() }).bind('click', function() {
                if (!settings.modal)
                    $.photoGallery.close();
            });

            $('a.pp_close').bind('click', function() {
                $.photoGallery.close();
                return false;
            });

            $pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click', function() {
                $.photoGallery.changePage('previous');
                return false;
            });

            $pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click', function() {
                $.photoGallery.changePage('next');
                return false;
            });
        };

        _centerOverlay();
    };

    function grab_param(name, url) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(url);
        if (results == null)
            return "";
        else
            return results[1];
    }


    function _GetImages(direction, position) {
        var startIndex = $.inArray($("#" + GetImagesContainerID() + " td:visible:first")[0], $("#" + GetImagesContainerID() + " td"));
        var endIndex = $.inArray($("#" + GetImagesContainerID() + " td:visible:last")[0], $("#" + GetImagesContainerID() + " td"));
        if (direction == 'previous') {
            if (getPreviousImages) {
                if (startIndex == position + 1 && startIndex != 0) {
                    GetPreviousImages(imagesCount, lnkPrevious, lnkNext);
                }
            }
        }
        else {
            if (getNextImages) {
                if (endIndex == position - 1) {
                    {
                        GetAlbumPhotos(SID, imagesCount, lnkPrevious, lnkNext, template, OwnerId, IsClosed);
                    }
                }
            }
        }
    }

})(jQuery);

function GetLocalizedSlideShowContents() {
    var rawContent = slideshow_html;
    for (var parameter in PhotoSlideShow_LocResources) {
        var replacementParameter = "[{" + parameter + "}]";
        rawContent = rawContent.replace(replacementParameter, PhotoSlideShow_LocResources[parameter]);
    }
    return rawContent;
}

var slideshow_html = '<div class="pp_pic_holder"> \
      <div class="pp_content_container"> \
      <div class="pp_top"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"></div> \
       <div class="pp_right"> <a class="pp_close" href="#"></a></div> \
      </div> \
        <div class="pp_content"> \
         <div class="pp_fade"> \
          <div class="pp_loaderIcon"></div> \
          <div id="pp_full_res"></div> \
		  <div class="navlinks"> \
		  <div class="pp_prevlink"><a class="pp_previous" href="#">previous</a></div> \
		 <div class="pp_nextlink"><a class="pp_next" href="#">next</a></div> \
		  </div> \
         </div> \
       </div> \
      </div> \
	  <div class="pp_details clearfix"> \
           <p class="pp_description wordWrap"></p> \
      </div> \
      <div class="pp_bottom"> \
       <div class="pp_left"></div> \
       <div class="pp_middle"> \
	    <div class="pp_remove"><a id="remove_link" href="#">[{Remove_Photo}]</a></div> \
		 <div class="pp_report"><a id="report_link" href="#">[{Report_This_Image}]</a></div> \
	   </div> \
       <div class="pp_right"></div> \
      </div> \
     </div> \
     <div class="pp_overlay"></div> \
     <div class="ppt"></div>';
