


window.__tradedocsPreview_cache = new Object();

function tradedocsPreview(anchor, doc_href) {
	window.__tradedocsPreview_timer = setTimeout(function() {
		clearTimeout(window.__tradedocsPreview_timer);
		tradedocsPreviewGo(anchor, doc_href);
	}, 300);
}
function tradedocsPreviewGo(anchor, doc_href) {
	anchor = $(anchor);


	var divdim = { width: 200, height: 150 };

	if( $('divTradedocsPreview') ) {
		divdim.width = $('divTradedocsPreview').getStyle('width');
		divdim.height = $('divTradedocsPreview').getStyle('height');

		$('divTradedocsPreview').destroy();
	}

	var div;
	with( div = new Element('div') ) {
		id = 'divTradedocsPreview';
		setStyles({
			position: 'absolute',
			display: 'block',
			width: divdim.width,
			height: divdim.height,
			'line-height': divdim.height,
			left: anchor.getLeft(),
			top: anchor.getTop() + 20,
			opacity: 0
		});
	}
	div.inject(document.body);


	var imgLoading, imgPreview;

	var c = new Chain();
	c.chain(function(){
		new Fx.Tween(div, {
			duration: 250,
			onComplete: function() {
				c.callChain();
			}
		}).start('opacity', 1);

	}).chain(function(){

		if( !window.__tradedocsPreview_cache[doc_href] ) {
			with(  imgLoading = new Element('img') ) {
				src = 'assets/images/loading.gif';
				setStyles({
					'display': 'block',
					'margin-left': 'auto',
					'margin-right': 'auto',
					'padding-top': div.getHeight() / 2 - 16
				});
				inject(div);
			};

			new Request({
				method: 'post',
				url: '/site/tradedocs/ajax_get_preview?doc_href='+doc_href,
				onSuccess: function(response) {
					window.__tradedocsPreview_cache[doc_href] = JSON.decode(response);
					c.callChain();
				}
			}).send();
		}
		else c.callChain();

	}).chain(function(){
		try { imgLoading.destroy(); } catch(e) {};

		if(!window.__tradedocsPreview_cache[doc_href] || !window.__tradedocsPreview_cache[doc_href].src) {
			div.innerHTML = 'Preview not available';
	
		} else {
			new Fx.Morph(div, {
				duration: 180,
				onComplete: function() {
					with( imgPreview = new Element('img') ) {
						src = window.__tradedocsPreview_cache[doc_href].src;
						setStyles({
							width: window.__tradedocsPreview_cache[doc_href].width,
							height: window.__tradedocsPreview_cache[doc_href].height,
							display: 'block',
							margin: 'auto',
							opacity: 0
						});
						inject(div);
					}

					new Fx.Tween( imgPreview, {
						duration: 200
					}).start('opacity', 1);
				}
			}).start({
				width: window.__tradedocsPreview_cache[doc_href].width,
				height: window.__tradedocsPreview_cache[doc_href].height
			});
		}

		c.callChain();
	}).callChain();

}

function tradedocsPreviewOut() {
	clearTimeout(window.__tradedocsPreview_timer);

	var div = $('divTradedocsPreview');
	if(div) {
		new Fx.Tween(div, {
			duration: 100,
			onComplete: function() {
				div.setStyle('display', 'none');
			}
		}).start('opacity', 0);
	}


}














