/*
cacheImage
$.cacheImage(array(), .....); or
$.cacheImage("http://img.boxpix.com/public/m/image.jpg", {
	complete: function (e) {
	},
	load : function (e) {
		//try{ console.log('load ', this, e, this.src, this.width, this.height); }catch(e){};
	},
	error: function (e) {
	},
	abort: function (e) {
	}
});
*/
(function ($) {
    $.extend($, {
        cacheImage: function (src, options) {
            //console.log('........',src, options);
            if (typeof src === 'object') {
                // se src è un arry itera tra i vari elementi
                // chiamando cacheImage e passando src come singola stringa
                $.each(src, function () {
                    $.cacheImage(String(this), options);
                });
                return;
            }
            var image = new Image();
            options = options || {};
            $.each(['load', 'error', 'abort'], function () {
                // Martin: non capisco perchè complete non è nell'array
                // questo crea problemi quando manca l'immagine
                var e = String(this);
                if (typeof options[e] === 'function') {
                    //console.log('cacheImage',e);
                    $(image).bind(e, options[e]);
                }
                if (typeof options.complete === 'function') {
                    //console.log('cacheImage','complete',e);
                    $(image).bind(e, options.complete);
                }
            });
            image.src = src;
            return image;
        }
    });
})(jQuery);

//cacheImageCss
//$.cacheImageCss('/global/css/navigation.css');
//or $.cacheImageCss(array());
//ha bisogno di $.cacheImage()
(function ($) {
    $.extend($, {
        cacheImageCss: function (css, options) {
            if (typeof css === 'object') {
                $.each(css, function () {
                    $.cacheImageCss(String(this), options);
                });
                return;
            }
            if(css){
                var allImgs = [];
                options = options || {};
                $.get(css, function(data) {
                    var imgUrls = data.match(/[^\(]+\.(gif|jpg|jpeg|png)/g);
                    for (key in imgUrls) {
                    	if(imgUrls[key]) imgUrls[key] = imgUrls[key].replace("src='", "");
                    }                    
                    $.cacheImage(imgUrls);
                });
            }
        }
    });
})(jQuery);
