/**
 * $Id$
 */
 
var sitename;
(function($){
 $.fn.mediagallery = function(options) {
 	
    var gallery = this;
    this.find(".imageThumbs").css("display","block");
    this.find(".videoThumbs").css("display","block");

    var images = this.find(".image .thumbLink");
    var videos = this.find(".video a");
    
    var placeholder = $('#media_placeholder');
    if (!(placeholder && (images.length || videos.length))) return this;
    
    var image_hold = false;
    var video_hold = false;
    var img_target = '';
    var image_big_target = '';
    var player = '';
    var carousel = '';
    
    var ch_loaded = 0;
    var ch_all = 0;

    var image_big_layer = options.image_layer;
    
    if('wait_for' in options) {
        var check_status_times = 15;
        var check_status = function(task_id) {
            $.ajax({url:options.staff_url+'external/celery/'+task_id+'/successful/',
                    dataType:'jsonp',
                    success:function(data) {
                if(data == 'YES') {
                    $(gallery).find('.load_container').load('/sensiads/images/'+options.wait_for+'/', function() {
                        images = $(gallery).find(".image .thumbLink");
                        init_images();
                        options.on_animation($(images).eq(0))
                    });
                } else if(check_status_times > 1) {
                    check_status_times -= 1;
                    setTimeout(function() {check_status(task_id)}, 2000);
                }
            }});
        }
        if('wait_for_task_id' in options) {
            check_status(options.wait_for_task_id);
        } else {
            $.ajax({url: options.staff_url+'external/webupload/celery/apply/delayed_advert_images_resize/'+options.wait_for+'/',
                    dataType: 'jsonp',
                    success: function(data) {
                        setTimeout(function() {check_status(data.task_id)}, 2000);
                    }});
        }
    }
        if (images.length) {
            if (!image_big_layer) image_big_layer = $('<div class="boxLayer" id="big_photo_layer" style="display:none"><div class="borderedCell"><div class="inside"><a class="close" href="#" onclick="popup.hidePopup(\'big_photo_layer\');big_photo_layer_visible=false;return false;">Close</a><table><tbody><tr><td class="prev"><a href="" id="prev_img">prev</a></td><td id="actual"></td><td class="next"><a href="" id="next_img">next</a></td></tr></tbody></table></div><div class="crns crn-lt"></div><div class="crns crn-rt"></div><div class="crns crn-lb"></div><div class="crns crn-rb"></div><div class="sud su"></div><div class="sud sd"></div><div class="slr sl"></div><div class="slr sr"></div></div></div>');
        
            image_hold = $('<div class="main_photo"><div class="displayfield image" id="id_main_photo"><a href="#" id="show_big_photo_layer"><img src="'+images.eq(0).attr('href')+'" alt="'+images.eq(0).attr('title')+'" /></a></div></div>');
            placeholder.append(image_hold);
            $('body').append(image_big_layer);

            image_target = image_hold.find('img');
            image_big_target = image_big_layer.find('#actual').append('<img id="big_img" src="'+images.eq(0).next().attr('href')+' "alt="'+images.eq(0).next().attr('title')+'" />');
            image_big_target = image_big_layer.find('#big_img');
            if(images.length < 2) { image_big_layer.find('td a').hide(); }
        };

        if(image_hold) image_hold.hide();
        if (videos.length) {
            fph = '';
            if($('#flash_placeholder').length) {
                fph = $('<p>').append($('#flash_placeholder')).html();
            }
            video_hold = $('<div id="flashbanner" style="overflow:hidden"><div id="player_placeholder">'+fph+'</div></div>');
            var VIDPLAYER_LOADED = false;
            videos.click(function() {
                if(!VIDPLAYER_LOADED) {
                    $('#flashbanner').css({'height':options['height'],
                                           'width':options['width']})
                    if(image_hold) image_hold.hide();
                    return false;
                }
            });
            placeholder.append(video_hold);
        };
    
    cur_img = 0;
    big_photo_layer_visible = false;

    $('#show_big_photo_layer').click(function() {
        popup.showPopup('big_photo_layer');
        image_big_target.attr('src', ch_loaded.next().attr('href'));
        image_big_target.load(function() {
            popup.justify('big_photo_layer');
        });
        big_photo_layer_visible = true;
        return false;
    })
    var next_from = function(list){
        return function() {
            var i = list.index(ch_loaded.get(0));
            if (i==list.length-1) { i = 0; }
            else { i = i+1;}
            list.eq(i).click();
            return false;
            }
        }
    var prev_from = function(list) {
        return function() {
            var i = list.index(ch_loaded.get(0));
            if (i==0) { i = list.length-1; }
            else { i = i-1;}
            list.eq(i).click();
            return false;
            }
        }

    if (options.carousel) {
            var carousel = options.carousel.container.css('position','absolute');
            var offset = 0;
            var cp = $('<a class="prev" href="#">'+options.carousel.prev+'</a>').insertBefore( carousel.parent() );
            var cn = $('<a class="next" href="#">'+options.carousel.next+'</a>').insertAfter( carousel.parent() );
    }
    var init_images = function() {
        /* fixme: these should be connected to buttons known to lay in some layer... */
        $('#next_img').click(next_from(images));
        $('#prev_img').click(prev_from(images));
    
        ch_all = videos.add(images);
    
        if (options.off_animation) options.off_animation(ch_all);
        // connect image events instantly:
        images.click(function() {
            a = $(this);
            
            if (options.on_animation) { options.off_animation(ch_all); options.on_animation(a); }
            ch_loaded = a;
    
            var href = a.attr('href');
            if (href == "#") return false;
            
            if (video_hold) {
                $('#flashbanner').css({'height':'1px', 'width':'1px'});
                if($('#player_0').length) {
                    $('#player_0').css({'height':'0'});
                }
            }
            image_target.attr('src', href);
            
            if(big_photo_layer_visible) {
                image_big_target.attr('src', a.next().attr('href'));
            }
            image_hold.show();
            return false;
        });
        
        if (options.carousel) {
            // carousel - contains all spans (its width is the sum of all children widths
            // carousel.parent has exacly the visible width
            // it is essential to init carousel on window.load not document.ready. Because on document.ready the images are not loaded yet
            // so we can't get their actual width.
            //if (ch_all.length < 3) {
            if (carousel.width() <= carousel.parent().width()) {
                cp.css('visibility','hidden'); cn.css('visibility','hidden');
            } else {
                cp.css('visibility',''); cn.css('visibility','');
                var max_offset = carousel.width() - carousel.parent().width() - 5;
                var step = options.carousel.step;
                var show_hide_arrows = function() {
                    if (offset == 0) {
                        cp.hide();
                    } else {
                        cp.show();
                    }
                    if (offset == -max_offset) {
                        cn.hide();
                    } else {
                        cn.show()
                    }
                }
                show_hide_arrows(); // initialize
                var next_car = function() {
                    offset -= step;
                    if (offset < -max_offset) offset = -max_offset;
    
                    carousel.stop().animate({left:offset}, 400);
                    return false;
                    }
    
                var prev_car = function() {
                    offset += step;
                    if (offset > 0) offset = 0;
                    carousel.stop().animate({left:offset}, 400);
                    return false;
                    }
               cp.click(prev_car); cn.click(next_car);
               cp.click(show_hide_arrows);
               cn.click(show_hide_arrows);
           }
    }
    }
    init_images();
    
    var init_changers = function () {
        if (!options['changers']) return;
        if ( ch_all.length > 1 ) {
            $('<a class="prev" href="#">'+options['changers']['prev']+'</a>').click(prev_from(ch_all))
            .add(
            $('<a class="next" href="#">'+options['changers']['next']+'</a>').click(next_from(ch_all))
            ).appendTo(gallery);
        };
    };


    if (videos.length) {        
        // first video
        if(videos.filter('.valid').length) {
            var has_valid_video = true;
            ch_loaded = videos.filter('.valid').eq(0);
        } else {
            var has_valid_video = false;
            ch_loaded = videos.eq(0);
        }
        if(!has_valid_video && images.length) {
            images.eq(0).click();
            init_changers()
        }
        iv_urls = ch_loaded.attr('href').split("#");
        
        var flashvars = $.extend(options['playervars'], {image:iv_urls[0], file:iv_urls[1]});
        // insert video gallery and connect when it's ready
        create_player("player_placeholder", flashvars, 1, 1, "player_0",
            function(p) { /* callback after player is ready:*/
							 video_hold = p;
               if (image_hold) image_hold.hide();
               videos.click(function() {
                    a = $(this); ch_loaded = a; 
                    if (options.on_animation) { options.off_animation(ch_all); options.on_animation(a); }
                    iv_urls = a.attr('href').split("#");
                    if (image_hold) image_hold.hide();                    
                    p.sendEvent("LOAD", {image:iv_urls[0], file:iv_urls[1]}); 
                    /* p.sendEvent("PLAY", true); */
                    $('#player_0').css({'height':options['height'],
                                        'width':options['width']});                    
                    $('#flashbanner').css({'height':options['height'],
                                           'width':options['width']});
                    return false;
                });
                if(has_valid_video || !images.length) { // changers not initialized yet.
                    init_changers();
                    $('#player_0').css({'height':options['height'],
                                        'width':options['width']});                    
                    $('#flashbanner').css({'height':options['height'],
                                           'width':options['width']});
                } else { // hide player
                    images.eq(0).click();
                }
            });
    } else { // no videos load first image
        images.eq(0).click();
        init_changers();
    };          

    return gallery;
};
})(jQuery);




