
var PK = {}

PK.Dialog = {
	init: function () {
		var dlg = $('#dialog');
		var dlgForm = $('#dialog form');
		
		dlg.prepend('<div class="errors"></div>');
		dlg.append('<div class="mask"></div>');
		dlg.append('<div class="processing"><div>Processing...</div></div>');
		
		var dlgMask = $('#dialog .mask');
		var dlgProc = $('#dialog .processing');
		var dlgErrors = $('#dialog .errors');
		
		$(document.body).append(dlg);
		
		dlgForm.append(
			"<div class='dialog-bar'>"
			+ "<button type='submit'>OK</button>"
			+ "<button onclick='$(\"#dialog\").hide(\"fast\"); return false'>Cancel</button>"
			+ "</div>"
		);
		
		dlgForm.ajaxForm({
			beforeSubmit: function () {
				dlgMask.show();
				dlgProc.show();
			},
			success: function (response) {
				dlgMask.hide();
				dlgProc.hide();
				
				if (response.success) {
					dlg.hide('normal');
				} else {
					dlgErrors.empty();
					var errors = "";
					for (var i=0; i<response.errors.length; i++) {
						errors += "<div>"+response.errors[i]+"</div>";
					}
					dlgErrors.append(errors);
				}		

				if (PK.Dialog.callback) PK.Dialog.callback();
				PK.Dialog.callback = null;	
			},
			dataType: 'json'
		});
	},
	
	show: function (name, cb) {
		$('#dialog > div').hide();
		$('#'+name).show();
		$('#dialog .errors').empty();
		$('#dialog').center().hide().show('normal');
		
		PK.Dialog.callback = cb;
	}
	
};

$(document).ready(function(){
//	PK.Dialog.init
	$('a.lightbox').lightBox();
	$('a.lightbox').each(function(){
		var width = $('img',this).width();
		var height = $('img',this).height();
		if (width < height) {
			$('img',this).attr('width', '200');
		} else {
			$('img',this).attr('height', '200');
		}
	});
	$('a.lightbox span.close').click(function(){
		var image = $(this).parent();
		if (confirm('Do you really want to delete this photo?')) {
			$.get('http://'+location.host+location.pathname, {'delete': $(this).attr('id').match(/image(\d+)/)[1]}, function(answer){
				if (answer != null && answer.success == 'ok') {
					$(image).remove();
				}
		    }, "json");    
		}
		return false;
	});
});
