var strings = {
    'select': '<div class="select"><div class="selected">{0}</div><div class="selection"><div class="options">{1}</div></div></div>',
    'preview': {
        'container': '<div class="preview">{0}</div>',
        'element': '<div class="element" rel="{2}"><div class="entry"><div class="image">{0}</div><p class="title">{1}</p></div></div>'
    }, 'gallery': {
        'container': '<div class="gallery">{0}</div>',
        'element': '<p rel="{0}"><img src="{1}" /></p>',
        'blank': '<p><img /></p>'
    }, 'pager': {
        'container': '<ul class="pager"><li class="prev"><a href="javascript:void(0);"></a></li>{0}<li class="next"><a href="javascript:void(0);"></a></li></ul>',
        'element': '<li><a rel="{0}" href="{1}">{0}</a></li>'
    }
}

function photoGallery() {
    var self = this;
    this.data = {};
    this.core = {'root': j('#gallery'), 'select': {}, 'preview': {}};
    this.addr = '/files/photographers/gallery/' + photographer + '/';
    this.index = null;
    this.first = true;
    this.position = 0;
    this.count = {'min': 0, 'max': 0};

    this.start = function() {
        if (typeof gallery == 'object') {
            self.data = gallery;
            this.construct();
        }
    };
    
    this.setSheet = function(index) {
        self.index = index;
        return self.getSheet();
    }
    
    this.getSheet = function() {
        return self.data[self.index]['data'];
    };

    this.cutSheet = function() {
        for (i in self.data) {
            self.data[i]['data'] = self.data[i]['data'].slice(1);
        };
    };
    
    this.construct = function() {
        options = '';
        preview = '';
        for (i in self.data) {
            options += '<a href="javascript:void(0);" rel="'+i+'">'+self.data[i]['title']+'</a>';
            preview += strings.preview.element.format('<img src="'+self.addr+self.data[i]['data'][0]+'" alt="'+self.data[i]['title'].replace(/"/g, "&quot;")+'" />', self.data[i]['title'], i);
        };
        self.core.select.container = j(strings.select.format('Wybierz galerię', options))
            .appendTo(j(self.core.root).find('h3'));
        self.core.select.element = self.core.select.container.find('a');
        self.core.preview.container = j(strings.preview.container.format(preview))
            .appendTo(j(self.core.root).find('.content'));
        self.core.preview.element = self.core.preview.container.find('.element');
        self.actions();
    };
    
    this.actions = function() {
        j(self.core.root).find('.selected').bind('click', function() {
            j(this).parents('.select').find('.selection').slideToggle(120);
            return false;
        })
        j(self.core.select.element).bind('click', function() {
            t = j(this);
            t.parents('.select').find('.selected').html(t.html());
            t.parents('.selection').slideUp(120);
            t.siblings('a').show();
            t.hide();
            self.setSheet(j(this).attr('rel'));
            self.draw();
            return false;
        });
        j(self.core.preview.element).bind('click', function() {
            j(self.core.select.element).eq(j(this).index()).trigger('click');
            return false;            
        });
    };
    
    this.draw = function() {
        if (self.first) {
            self.cutSheet();
            self.first = false;
        } else {
            j(self.core.root).find('.pager').remove();
        }
        self.count.max = j(self.getSheet()).size();
        self.position = 0;
        sheet = self.getSheet();
        j(self.core.root).find('.content').empty()
            .append(strings.gallery.container.format(strings.gallery.blank));
        self.pager();
        self.active();
    };
    
    this.active = function() {
        r = j(self.core.root).find('.pager li');
        e = r.find("a[rel='"+self.position+"']");
        r.removeClass('active');
        e.parent().addClass('active');
        self.load(e.attr('href'));
    }
    
    this.pager = function() {
        sheet = self.getSheet();
        pages = '';
        for (i in sheet) {
            pages += strings.pager.element.format(i, self.addr+sheet[i]);
        }
        pager = j(self.core.root).find('.content')
            .append(strings.pager.container.format(pages));
        pager.find('a').bind('click', function() {
            self.position = j(this).attr('rel');
            self.active();
            return false;
        });
        pager.find('.next a').unbind('click').bind('click', function() {
            self.position++;
            if (self.position == self.count.max) {
                self.position--;
                return false;
            };
            self.active();
            return false;
        });
        pager.find('.prev a').unbind('click').bind('click', function() {
            self.position--;
            if (self.position < 0) {
                self.position++;
                return false;
            };
            self.active();
            return false;
        });
    };
    
    this.load = function(url) {
        var e = document.createElement('img');
        var t = j(self.core.root).find('.gallery p');
        var r = t.find('img').not('.hidden');
        e.src = url;
        e.onload = function() {
            e.className = 'hidden';
			e.setAttribute("style", "margin: -"+(e.height / 2)+"px 0 0 -"+(e.width / 2)+"px;");
            e.onload = function(){};
            c = j(e).appendTo(t);
            r.fadeOut(300, function() {
                r.remove();
                c.fadeIn(300).removeClass('hidden');
            });

        };
    }
}

var switcher = {
    data: {},
    
    start : function() {
        if (typeof gallery == 'object')
            this.pager();
    },
    
    write: function(index) {
        var index = index ? index : 0;
        j('#gallery .pager').empty().append(switcher.data[index]);
        var w = j('#gallery .pager ul').width() / 2;
        j('#gallery .pager ul').css({'marginLeft': -w});
        switcher.gallery(true);
    },

    pager: function() {
        j(gallery).each(function(i, d){
            var struct = '<ul><li class="prev"><a href="javascript:void(0);"></a></li>';
            for (e in d.data) {
                title = '';
                if (d.description) {
                    title = d.description[e] ? d.description[e] : '';
                } 
                struct += '<li class="item"><a href="/files/photographers/gallery/'+photographer+'/'+d.data[e]+'" rel="'+i+'" title="'+title+'"></a></li>';
            }
            struct += '<li class="next"><a href="javascript:void(0);"></a></li></ul>';
            switcher.data[i] = struct;                
            j('#gallery .title').append('<a class="element-'+i+'" href="javascript:void(0);" rel="'+i+'"><span></span> '+d.title+'</a>');
            j("#gallery .title a[rel='1']").animate({opacity: 0.3});
        });

        j('#gallery .title a').click(function() {
            var i = j(this).attr('rel');
            j('#gallery .title a').animate({opacity: 0.3});
            j(this).animate({opacity: 1});
            switcher.write(i);
            return false;
        });
        switcher.write();
    },

    slider: function(current, first) {
        j('.slider img').remove();
        title = current.attr('title');
        if (title) {
            j('.slider').height(468).css({'position': 'relative'});
            j('.slider .description').remove();
            j('.slider').append('<div style="position: absolute; bottom: 0;width: 949px" class="description">'+title+'</div>');
        }
        var elem = document.createElement('img');
        elem.src = current.attr('href');
        elem.onload = function() {
            var height = elem.height;
            var parent = '448';
            var margin = (parent > height) ? ((parent - height) / 2) : 0;
            j('.slider').prepend(elem);
            j(elem).css({marginTop: margin});
            elem.onload = function(){};
        };
    },

    gallery: function(start) {
        if (start) {
            var current = j('.pager .item:eq(0) a');
            current.parent().addClass('active');
            this.slider(current, true);            
        }
        j('.pager a').bind('click', function() {
            var block = false;
            if (block == false) {
                var action  = j(this).parent().attr('class');
                switch (action) {
                    case 'next':
                        element = j(this).parents('ul').find('.active');
                        if (element.next().is('.next')) {
                            block = true;
                            return false;
                        }
                        element.removeClass('active').next().addClass('active');
                        switcher.slider(element.next().find('a'), false)
                        break;
                    case 'prev':
                        element = j(this).parents('ul').find('.active');
                        if (element.prev().is('.prev')) {
                            block = true; 
                            return false;
                        }
                        element.removeClass('active').prev().addClass('active');
                        switcher.slider(element.prev().find('a'), false)
                        break;
                    default:
                        element = j(this);
                        j('.pager .active').removeClass('active');
                        element.parent().addClass('active');
                        switcher.slider(element, false);
                }

            }
            return false;
        });

        jQuery('.galery-select a').bind('click', function() {
            id = jQuery(this).attr('id');
            var ids = '#' + id + '-preview';
            jQuery('.galery-select a').not(id).animate({opacity: 0.3});
            jQuery(this).animate({opacity: 1});
            var $other = jQuery('.fotosection .preview').not(id + '-preview');
            $other.animate({opacity: 0}, 600, function() {
                $other.hide();
            });
            jQuery('.pager .active').removeClass('active');

            jQuery(ids).animate({opacity: 1, height: 529}, 300, function() {
                jQuery(ids).show();
            });
            jQuery(ids + ' .pager li:eq(1)').addClass('active');
            photographers.slider(jQuery(ids + ' .pager li:eq(1) a'), id, true);
            return false;
        });
    }
}

var video = {
    start: function() {
        this.write();
    },
    
    play: function(id) {
        document.getElementById('video-player-flash').playVideo(id);
    },
    
    write: function() {
        if (typeof videos  === 'object') {
            j('#video-player').addClass('javascript');
            var so = new SWFObject("/swf/photographer_player.swf", "video-player-flash", "900", "576", "9", "#000000", true);
            j.each(videos, function(key, val){
                so.addVariable(key, val);
            });
            so.addVariable("userId", userid);
            so.addVariable("gateway", "/cake_gateway.php");
            so.addVariable('hd', 1);
            so.addParam("allowScriptAccess", "always");
            so.addParam("scale", "noscale");
            so.addParam("allowFullScreen", "true");
            so.write("video-player");
            j('#header .interview').click(function() {
                video.play(1);
                return false;
            });
            j('#header .homework').click(function() {
                video.play(2);
                return false;
            });
        }
    }
}

var contest = {
    start: function() {
        this.photo();
        this.submit();
    },
    
    photo: function() {
        j('.winner-photo a').click(function() {
            var source = {
                src: j(this).attr('href'),
                'title': 'Kliknij aby zamknąć zdjęcie.'
            };
            var content = j('<div id="image_window" class="wimage"></div>');
            content.append('<div class="content"><a class="image" href="javascript:void(0);" title=""></a></div>');
            content.append('<div class="close"><a class="terminate" href="javascript:void(0);"></a></div>');
            var values = {
                'height' : j('body').height(),
                'width'  : j('body').width()
            };
            j('<div id="image_overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css(values).animate({opacity: 0.6}, 180, function() {
                j(content).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                    new Loader(source, '#image_window');
                    j('#image_window .image').click(function() {
                        j('#image_window').fadeOut('120', function() {
                            j('#image_overlay').fadeOut('60', function() {
                                j('#image_window').remove();
                                j('#image_overlay').remove();
                            });
                        });
                        return false;
                    })
                    Close();
                }).center();
            });
            return false;
        });
    },
    
    submit: function() {
        j('.contest-homework').click(function() {
            var target = j(this).attr('rel');
            var values = {
                'height' : j('body').height(),
                'width'  : j('body').width()
            };

            function closeLayer() {
                j('#homework-window').fadeOut('120', function() {
                    j('#overlay').fadeOut('60', function() {
                        j('#homework-window').remove();
                        j('#overlay').remove();
                    });
                });
            }
            jQuery.ajax({
                url: target,
                cache: false,
                success: function(content){
					var o = j('#contest .contest-homework').offset();
                    j('<div id="overlay"></div>').animate({opacity: 0}, 0).prependTo('body').css(values).animate({opacity: 0.6}, 180, function() {
                        j(content).css({'top': (o.top - 262)}).animate({opacity: 0}, 0).prependTo('body').animate({opacity: 1}, 260, function() {
                            if (j.browser.msie)
                                this.style.removeAttribute('filter');
                            Form.checkbox('#homework-window');
                            j('#homework-window .close, #overlay').click(function() {
                                closeLayer();
                                return false;
                            });
                            j('#homework-window .submit').click(function(){
                                j('form#homework-form').ajaxSubmit(function(content) {
                                    var c = j(content).find('.content').html();
                                    j('#homework-window .content').html(c);
                                });
                                return false;
                            });
                            j('.homework-file').filestyle({
                                imageheight : 30,
                                width: 376,
                                imagewidth : 63
                            });
                        });
                    });
                }
            });
            return false;
        });
    }
}

j(document).ready(function() {
    Cufon.replace('.element .date, #header h2, #contest h4, #gallery h4 span, #associated h4 span.cufon', {fontFamily: 'GlasgowPl RR Light'});
    Cufon.replace('#photographers .user-title h2.past-month,h1 span.cufon', {fontFamily: 'GlasgowPl RR ExtraBold'});
    Cufon.replace('#photographer-editor h3, .column h4, .element h3, .element h4, #header h1, #header h2 strong, #gallery h4 strong, #tutorials li a, #contest h4 strong, #associated h4 span.cufon strong', {fontFamily: 'GlasgowPl RR ExtraBold'});
    video.start();
    switcher.start();
    contest.start();
	if (typeof gallery == 'object') {
	 	g = new photoGallery();
	    g.start();		
	}
    Discussion.start();
});
