$(document).ready(function(){
    initPage();
})

function initPage(){
    doImageFrame();
    doCenterObject();
    doShowSearch();
//    doHideLastSep();
}

function doImageFrame(){
    // default picture insertion
    $(".wp-caption").each(function(){
        $("img", this).before('<span></span>');
    });

    // fixed width single picture
    $("img.pic").each(function(){
        $(this).wrap('<div class="photo"></div>')
        .wrap('<a href="'+$(this).attr("src")+'" title="'+$(this).attr("alt")+'" rel="lightbox" class="lightbox"></a>');
        $(this).before('<span/>').after('<em>'+$(this).attr("alt")+'</em>');
    });

    // fixed width horizontal picture gallery
    $("ul.gallery").each(function(){
        $(this).after('<div class="clear"/>');
        $("li img", this).each(function(){
            doResizeImage(170, 120, $(this));
            $(this).wrap('<a href="'+$(this).attr("src")+'" title="'+$(this).attr("alt")+'" rel="lightbox-album" class="lightbox"></a>');
            $(this).before('<span/>').after('<em>'+$(this).attr("alt")+'</em>');
        });
    });

    // fixed width vertical picture gallery
    $("ul.vgallery").each(function(){
        $(this).after('<div class="clear"/>');
        $("li img", this).each(function(){
            doResizeImage(120, 170, $(this));
            $(this).wrap('<a href="'+$(this).attr("src")+'" title="'+$(this).attr("alt")+'" rel="lightbox-album" class="lightbox"></a>');
            $(this).before('<span/>').after('<em>'+$(this).attr("alt")+'</em>');
        });
    });
}

function doResizeImage(maxWidth, maxHeight, object){
    var ratio = 0;  // Used for aspect ratio
    var width = object.width();    // Current image width
    var height = object.height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        object.css("width", maxWidth); // Set new width
        object.css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
        width = width * ratio;    // Reset width to match scaled image
    }

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        object.css("height", maxHeight);   // Set new height
        object.css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
}

function doCenterObject(){
    $(".p_content object").each(function(){
        $(this).wrap('<center class="object"></center>');
    });
}

function doHideLastSep(){
    $(".p_sep:last").hide();
}

function doShowSearch(){
    $('#searchbox').fadeIn(150);
}

