$(document).ready(function() {
	/*Hide all checkboxes*/
    $("#frm_comments li input").addClass("hide");
    
    /*toggle selected images.*/
    $("#frm_comments li img").toggle( 
        function(){    
            $(this).parent().children(":checkbox").attr("checked", "checked");
            $(this).parent().parent().addClass("hilite");
            //debug only
            //alert($(this).parent().children(":checkbox").attr("checked"));
        },
        function(){
            $(this).parent().children(":checkbox").removeAttr("checked");
            $(this).parent().parent().removeClass("hilite");
            //debug only
            //alert($(this).parent().children(":checkbox").attr("checked"));
        }
    );       

    /* submit comment form*/
    $("#frm_comments").submit(function(){
        var elements = new Array();
        $('.related-items input:checked').each(function(){
            elements.push($(this).val());
        });
        
        var ajaxQuery = $(this).attr("action");
        ajaxQuery = "/ajax" + (ajaxQuery.substr(0, 1) == '/' ? '' : '/') + ajaxQuery;
        
        var pos = ajaxQuery.indexOf('#');
        
        if (pos) {
            ajaxQuery = ajaxQuery.substr(0, pos);
        }
        
        $.ajax({
            data: { comment: $('#comment').val(), 'elements[]': elements },
            error: function (xhr, status, error) {
                $('#frm_comments label:first').filter(':not(:has(p.error))').prepend('<p class="error">Unohdit kirjoittaa kommenttisi!</p>');
								//$('#frm_comments label:first').filter(':not(:has(p.error))').prepend('<p class="error">Unohdit kirjoittaa kommenttisi!</p>');

            },
            success: function (data, status) {
                $('#comment-browser').html(data);
                $('#comment').val('');
                $("#frm_comments :checked").siblings('img').click();
                $('#frm_comments label:first p.error').remove();
                ajaxifyPaginationLinks();
            },
            type: 'POST',
            url: ajaxQuery
        });

        return false;
    });

	// make comment text areas autogrow
	$('#frm_comments textarea').growfield();
	
	// comment pagination
	ajaxifyPaginationLinks();
});

function ajaxifyPaginationLinks()
{
	$('#comment-browser .pagination a').click(function(){
        var ajaxQuery = "/ajax" + ($(this).attr("href").substr(0, 1) == '/' ? '' : '/') + $(this).attr("href");

        $.post(ajaxQuery, {}, function(data, status) {
            if (status == 'success') {
                $('#comment-browser').html(data);
                ajaxifyPaginationLinks();
            }
        });
        
        return false;
	});
}
