function NoticeHandler() {
    var count = 0;
    var currentIndex = 0;
    var messages = [];

    function showNext() {
        messages[currentIndex++].hide();
        currentIndex = currentIndex % count; 
        messages[currentIndex].fadeIn();
        window.setTimeout(showNext, 3000);
    }
    
    return {
        setup: function() {
            $('.notify_message').each(function() { messages[count++] = $(this) });
            if(count > 1) {
                window.setTimeout(showNext, 3000);
            }
            messages[currentIndex].show();
        }
    }
}

function ItemSortHandler() {
    
    function sortItems() {
        var selectedValue = $("#sort_by_select option:selected").val();
        var form = $('#SortByFilter');
        var action = form.attr('action');
        document.location = action + selectedValue
    }
    
    return {
        setup: function() {
            $('#sort_by_select').bind('change', sortItems);       
            $('#SortByFilter').resetForm();
        }
    }
}

function ThumbNailHandler() {
    function changeBigPhoto() {
        var elem = $(this);
        var thumb_path = elem.attr('src');
        var items = new RegExp('(.*)\/(.*)\/(.*)').exec(thumb_path);
        
        if((items.length != 4) || items[2] !== 'thumb') {
            return;
        }
        
        full_path = items[1] + '/full/' + items[3];
        
        $('#main_photo').attr('src', full_path);
        $('#main_photo_link').attr('href', full_path);
        
        $('#thumbnail_wrapper .thumb_item').removeClass('thumb_selected');
        elem.addClass('thumb_selected');        
    }
    
    return {
        setup: function() {
            $('#thumbnail_wrapper .thumb_item').click(changeBigPhoto);
        }
    }
}

$(document).ready(function() {
    if($('#notice_box').size() > 0) {
        noticeHandler = new NoticeHandler();
        noticeHandler.setup();
    }
    
    if($('#sort_by_select').size() > 0) {
        sortHandler = new ItemSortHandler();
        sortHandler.setup();   
    }
    
    if($('#item_list_container').size() > 0) {
        $('.section_item_container:last').addClass('last_section_item_container');
        $('.last_section_item_container').removeClass('section_item_container');
    }
    
    if($('#thumbnail_wrapper').size() > 0) {
        thumbnailHandler = new ThumbNailHandler();
        thumbnailHandler.setup();    
    }
    
    $('#main_photo_link').flyout();
});

