/*
 * FancyBox - jQuery Plugin
 * Simple and fancy lightbox alternative
 *
 * Examples and documentation at: http://fancybox.net
 *
 * Copyright (c) 2008 - 2010 Janis Skarnelis
 * That said, it is hardly a one-person project. Many people have submitted bugs, code, and offered their advice freely. Their support is greatly appreciated.
 *
 * Version: 1.3.4 (11/11/2010)
 * Requires: jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

;(function($) {



var tmp, loading, overlay, wrap, outer, content, close, nav_left, nav_right,

        selectedIndex = 0, selectedOpts = {}, selectedArray = [], currentIndex = 0, currentOpts = {}, currentArray = [],

        ajaxLoader = null, imgPreloader = new Image(), imgRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i, swfRegExp = /[^\.]\.(swf)\s*$/i,

        loadingTimer, loadingFrame = 1,

         start_pos, final_pos, busy = false, fx = $.extend($('<div/>')[0], {prop: 0}),

        isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,

        /*
         * Private methods
         */


        /**
         * Abort loading of detail, of is clicekd another photo
         */
        _abort = function() {
                loading.hide();

                imgPreloader.onerror = imgPreloader.onload = null;

                if (ajaxLoader) {
                        ajaxLoader.abort();
                }

                tmp.empty();
        },

        _error = function() {
                if (false === selectedOpts.onError(selectedArray, selectedIndex, selectedOpts)) {
                        loading.hide();
                        busy = false;
                        return;
                }

                selectedOpts.width = 'auto';
                selectedOpts.height = 'auto';

                tmp.html( '<p id="gallerybox-error">The requested content cannot be loaded.<br />Please try again later.</p>' );

        },

        _start = function() {

            var selectedObject = $(selectedArray[selectedIndex]);
            var offset = selectedObject.offset();
            offset = offset.top + selectedObject.height();
            offset = offset - Math.floor($(window).height()/2);
            if (offset > 0) {
                if( $.browser.opera){
                    $('html').animate({
                            scrollTop: offset
                    }, 0);
                } else {
                    $('html,body').animate({
                            scrollTop: offset
                    }, 0);
                }
            }

            var obj = selectedArray[ selectedIndex ],
                    href,
                    type,
                    title,
                    str,
                    emb,
                    ret;

            _abort();

            selectedOpts = $.extend({}, $.fn.gallerybox.defaults, (typeof $(obj).data('gallerybox') == 'undefined' ? selectedOpts : $(obj).data('gallerybox')));

            ret = selectedOpts.onStart(selectedArray, selectedIndex, selectedOpts);

            if (ret === false) {
                    busy = false;
                    return;
            } else if (typeof ret == 'object') {
                    selectedOpts = $.extend(selectedOpts, ret);
            }


            if (obj.nodeName && !selectedOpts.orig) {
                    selectedOpts.orig = $(obj).children("img:first").length ? $(obj).children("img:first") : $(obj);
            }

            href = selectedOpts.href || (obj.nodeName ? $(obj).attr('href') : obj.href) || null;

            if ((/^(?:javascript)/i).test(href) || href == '#') {
                    href = null;
            }

            selectedOpts.href = href;

            $('.gallerybox-inline-tmp').unbind('gallerybox-cancel').bind('gallerybox-change', function() {
                    $(this).replaceWith(content.children());
            });

            busy = false;

            $.gallerybox.showActivity();

            selectedOpts.ajax.win = selectedOpts.ajax.success;

            href = href.replace('/run/albums/photo/detail/', '/ajax/public-photo/index/detail/');
            href = href.replace('/run/sale-items/detail/', '/ajax/sale-items/detail/');

            ajaxLoader = $.ajax($.extend({}, selectedOpts.ajax, {
                url  : href,
                data : selectedOpts.ajax.data,
                error : function(XMLHttpRequest, textStatus, errorThrown) {
                        if ( XMLHttpRequest.status > 0 ) {
                                _error();
                        }
                },
                success : function(data, textStatus, XMLHttpRequest) {
                    var o = typeof XMLHttpRequest == 'object' ? XMLHttpRequest : ajaxLoader;
                    if (o.status == 200) {
                        if ( typeof selectedOpts.ajax.win == 'function' ) {
                            ret = selectedOpts.ajax.win(href, data, textStatus, XMLHttpRequest);

                            if (ret === false) {
                                    loading.hide();
                                    return;
                            } else if (typeof ret == 'string' || typeof ret == 'object') {
                                    data = ret;
                            }
                        }
                        data = eval('(' + data + ')');

                        tmp.html( data.content );
                        tmp.append(nav_left,nav_right);
                        fotoInfo.html(data.footer);
                        _show();
                    }
                }
            }));
        },

    _show = function() {

        Nameee.comments.init();
        loading.hide();

        if (wrap.is(":visible") && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
            $.event.trigger('gallerybox-cancel');

            busy = false;
            return;
        }

        busy = true;

        $(content.add( overlay )).unbind();

        $(window).unbind("resize.fb scroll.fb");
        $(document).unbind('keydown.fb');

        currentArray = selectedArray;
        currentIndex = selectedIndex;
        currentOpts = selectedOpts;

        if (currentOpts.overlayShow) {
            overlay.css({
                    'background-color' : currentOpts.overlayColor,
                    'opacity' : currentOpts.overlayOpacity,
                    'cursor' : currentOpts.hideOnOverlayClick ? 'pointer' : 'auto',
                    'height' : $(document).height()
            });

            if (!overlay.is(':visible')) {
                    if (isIE6) {
                            $('select:not(#gallerybox-tmp select)').filter(function() {
                                    return this.style.visibility !== 'hidden';
                            }).css({'visibility' : 'hidden'}).one('gallerybox-cleanup', function() {
                                    this.style.visibility = 'inherit';
                            });
                    }

                    overlay.show();
            }
        } else {
            overlay.hide();
        }

        if (wrap.is(":visible")) {
            $( close.add( nav_left ).add( nav_right ) ).hide();

            $.event.trigger('gallerybox-change');

            content
                    .empty()
                    .removeAttr('filter');

            content.html( tmp.contents() );
            _finish();
            return;
        }

        wrap.removeAttr("style");
            content.html( tmp.contents() );


            if (currentOpts.opacity) {
                    final_pos.opacity = 0;
            }

            fx.prop = 0;

            _finish();

            return;
    },

    _set_navigation = function() {
        if (currentOpts.enableEscapeButton || currentOpts.enableKeyboardNav) {
            $(document).bind('keydown.fb', function(e) {
                if (e.keyCode == 27 && currentOpts.enableEscapeButton) {
                    e.preventDefault();
                    $.gallerybox.close();

                } else if ((e.keyCode == 37 || e.keyCode == 39) && currentOpts.enableKeyboardNav && e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'SELECT') {
                    e.preventDefault();
                    $.gallerybox[ e.keyCode == 37 ? 'prev' : 'next']();
                }
            });
        }

        if (!currentOpts.showNavArrows) {
            nav_left.hide();
            nav_right.hide();
            return;
        }

        if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex !== 0) {
            nav_left.show();
        }

        if ((currentOpts.cyclic && currentArray.length > 1) || currentIndex != (currentArray.length -1)) {
            nav_right.show();
        }
    },

    _finish = function () {
        if (!$.support.opacity) {
            content.get(0).style.removeAttribute('filter');
            wrap.get(0).style.removeAttribute('filter');
        }

        if (currentOpts.showCloseButton) {
            close.show();
        }

        _set_navigation();

        if (currentOpts.hideOnContentClick)	{
            content.bind('click', $.gallerybox.close);
        }

        if (currentOpts.hideOnOverlayClick)	{
            overlay.bind('click', $.gallerybox.close);
            wrap.bind('click', $.gallerybox.close);
            photo_box_wrap.bind('click', function(e){
                e.stopPropagation();
            });
        }

        $(window).bind("resize.fb", $.gallerybox.resize);

        if (currentOpts.centerOnScroll) {
            $(window).bind("scroll.fb", $.gallerybox.center);
        }
        $('body').css('overflow','hidden');
        wrap.show();

        busy = false;

        $.gallerybox.center();

        currentOpts.onComplete(currentArray, currentIndex, currentOpts);

        _preload_images();
    },

    _preload_images = function() {

        if (selectedIndex > selectedArray.length -6) {
            $('.link-next').click();
        }
        var href,
                objNext;

        if ((currentArray.length -1) > currentIndex) {
            href = $(currentArray[ currentIndex + 1 ]).find('img').attr('src');

            if (typeof href !== 'undefined') {
                href = href.replace('album-list','album');
            }

            if (typeof href !== 'undefined' && href.match(imgRegExp)) {
                objNext = new Image();
                objNext.src = href;
            }
        }
    },

    _get_viewport = function() {
        return [
            $(window).width(),
            $(window).height(),
            $(document).scrollLeft(),
            $(document).scrollTop()
        ];
    },

    _animate_loading = function() {
        if (!loading.is(':visible')){
            clearInterval(loadingTimer);
            return;
        }

        $('div', loading).css('top', (loadingFrame * -40) + 'px');

        loadingFrame = (loadingFrame + 1) % 12;
    },

    _reinit = function(collection, options)
    {

        selectedArray = $(collection);
        currentArray = $(collection);

        $(collection).data('gallerybox', $.extend({}, options, ($.metadata ? $(this).metadata() : {})))
            .unbind('click.fb')
            .attr("rel", "gallery")
            .bind('click.fb', function(e) {
                e.preventDefault();
                if (busy) {
                        return;
                }

                busy = true;

                $(this).blur();

                selectedArray = [];
                selectedIndex = 0;

                var rel = $(this).attr('rel') || '';

                if (!rel || rel == '' || rel === 'nofollow') {
                        selectedArray.push(this);

                } else {
                        selectedArray = $("a[rel=" + rel + "], area[rel=" + rel + "]");
                        selectedIndex = selectedArray.index( this );
                }

                nav_left.click(function(e) {
                    e.preventDefault();
                    $.gallerybox.prev();
                });

                nav_right.click(function(e) {
                    e.preventDefault();
                    $.gallerybox.next();
                });

                _start();

                return;
            });
    };

/*
 * Public methods
 */

/**
 * First line init
 *
 **/
$.fn.gallerybox = function(options) {

    $(this).bind("afterDOMChanged", function() {
        _reinit($(this).find(options.children), options);
        if ($(outer).is(':visible')) {
            nav_right.show();
        }
    });

    if ($(this).find(options.children).length < 1) {  // tohle jde prvni
        return this;
    }

    _reinit($(this).find(options.children), options);

    return this;
};

$.gallerybox = function(obj)
{

}

//$.gallerybox = function(obj) {
//    var opts;
//
//    if (busy) {
//        return;
//    }
//
//    busy = true;
//    opts = typeof arguments[1] !== 'undefined' ? arguments[1] : {};
//
//    selectedArray = [];
//    selectedIndex = parseInt(opts.index, 10) || 0;
//
//    if ($.isArray(obj)) {
//        for (var i = 0, j = obj.length; i < j; i++) {
//            if (typeof obj[i] == 'object') {
//                $(obj[i]).data('gallerybox', $.extend({}, opts, obj[i]));
//            } else {
//                obj[i] = $({}).data('gallerybox', $.extend({content : obj[i]}, opts));
//            }
//        }
//
//        selectedArray = jQuery.merge(selectedArray, obj);
//
//    } else {
//        if (typeof obj == 'object') {
//            $(obj).data('gallerybox', $.extend({}, opts, obj));
//        } else {
//            obj = $({}).data('gallerybox', $.extend({content : obj}, opts));
//        }
//
//        selectedArray.push(obj);
//    }
//
//    if (selectedIndex > selectedArray.length || selectedIndex < 0) {
//        selectedIndex = 0;
//    }
//
//    _start();
//};

$.gallerybox.showActivity = function() {
    clearInterval(loadingTimer);

    loading.show();
    loadingTimer = setInterval(_animate_loading, 66);
};

$.gallerybox.hideActivity = function() {
    loading.hide();
};

$.gallerybox.next = function() {
    return $.gallerybox.pos( currentIndex + 1);
};

$.gallerybox.prev = function() {
    return $.gallerybox.pos( currentIndex - 1);
};

$.gallerybox.pos = function(pos) {
    if (busy) {
        return;
    }

    pos = parseInt(pos);

    selectedArray = currentArray;

    if (pos > -1 && pos < currentArray.length) {
        selectedIndex = pos;
        _start();

    } else if (currentOpts.cyclic && currentArray.length > 1) {
        selectedIndex = pos >= currentArray.length ? 0 : currentArray.length - 1;
        _start();
    }

    return;
};

$.gallerybox.cancel = function() {
    if (busy) {
        return;
    }

    busy = true;

    $.event.trigger('gallerybox-cancel');

    _abort();

    selectedOpts.onCancel(selectedArray, selectedIndex, selectedOpts);

    busy = false;
};

$.gallerybox.close = function() {
    if (busy || wrap.is(':hidden')) {
        return;
    }

    busy = true;

    if (currentOpts && false === currentOpts.onCleanup(currentArray, currentIndex, currentOpts)) {
        busy = false;
        return;
    }

    _abort();

    $(close.add( nav_left ).add( nav_right )).hide();

    $(content.add( overlay )).unbind();

    $(window).unbind("resize.fb scroll.fb");
    $(document).unbind('keydown.fb');

    content.find('iframe').attr('src', isIE6 && /^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank');

    wrap.stop();

    function _cleanup() {

        overlay.fadeOut('fast');
        $('body').css('overflow','scroll');
        wrap.hide();

        $.event.trigger('gallerybox-cleanup');

        content.empty();

        currentOpts.onClosed(currentArray, currentIndex, currentOpts);

        currentArray = selectedOpts	= [];
        currentIndex = selectedIndex = 0;
        currentOpts = selectedOpts	= {};

        busy = false;
    }
    wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 :0, _cleanup);

};


$.gallerybox.resize = function() {
    if (overlay.is(':visible')) {
        overlay.css('height', $(document).height());
    }

    $.gallerybox.center(true);
};

/**
 * Position gallery box window on center horizontaly and 5 pixels from top
 */
$.gallerybox.center = function() {
    var view, align;

    if (busy) {
        return;
    }

    align = arguments[0] === true ? 1 : 0;
    view = _get_viewport();

    if (!align && (wrap.width() > view[0] || wrap.height() > view[1])) {
        return;
    }

    photo_box_wrap
    .css({
        'top' : 5,
        'left' : parseInt(Math.max(view[2] +5+480, view[2] + ((view[0] - content.width()) * 0.5+480)))
    });
};

/**
 * Creates Html structires and bind events handlers
 */
$.gallerybox.init = function() {
        if ($("#gallerybox-wrap").length) {
                return;
        }

        $('body').append(
                tmp	= $('<div id="gallerybox-tmp"></div>'),
                overlay	= $('<div id="gallerybox-overlay"></div>'),
                wrap = $('<div id="NMPhotoBoxWrap"></div>')
                //wrap = $('<div id="NMPhotoBox"></div>')

        );
        photo_box_wrap = $('<div id="NMPhotoBox"></div>')
            .appendTo( wrap );

        photo_box_wrap.append(loading	= $('<div id="gallerybox-loading"><div></div></div>'));

        insideblock = $('<div id="container"></div>')
            .appendTo( photo_box_wrap );
        //    .appendTo( wrap );


        outer = $('<div id="photo-wrapper"></div>')
            .appendTo( insideblock );

        insideblock.append(fotoInfo = $('<div id="photo-info-wrapper"></div>'));

        var closeText = lm('Close');

        outer.append(
                content = $('<div class="photo"></div>'),
                close = $('<a class="close">'+ closeText +'</a>')
        );

        nav_left = $('<div href="javascript:;" id="gallerybox-left"><span class="fancy-ico" id="gallerybox-left-ico"></span></div>');
        nav_right = $('<div href="javascript:;" id="gallerybox-right"><span class="fancy-ico" id="gallerybox-right-ico"></span></div>');

        close.click($.gallerybox.close);
        loading.click($.gallerybox.cancel);

        if ($.fn.mousewheel) {
                wrap.bind('mousewheel.fb', function(e, delta) {
                        if (busy) {
                                e.preventDefault();

                        } else if ($(e.target).get(0).clientHeight == 0 || $(e.target).get(0).scrollHeight === $(e.target).get(0).clientHeight) {
                                e.preventDefault();
                                $.gallerybox[ delta > 0 ? 'prev' : 'next']();
                        }
                });
        }

        if (!$.support.opacity) {
                wrap.addClass('gallerybox-ie');
        }

        if (isIE6) {
                loading.addClass('gallerybox-ie6');
                wrap.addClass('gallerybox-ie6');

                $('<iframe id="gallerybox-hide-sel-frame" src="' + (/^https/i.test(window.location.href || '') ? 'javascript:void(false)' : 'about:blank' ) + '" scrolling="no" border="0" frameborder="0" tabindex="-1"></iframe>').prependTo(outer);
        }
};



$.fn.gallerybox.defaults = {
        bazaar : false,
        children : 'a',//Conteiner children selector which filtering elemnts for gallery box show.
        opacity : false,
        cyclic : true,

        width : 560,
        height : 340,

        centerOnScroll : false,

        ajax : {},
        hideOnOverlayClick : true,
        hideOnContentClick : false,

        overlayShow : true,
        overlayOpacity : 0.7,
        overlayColor : '#777',

        showCloseButton	 : true,
        showNavArrows : true,
        enableEscapeButton : true,
        enableKeyboardNav : true,

        onStart : function(){},
        onCancel : function(){},
        onComplete : function(){},
        onCleanup : function(){},
        onClosed : function(){},
        onError : function(){}
};

$(document).ready(function() {
        $.gallerybox.init();
});

})(jQuery);
