var pb_media_ImageUtils = Class.create({
	getImageSize: function(imageUrl,callback){
		var image = new Image();
		image.src = imageUrl;
		if (image.width || image.height){
			var size = new Object();
			size[0] = image.width;
			size.width = image.width;
			size[1] = image.height;
			size.height = image.height;
			callback(size);
		}
		else {
			image.onload = function(){
				var size = new Object();	
				size[0] = this.width;
				size.width = this.width;
				size[1] = this.height;
				size.height = this.height;
				callback(size);		
			}
		}
	},
	
	preloadStyleImages: function(style){
		var backgroundImage = pb.core.cssUtils.parseBackgroundImage(style);
		if (backgroundImage) pb.media.imagePreloader.load(backgroundImage);
	},
	
	getImageUrl: function(imageId,onSuccess){
		new Ajax.Request(system.getLibraryPath() + 'plasticbriqFramework/actions/_image_picker_actions.php',{
				method:'post',
				parameters:{command:'getImageUrl',style:system.getCurrentStyle(),imageId:imageId},
				onSuccess:onSuccess
			});	
	},
	
	checkImageUrl: function(url,callback) {
		pb.core.console.log('checking url ' + url);
		var image = new Image();
		image.src = url;
		if (image.width || image.height){
			callback(true);
		}
		else {
			image.onerror = function() {
				pb.core.console.log('url not valid');
				callback(false);				
			}
			
			image.onload = function(){
				if (image.width || image.height) {
					pb.core.console.log('url valid');
					callback(true);
				}
				else {
					pb.core.console.log('url not valid');
					callback(false);
				}
			}
		}
	}

});

var pb_media_ImageLoader = Class.create({
	
	actionFile: 'actions/_image_actions.php',
	
	load: function(containerId,thumbUrl,imageId,callback){

		var params = { id: imageId, thumbUrl: thumbUrl };

		pb.core.actions.executeAndPutResultIntoContainer(system.getLibraryPath() + 'plasticbriqFramework/' + this.actionFile,'loadImage',params,containerId,true);
		
		// var container = $(containerId);
		// if (!container) return;
		// container.innerHTML = pb.core.loaderAnimation.getLoaderContainerText();
		// var image = new Image();
		// image.src = imageUrl;
		// if (image.width || image.height){
		// 	container.innerHTML = '<img src="' + imageUrl + '"/>';
		// 	if (callback) callback();
		// }
		// else {
		// 	image.onload = function(){
		// 		container.innerHTML = '<img style="width: ' + this.width + 'px;height: ' + this.height + 'px;" src="' + imageUrl + '"/>';
		// 		if (callback) callback();				
		// 	}
		// }
	}
}); // pb_media_ImageLoader

var pb_media_ImagePreloader = Class.create({
	load: function(imageUrl){
		var image = new Image();
		image.src = imageUrl;
	}
}); // pb_media_ImagePreloader

var pb_media = Class.create({
	imageUtils: new pb_media_ImageUtils(),
	imagePreloader: new pb_media_ImagePreloader(),
	imageLoader: new pb_media_ImageLoader()
});
