$(document).ready( function() {
    $("#reorder").bind("change",sortBy);
    $("#ppp").bind("change",postPerPage);
    $('#keyword').bind("click",clearBox).bind("blur",clearBoxBlur);

    //Lightbox
    if($('.pics > a').length > 0){
        $('.pics > a').lightBox();
    }

    //Switch Captcha
    if($("#captcha_refresh").length > 0){
        $('#captcha_refresh').bind("click",function(){
           $('#captcha').attr("src","/home/captcha?rnd=" + Math.floor(Math.random()*10000));
           return false;
        });
    }
});

function clearBox(){
    if($(this).val() == "Enter Keyword"){
        $(this).val("");
    }
}

function clearBoxBlur(){
    if($(this).val() == ""){
        $(this).val("Enter Keyword");
    }
}

function sortBy(){
    window.location.href = window.location.pathname + "?reorder=" + this.value;
}

function postPerPage(){
    window.location.href = window.location.pathname + "?ppp=" + this.value;
}

function bindImages(){
    var isFlash = fixFlash(".pics > div[id*='flash-']");
    var tag = "img";

    if(!isFlash){
        //If there's no flash, add lightbox
        if($('#p_main-item  > a').length > 0){
            $('#p_main-item > a').lightBox();
        }
        tag = "a";
    }

    $('#p_sub-items > ul> li > a').each(function(){
        $(this).bind("click",function(){
            var id = $(this).attr("id");
            id = id.substr(6);

            //Make sure all elements are hidden
            $('.pics > ' + tag + ':not(.hide)').addClass("hide");
            $(".pics > div[id*='flash-']:not(.hide)").addClass("hide");

            //Make one visible.
            $('#image-'+id).removeClass("hide");
            $('#flash-'+id).removeClass("hide");

            //Sub items
            $('#p_sub-items > ul > li:.current').removeClass("current");
            $('#thumb-'+id).parent().addClass("current");
            return false;
        });
    });
}
