(function($){
	$(document).ready(function(){

		$('#thumbnail-list .site-theme-thumbnail input[type=radio]').thumbnailRadioButton({
			radioGroupId: 'thumbnail-list',
			thumbnailClass:'radio-button-thumbnail image shadow',
			select:function($thumbnail, $radio){
				$thumbnail.css('border-style', 'inset');
				$thumbnail.parent().removeClass('shadow');

				$('#btnSave').removeAttr('disabled');
				$('#themeid').val($radio.val());
			},
			deselect:function(){
				$('#thumbnail-list .radio-button-thumbnail img').css('border-style', 'solid');
				$('#thumbnail-list .radio-button-thumbnail').addClass('shadow');
			}
		});

		$('.site-theme-thumbnail .image.selected img').addClass('inset');

		$('#preview-dialog').dialog({
			title:'Preview',
			autoOpen:false,
			modal:true,
			resizable:false,
			height:805,
			width:828,
			dialogClass:'sb-dialog-container preview-dialog-container shadow-dark',
			create:function(){
				$('#btnClose').click(function(){
					$('#preview-dialog').dialog("close");
				});
			}
		});
		
		$('#btnCancel').click(function(){
			location.href = 'site-manager';
		});
		
		$('#btnPreview').click(function(){
			$('#preview-dialog').dialog("open");
		});

		$('.preview-button').click(function(){
			$('.image', $(this).prev()).click();
		});

		$('.preview-button button[name=btnPreview]').click(function(){
			$('#preview-dialog .dialog-content .preview-image').hide();
			$('#preview-dialog .loading-icon').show();

			var previewTitle = $('label', $(this).closest('.site-theme-thumbnail')).text();
			$('#preview-dialog').dialog("option", "title", "Preview: " + previewTitle).dialog("open");

			var img = new Image(800, 700);
			img.onload = function(){
				$('#preview-dialog .loading-icon').hide();
				$('#preview-dialog .dialog-content .preview-image').html('<img src="' + this.src + '" alt="' + this.alt + '" title="" />').show();
			}
			img.onerror = function(){
				$('#preview-dialog .loading-icon').hide();
				$('#preview-dialog .dialog-content').html('<div class="error">Error loading the preview.</div>');
			}
			img.src = $(this).parent().prevAll('img').attr('src').replace('.png', '-large.png');

			img.alt = previewTitle;
		});
		
		$('.preview-button button[name=btnSelect]').click(function(){
			location.href = 'page';
		});
	});
})(jQuery);