/// <reference path="jquery-1.3.1.js" />

(function($) {
    $.fn.DaGallery = function(options) {

        var settings = $.extend({}, $.fn.DaGallery.defaults, options);
        var globals = $.fn.DaGallery.globals;
        var ui = {};
        var $thumbList;
        var $galleryBox = $(this);
        var $thumbList; //= jQuery('<div class="thumbList"></div>');


        if (settings.type == 'ajax') {
            //var $galleryBox = $(this);
            $galleryBox.css('width', settings.galleryWidth);

            $thumbList = jQuery('<div class="thumbList"></div>');
            var $ul = jQuery('<ul style="overflow:hidden; display:none"></ul>');
            var $imgLoader = jQuery('<div class="loaderOverlay"><img src="ajax-loader.gif" class="loaderImg" style="display:none"/></div>');
            var $moreLink = jQuery('<div class="DGmoreLink">pokaż całą galerię</div>');

            $thumbList.append($imgLoader).append($ul);
            if (settings.fotoCount > 0) {
                $galleryBox.append($moreLink);
                $($moreLink, $galleryBox).one('click', function() {
                    jQuery(this).remove();
                    settings.fotoCount = 0;
                    $galleryBox.find('ul').empty();
                    LoadThumbnails($thumbList);
                });
            }
            LoadThumbnails($thumbList);
            $galleryBox.append($thumbList);
        }
        else if (settings.type == 'fromlist') {
            $thumbList = $galleryBox.find('.thumbList');
            PrepareGallery();
        }
        else if (settings.type == 'fromthumb') {
            var id = $galleryBox.parent().parent().find('a').index($galleryBox);
            $galleryBox.attr('id', id);
            $thumbList = jQuery('<div class="thumbList" style="display:none"></div>');
            var $ul = jQuery('<ul style="overflow:hidden; display:none"></ul>');
            var galleryUrl = $galleryBox.attr('href');
            galleryUrl = galleryUrl.substring(galleryUrl.lastIndexOf("?") + 1);

            var parms = galleryUrl.split("&");
            var qsParm = new Array();

            for (var i = 0; i < parms.length; i++) {
                var pos = parms[i].indexOf('=');
                if (pos > 0) {
                    var key = parms[i].substring(0, pos);
                    var val = parms[i].substring(pos + 1);
                    qsParm[key] = val;
                }
            }

            globals.galeryId = qsParm['gl'];
            galleryUrl = "/_controls/xml/getxml.aspx?link=" + settings.galleryUrl + qsParm['gr'] + '/' + qsParm['gl'] + '/gallery_500.xml';
            settings.galleryUrl = settings.galleryUrl + qsParm['gr'] + '/' + qsParm['gl'] + '/';
            settings.ajaxUrl = galleryUrl;

            $thumbList.append($ul);
            jQuery('body').append($thumbList);
            LoadThumbnails($thumbList);
        }


        function LoadThumbnails($this) {
            var $gallery = $this;
            var $ul = $gallery.find('ul');
            var $imgLoader = $gallery.find('img');

            //alert($.fn.DaGallery.globals.pageIndex);
            var qsData = {};
            qsData.thumbSize = settings.thumbSize
            if (settings.fotoCount > 0) qsData.count = settings.fotoCount;

            $imgLoader.show();
            jQuery.ajax({
                type: "GET",
                url: settings.ajaxUrl,
                async: false,
                data: qsData,
                dataType: "xml",
                success: function(xml) {
                    var url = settings.galleryUrl;
                    jQuery("photo", xml).each(function(index) {
                        if (settings.fotoCount == 0 || index < settings.fotoCount) {
                            var $this = jQuery(this);
                            var thumb = $this.attr('id') + "_100.jpg";
                            var title = $this.find('title').text();
                            var desc = $this.find('desc').text();
                            var author = $this.find('author').text();
                            var filename = $this.find('filename').text();
                            var $li = jQuery('<li></li>');
                            var $a = jQuery('<a></a>');

                            $a.attr('href', url + filename);
                            $a.html('<img src="' + url + thumb + '" title="' + title + '" alt="' + title + '"/>')
                            $a.append('<div class="desc" style="display:none">' + desc + '</div>');
                            $a.append('<div class="author" style="display:none">' + author + '</div>');
                            $li.append($a);
                            $ul.append($li);
                        }
                    });
                },
                error: function() {
                    debug("ajax error", this.msg);
                },
                complete: function() {
                    $imgLoader.hide();
                    var imagesCount = $ul.find('li').size();
                    var counter = 0;
                    $gallery.find('img').load(function() {
                        counter++;
                        if (counter == imagesCount) {
                            $ul.show();
                            if (settings.type == 'ajax') {
                                var ulHeight = $ul.height();
                                $gallery.animate({ height: ulHeight + "px" }, 300);
                            }
                            PrepareGallery();
                            if (settings.type == 'fromthumb') {
                                $thumbList.find('a:first').triggerHandler('click');
                            }
                        }
                    });
                }
            });
        } //end loadThumbnails()

        function PrepareGallery() {
            //debug('#', 'PrepareGallery()');
            if (typeof ui.$overlay == 'undefined') {
                BuildOverlay();
            }
            $thumbList.find('a').bind('click', StartGallery);
            // debug("id kontenera: " + $galleryBox.attr('id'), "# ile obrazków: " + $thumbList.find('a').size());
        }

        function StartGallery() {
            var $this = jQuery(this);
            // debug($galleryBox.attr('id'), 'StartGallery() -> otworzyłem galerie');

            jQuery("html").addClass('overflow');
            showOverlay();
            debug(globals.photoIndex, '# index(foto)')



            BuildPager();

            var $thisThumb = ui.$list.find('a').eq($thumbList.find('a').index($this)); //szukam miniatury na pagerze odpowiadającej miniaturze na liście miniatur            
            SetThisPhotoIndex($thisThumb);
            SetThisThumbActive($thisThumb);
            SetCurrentPage();
            GoToCurrentPage();
            ShowPhoto($this);


            if ($.browser.mozilla) {
                $(document).bind('keypress', bindKeyActions);
            } else {
                $(document).bind('keydown', bindKeyActions);
            }



            jQuery(window).resize(function() {
                CalculateDimensions();
                SetUiViewTopMargin(globals.viewTopMargin);
                SetContainersDimension();
                SetCurrentPage();
                GoToCurrentPage();
            });

            return false;
        }


        function bindKeyActions(e) {
            var code = e.keyCode;
            //alert(e.which + " " + code);
            switch (code) {
                case 39: //arrow right
                    NextImage();
                    break;
                case 37: //arrow left
                    PreviousImage();
                    break;
                case 34: //page down
                    NextPage();
                    break;
                case 33: //page up
                    PreviousPage();
                    break;
                case 27: //esc
                    hideOverlay();
                    break;
            }
            return false;

        }

        function showOverlay() {
            //debug($galleryBox.attr('id'), 'showOverlay() -> pokazuje layer z galerią');
            ui.$overlay.show();
            jQuery('embed, object').hide(); //chowam flashe, żeby nie prześwitywały
        }

        function BuildPager() {
            var $pagerThumbsList = $thumbList;
            ui.$list.html(jQuery('li', $pagerThumbsList).clone());

            globals.photoCount = ui.$list.find('a').size();
            CalculateDimensions();

            ui.$list.find('a').unbind('click').bind('click', function(e) {
                var $this = jQuery(this);
                ShowPhoto($this);
                SetThisPhotoIndex($this);
                SetThisThumbActive($this);
                return false;
            });

            SetContainersDimension();

            ui.$listPrev.bind('click', PreviousPage)
            ui.$listNext.bind('click', NextPage)
            ui.$naviNext.bind('click', NextImage);
            ui.$naviPrev.bind('click', PreviousImage);

            //alert(globals.pages + " " + (ui.$list.find('li').size() * 85));
        }



        function BuildOverlay() {
            //debug('#', 'buildoverlay()');
            ui.$overlay = buildUniqueElement('overlay', $galleryBox.attr('id')); // main container for overlay
            ui.$mask = buildElement('mask'); // semitransparent
            ui.$scene = buildElement('scene') // something like overlay, but without semitransparency
            ui.$view = buildElement('view'); // main content (logo, photo or description or custom HTML)
            ui.$photo = buildElement('photo');
            ui.$html = buildElement('html');
            ui.$title = buildElement('title');
            ui.$desc = buildElement('desc');
            ui.$author = buildElement('author');
            ui.$close = buildElement('close', 'a')
            ui.$preload = buildElement('preload');
            ui.$link = buildElement('link', 'a')

            // event hiding overlay
            ui.$scene
				.bind('click', this, function(e) {
				    var target = e.target;
				    var root = e.data;
				    // clicking on elements in this 'if' statement will hide overlay
				    if ((target.className == ui.$scene[0].className) ||
						(target.className == ui.$view[0].className) ||
						(target.className == ui.$close[0].className)) { // clicking in image doesn't close the Artshow
				        hideOverlay();
				    }
				})
				.append(ui.$preload)
				.append(ui.$view);



            ui.$view
				.append(ui.$photo)
				.append(ui.$html);

            ui.$html
                .append(ui.$title)
                .append(ui.$desc)
                .append(ui.$author)
            if(globals.galeryId==395)
				ui.$html.append(ui.$link);

            ui.$photo.append(ui.$close);

            ui.$panelBox = buildElement('panel-box');
            ui.$panel = buildElement('panel'); // black panel at the bottom of overlay
            ui.$thumbs = buildElement('thumbs'); // inner container for thumbnail list
            ui.$list = buildElement('list', 'ol'); // list with thumbnails
            ui.$listPrev = buildElement('list-prev', 'a'); // skip to the previous page button
            ui.$listNext = buildElement('list-next', 'a'); // skip to the next page button
            ui.$listNav = ui.$listPrev.add(ui.$listNext); // skipping buttons. combined declaration for clarity
            //   ui.$pager = buildElement('pager'); // dotted pager
            ui.$navi = buildElement('navi');
            ui.$naviPrev = buildElement('navi-prev', 'a');
            ui.$naviNext = buildElement('navi-next', 'a');


            ui.$thumbs
					.append(ui.$list)
					.appendTo(ui.$panel);

            ui.$panel
            //	.append(ui.$pager)
					.append(ui.$listPrev)
					.append(ui.$listNext)

            ui.$panelBox
                    .append(ui.$panel)


            ui.$navi
					.append(ui.$naviPrev)
					.append(ui.$naviNext)
					.appendTo(ui.$scene);

            ui.$overlay.hide();
            ui.$overlay
				.append(ui.$mask)
				.append(ui.$scene)
				.append(ui.$panelBox)
				.appendTo('body');

        }

        function ShowPhoto(source) {
            //   debug('ShowPhoto()  otworzyłem foto ', source);


            $view = ui.$view
            $photo = ui.$photo
            $title = ui.$title
            $desc = ui.$desc
            $author = ui.$author
            $html = ui.$html
            $image = jQuery('<img/>');
            $preload = ui.$preload;
            $link = ui.$link;

            $photo.find('img').remove();

            $view.hide();
            $preload.css("margin", ((globals.sceneHeight - $preload.height()) / 2) + "px auto 0").show();


            $desc.html(jQuery('.desc', source).text());
            $title.text(jQuery('img', source).attr('title'));
            $author.text('foto: ' + jQuery('.author', source).text());
            
			if(globals.galeryId==395) {
				var pageUrl = window.location.href.toLowerCase();
				var pageEn = new RegExp('/2009/en/');
				if(pageEn.test(pageUrl) == true)
					$link.attr('href', source.attr('href').replace('_500','')).html('Download original');
				else
					$link.attr('href', source.attr('href').replace('_500','')).html('Pobierz orginał');
			}


            $photo.append(
                $image.attr('src', source.attr('href')).load(function() {                    
                    $preload.hide();                   
                    $view.fadeIn(20, function() {
                    var viewWidth = $image.width() + 32;
                   // debug('viewWidth', viewWidth);                  
                    $view.css('width',viewWidth);

                    globals.viewHeight = $view.height();
                    globals.viewTopMargin = (globals.sceneHeight - globals.viewHeight) / 2;
                    SetUiViewTopMargin(globals.viewTopMargin);});
                }));
        }

        function hideOverlay() {
            jQuery("html").removeClass('overflow');
            globals.pageIndex = 1;
            ui.$overlay.hide();
            ui.$list.removeAttr('style');

            jQuery(document).unbind('keypress').unbind('keydown');


            if (settings.type == 'fromthumb') {
                $thumbList.remove();
                ui.$overlay.remove();
            }

            jQuery('embed, object').show(); //pokazuje wszystkie flashe na stronie
        }

        function SetThisPhotoIndex(clicked) {
			debug(jQuery(clicked),"");
            globals.photoIndex = ui.$list.find('a').index(clicked);
            debug('photoIndex: ', ui.$list.find('a').index(clicked) + ' ' + clicked);
        }

        function SetThisThumbActive(clicked) {
            ui.$list.find('li').removeClass('active');
            ui.$list.find('li').eq(globals.photoIndex).addClass('active');
            // jQuery(clicked).parent().addClass('active');
            //debug(jQuery(clicked).parent().html(), '');
        }

        function SetCurrentPage() {
            globals.pageIndex = Math.ceil((globals.photoIndex + 1) / globals.photosPerPage);
        }

        function CalculateDimensions() {
            globals.thumbsListWidth = parseInt(jQuery(window).width()) - 110; //długość div'a obejmującego listę ol z miniaturami zdjęć
            globals.olListWidth = (ui.$list.find('li').size() * 60) + 10;  //długość listy ol z miniaturami zdjęć
            globals.photosPerPage = Math.floor(globals.thumbsListWidth / 60); //(ui.$list.find('li').eq(1).width() + parseInt(ui.$list.find('li').css('margin-right')));
            globals.thumbsListWidth = globals.photosPerPage * 60;
            globals.pages = Math.ceil(globals.olListWidth / globals.thumbsListWidth);
            globals.sceneHeight = parseInt(jQuery(window).height()) - 100;
            globals.viewTopMargin = (globals.sceneHeight - globals.viewHeight) / 2;
        }

        function SetContainersDimension() {
            ui.$list.width(globals.olListWidth);
            ui.$thumbs.width(globals.thumbsListWidth);
            ui.$scene.height(globals.sceneHeight);
        }

        function SetUiViewTopMargin(margin) {
            if (margin < 0) margin = 0;
            ui.$view.css("margin", margin + "px auto 0");

        }



        function NextImage() {
            if (globals.photoCount > globals.photoIndex + 1) {
                var $next = jQuery(ui.$list.find('li a').eq(globals.photoIndex + 1));
                SetThisPhotoIndex($next);
                SetThisThumbActive($next);
                ShowPhoto($next);
                //debug('modulo ', ((globals.photoIndex + 1) % globals.photosPerPage));
                if ((globals.photoIndex + 1) % globals.photosPerPage == 1) {
                    NextPage();
                }
            }
        }
        function PreviousImage() {
            if (globals.photoIndex > 0) {
                var $prev = jQuery(ui.$list.find('li a').eq(globals.photoIndex - 1));
                SetThisPhotoIndex($prev);
                SetThisThumbActive($prev);
                ShowPhoto($prev);
                //debug('modulo ', ((globals.photoIndex) % globals.photosPerPage));
                if ((globals.photoIndex) % globals.photosPerPage == globals.photosPerPage - 1) {
                    PreviousPage();
                }
            }
        }

        function NextPage() {
            //debug(globals.pages, globals.pageIndex);
            if (globals.pages > globals.pageIndex) {
                ui.$list.animate({ "left": "-=" + globals.thumbsListWidth + "px" }, 600);
                globals.pageIndex++;
            }
        }
        function PreviousPage() {
            if (globals.pageIndex > 1) {
                ui.$list.animate({ "left": "+=" + globals.thumbsListWidth + "px" }, 600);
                globals.pageIndex--;
            }
        }


        function GoToCurrentPage() {
            var position = ((globals.pageIndex - 1) * globals.thumbsListWidth);
            ui.$list.css("left", "-" + position + "px");
        }



        //end public functions
    };

    //    function debug($obj) {
    //        if (window.console && window.console.log)
    //            window.console.log('DaGallery selection count: ' + $obj.attr('id'));
    //    };

    function debug(msg, msg2) {
        if (window.console && window.console.log)
            window.console.log(msg + ' ' + msg2);
    };

    buildElement = function(className) {
        var element = 'div';
        if (typeof arguments[1] != 'undefined') {
            element = arguments[1]; // build a custom tag, not a div
        }
        return jQuery('<' + element + ' class="' + $.fn.DaGallery.globals.classPrefix + '-' + className + '"></' + element + '>');
    }

    buildUniqueElement = function(className, idName) {
        var element = 'div';
        return jQuery('<' + element + ' class="' + $.fn.DaGallery.globals.classPrefix + '-' + className + '" id="' + $.fn.DaGallery.globals.classPrefix + '-' + idName + '"></' + element + '>');
    }

    $.fn.DaGallery.defaults = {
        fotoCount: 0,
        fotoSize: 500,
        thumbSize: 100,
        type: 'fromlist', //fromlist,ajax,fromthumb
        galleryWidth: '500px',
        galleryUrl: 'http://www.polskieradio.pl/_cms/galleries/',
        ajaxUrl: 'gallery_500_48_176.xml'
    };

    $.fn.DaGallery.globals = {
        thumbsListWidth: 0, //długość div'a obejmującego listę ol z miniaturami zdjęć 
        olListWidth: 0, //długość listy z miniaturami zdjęć
        photoIndex: 0, //index wybranego zdjęcia w kolekcji miniatur z $list (0 based)
        photoCount: 0,
        photosPerPage: 0,
        viewTopMargin: 0,
        viewHeight: 0,
        sceneHeight: 0,
        pageIndex: 1, //index bierzącej strony w pagerze (1 based)
        pages: 1, //ilość stron w pagerze
        classPrefix: 'daGallery',
        xmlPath: '',
        galeryId: 0
    };
})(jQuery);