
(function(){
	
	function showImage(url){
		var maskel = Ext.getBody();
		maskel.mask();
		
		var el=Ext.get("modal-image");	
		el.hide();
		el.dom.setAttribute("title", "click to close");
		el.setStyle("zIndex", 30000);
		el.on("click", function(){
			el.hide({
				callback: function(){
					Ext.get(maskel).unmask();
					el.removeAllListeners();
				}
			})
		})
		el.update("loading image ...");
		el.anchorTo(maskel, "c-c");
		el.show(true);
		
		var divdom = document.createElement("div");
		divdom.id="modal-image-close";
		var div = Ext.get(divdom).setStyle("position", "absolute");
		
		var imgdom = document.createElement("img");
		var img = Ext.get(imgdom);
		img.on("load", function(){
			scaleImg(img.dom);
			el.hide();
			el.update("");
			el.appendChild(div);
			el.appendChild(img);
			el.anchorTo(maskel, "c-c");
			el.show(true);
		});
		img.dom.src=url;
	}
		
	function scaleImg(img){
		var wMax = Ext.lib.Dom.getViewportWidth()-60;
		var hMax = Ext.lib.Dom.getViewportHeight()-60;
	
		if (Ext.isIE) {
			// drifferent padding/margin behaviour in IE
			wMax -= 2 * 3;
			hMax -= 2 * 3;
		}
		
		var ratio = img.height/img.width;

		if(img.height>hMax){
			var newW = Math.min(hMax / ratio, wMax);
			img.height = newW * ratio;
			img.width = newW;
			return;
		}		
		if(img.width>wMax){
			var newH = Math.min(ratio * wMax, hMax);
			img.height = newH;
			img.width = newH / ratio;
			return;
		}
	}

	// init:
	Ext.onReady(function(){
		Ext.select(".post-abstract a, .post-body a").each(function(el){
			var href = el.dom.href;
			var a = href.split(".");
			if(a.length>1){
				var ext = a.pop().toLowerCase();
				if(ext=="png" || ext=="jpg" || ext=="gif"){
					el.on("click", function(ev){
						ev.preventDefault();
						showImage(this);
					}, href)
				}
			}
		})
	})
	
}())