(function () {
	var $ = window.jQuery;
	window.top.ZemantaGetAPIKey = function () {
		return '4vfajjf9xusfqcducz6z5arg';
	};

	// experience zemanta - platform part
	function experience() {
		var side = $('.zemanta-wrap');
		if (side.size() === 0) {
			$('#experience').parent()
				.after('<div class="zemanta-wrap"><h2>Content recommendations</h2><div id="zemanta-sidebar"><div id="zemanta-control"><h1>Powered by Zemanta</h1></div><div id="zemanta-message">Loading...</div><div id="zemanta-source"></div><div id="zemanta-gallery"></div><div id="zemanta-articles"></div><div id="zemanta-tools" title="Drag to resize"></div></div></div><iframe src="/stats/experiencezemanta/" style="height:1px;width:1px;border:0;overflow:hidden;visibility:hidden;"></iframe>')
				.remove();
			(function () {
				var $ = null;
				function setPlatform($, p) {
					return $.zextend(p, {
						widget_version: 1,
						platform: {
							dnd_supported: true
						}
					});
				}
				function waitForLoad() {
					var done = false, t0 = null;
					t0 = arguments.callee.t0 = arguments.callee.t0 || new Date().getTime();
					if (typeof $.zemanta === "undefined") {
						setTimeout(arguments.callee, 100);
						return;
					}
					if (document.getElementById('content_ifr') !== null) {
						done = Zemanta.initialize(setPlatform($, {
							textarea_id: 'content_ifr',
							textarea_type: 'rte',
							interface_type: 'reblog',
							proxy_url: '/reblog/json-proxy/',
							tags_target_id: 'tags-input'
						}));
					}
					if (!done && new Date().getTime() - t0 < 5000) {
						setTimeout(arguments.callee, 100);
					}
				}
				try {
					if (!window.zQuery && window.jQuery) {
						window.zQuery = window.jQuery.noConflict(true);
						if (!window.jQuery) {
							window.jQuery = window.zQuery;
						}
					}
					$ = window.zQuery;
					waitForLoad();
				} catch(er) {
					window.setTimeout(arguments.callee, 100);
					return;
				}
			})();
		}
	}
	// publish
	function getValues() {
		return {
			post: tinyMCE.activeEditor.getContent().replace(' id="zemblockquote"',''),
			title: $('#reblogtitle').text()
		};
	}
	
	// content
	function onContentOver(ev) {
		var el = $(this),
			h = 0;
		if (!el.parent().hasClass("wrapped")) {
			el.wrap("<div></div>")
				.parent()
					.addClass("wrapped").append(el.clone().addClass("bottom")).end()
				.addClass("top");
			$("#reblog-post span.noshow").clone()
				.removeClass("noshow")
				.appendTo(el)
				.find("a").click(function (ev) {
					ev.preventDefault();
				});
		}
		el.parent().addClass("hover").css("z-index", 2);
		if (el.parent().next('.attribution').size() === 1) {
			h = $('#reblog-post-content').height() - $('#reblog-post').height() + el.parent().find('.top').outerHeight() - el.parent().height();
			el.parents('#reblog-post').scrollTop(h);
		}
	}
	function onContentOut(ev) {
		$(this).parent().removeClass("hover").css("z-index", 1);
	}
	function findContentWrapper(elm) {
		var p = null;
		while (elm) {
			p = elm.parentNode;
			if (p.tagName.toLowerCase() === 'div' && p.className.indexOf('wrapped') >= 0) {
				return elm;
			}
			elm = p;
		}
		return null;
	}
	function createQuote(elm, intro) {
		if (!elm) {
			return '';
		}
		var tag = elm.tagName.toLowerCase() === 'blockquote'? 'p' : elm.tagName.toLowerCase(), quote = '';
		quote = $(elm.cloneNode(true))
			.find("span").css({
					'text-align': 'right',
					'display': 'block',
					'width': '100%',
					'padding': '1em 0'
				}).addClass("zemanta-reblog-cite").end()
			.html();
		quote = '<' + tag + (intro? ' class="zemanta-reblog-cite"' : '') + '>' + quote + '</' + tag + '>';
		quote = '<blockquote id="zemblockquote" class="zemanta-reblog-quote" style="margin:1em 3em;" cite="' + $("span a", elm).attr('href') + '">' + quote + '</blockquote>';
		return quote;
	}
	function updateEditor(paragraph, intro) {
		var quote = createQuote(paragraph, intro),
			newBQ = null,
			edWin = $("#content_ifr")[0].contentWindow,
			editor = edWin.document.body,
			existingBQ = edWin.document.getElementById("zemblockquote");
		// Non-obvious way of doing things on account of IE, which
		// doesn't let nodes originating in one document be attached to other
		if (existingBQ) {
			newBQ = edWin.document.createElement("div");
			newBQ.innerHTML = quote;
			newBQ = newBQ.firstChild;
			existingBQ.parentNode.replaceChild(newBQ, existingBQ);
		} else {
			editor.innerHTML = "<p>I found this fascinating quote today:</p>" + quote + "<p>You should read the whole article.</p>";
		}
		Zemanta.control.update();
		$(edWin).focus();
	}
	function onContentClick(ev) {
		$(this)
			.parent()
				.parent()
					.find(".selected").removeClass("selected").end()
					.end()
				.end()
			.addClass("selected");
		var t = findContentWrapper(this);
		enablePublish();
		updateEditor(t);
		animateOpen();
	}
	function animateOpen() {
		//return $('body').addClass('extended'); // use this if no animation needed
		var done = 0, handlers = [],
			oneDone = function () {
				done -= 1;
				if (done === 0) {
					$.each(handlers, function () {
						this();
					});
				}
			},
			addAnim = function (h) {
				var fn = h;
				if (typeof h === 'string') {
					fn = function (h) {
						return function () {
							$(h).css({display: ""});
						};
					}(h);
				}
				handlers.push(fn);
				done += 1;
			},
			p = $('#reblog-post').position(),
			pp = $('#publisher').position(),
			h0 = 0, h1 = 0,
			editor = $('#reblog-editor'),
			tdiff = 0, sp = null;
		handlers.push(function () {
			$('body').addClass('extended');
		});
		// hide post
		h0 = $('#reblog-post').height();

		// switch displays, to get diff in height (margin + other stuff)
		$('#reblog-post').css({display: 'none'});
		editor.css({opacity: 0, display: 'block', overflow: 'hidden'});
		h1 = editor.height();

		editor.css({height: h0});
		tdiff = pp.top - $('#publisher').position().top;
		editor.css({height: h0 + tdiff});

		addAnim('#reblog-post');
		$('#reblog-post').css({display: 'block', position: 'absolute',left: p.left, top: p.top}).animate({opacity: 0}, function () {
			$(this).css({display: 'none', position: '', left: '', top: '', opacity: ''});
			oneDone();
		});

		// show editor
		addAnim('#reblog-editor');
		editor.animate({opacity: 1, height: h1, paddingRight: 238, paddingLeft: 18, width: 464}, 'slow', function () {
			$(this).css({opacity: '', height: '', overflow: '', paddingRight: '', paddingLeft: '', width: ''});
			oneDone();
		});

		// show sidebar
		addAnim('#sidebar');
		$('#sidebar').css({marginLeft: 220, opacity: 0, display: 'block'}).animate({marginLeft: 140, opacity: 1}, function () {
			$(this).css({opacity: '', marginLeft: ''});
			oneDone();
		});
		
		sp = $('#selectaquote').position();
		// hide selecte a quote
		addAnim('#selectaquote');
		$('#selectaquote').css({position: 'absolute', left: sp.left, top: sp.top}).animate({opacity: 0}, 'slow', function () {
			$(this).css({display: 'none', position: '', left: '', top: '', opacity: ''});
			oneDone();
		});
		// show pick another quote
		addAnim('#pickanother');
		$('#pickanother').css({display: 'block', opacity: 0, marginLeft: sp.left}).animate({opacity: 1, marginLeft: 0}, function () {
			$(this).css({width: '', marginLeft: '', opacity: ''});
			oneDone();
		});
	}
	function animateClose() {
		//return $('body').removeClass('extended'); // use this when no animation needed
		var done = 0, handlers = [],
			oneDone = function () {
				done -= 1;
				if (done === 0) {
					$.each(handlers, function () {
						this();
					});
				}
			},
			addAnim = function (h) {
				var fn = h;
				if (typeof h === 'string') {
					fn = function (h) {
						return function () {
							$(h).css({display: ""});
						};
					}(h);
				} else {
					fn = h;
				}
				handlers.push(fn);
				done += 1;
			},
			p = $('#reblog-editor').position(), ap = null, sp = null,
			h1 = 0;
		handlers.push(function () {
			$('body').removeClass('extended');
		});
		
		h1 = $('#reblog-post').css({position: 'absolute', opacity: 0, display: 'block'}).height() + 18;
		ap = $('#pickanother').position();
		sp = $('#selectaquote').css({display: 'block', opacity: 0}).position();
		
		// hide editor
		addAnim(function () {
			$('#reblog-editor').css({display: '', opacity: '', height: '', overflow: '', paddingRight: '', paddingLeft: '', width: ''});
		});
		$('#reblog-editor').css({overflow: 'hidden'}).animate({opacity: 0, height: h1, paddingRight: 0, paddingLeft: sp.left, width: 500}, 'slow', function () {
			oneDone();
		});
		
		// show post
		addAnim(function () {
			$('#reblog-post').css({position: '', left: '', top: '', opacity: ''});
		});
		$('#reblog-post').css({left: p.left, top: p.top}).animate({opacity: 1, left: sp.left}, function () {
			oneDone();
		});
		
		// hide sidebar
		addAnim('#sidebar');
		$('#sidebar').animate({marginLeft: 220, opacity: 0}, function () {
			$(this).css({display: 'none', opacity: '', marginLeft: ''});
			oneDone();
		});
		
		// hide selecte a quote
		addAnim('#pickanother');
		$('#pickanother').css({position: 'absolute', left: ap.left, top: ap.top}).animate({left: sp.left, opacity: 0}, 'slow', function () {
			$(this).css({position: '', left: '', top: '', opacity: '', display: 'none'});
			oneDone();
		});
		// show pick another quote
		addAnim('#selectaquote');
		$('#selectaquote').css({width: '100%', marginLeft: 0}).animate({marginLeft: sp.left, opacity: 1}, 'slow', function () {
			$(this).css({width: '', marginLeft: '', opacity: ''});
			oneDone();
		});
	}
	function enablePublish() {
		$('#publisher fieldset.submit')
			.removeClass('disabled')
			.find('#copy-html, #publish-now').removeClass('disabled').attr('title', '').end()			
			.find('#publish-now').attr('disabled', '').end();
	}
	
	// select text
	function selectField() {
		$(this).select();
	}
	
	// copy
	function copyHTML(ev) {
		ev.preventDefault();
		if ($(this).hasClass('disabled')) {
			return;
		}
		var v = getValues();
		openOverlay('<div id="overlay-message"><h2>Copy HTML to your blog</h2><form action="#" method="get"><fieldset><textarea id="html-code" cols="30" rows="10"></textarea><button id="close-overlay">Close</button></fieldset></form><div id="promotion"><h3>You can get Zemanta recommendations for your blog for <em>free</em>! <a href="http://www.zemanta.com/download/" rel="external">Download here.</a></h3><p>We support all the popular blogging platforms<br /><img src="/smedia/reblog/platforms.gif" alt="All the popular blogging platforms" /></div><iframe src="/stats/copyhtml/" style="height:1px;width:1px;border:0;overflow:hidden;visibility:hidden;"></iframe></div>');
		setTimeout(function () {
			var c = $('#html-code');
			c.val(v.post);
			c.focus(selectField).click(selectField);
		}, 1);
	}
	
	// post
	function postData(ev) {
		if ($(this).hasClass('disabled')) {
			return;
		}
		function cmpl(html, textStatus) {
			if (textStatus === 'success') { // successful response from server
				$("#message").html(html);
				if (document.getElementById('success')) { // successfully posted to blog
					$("#reblog-form").hide();
					if (document.referrer) {
						$("p.back a").attr({href: document.referrer});
					} else {
						$("#overlay-message #message p").not('.fwd').not('.sorry').remove();
					}
					$('#publish-post').hide();
				} else {
					$('#publish-post').html('Retry');
				}
			} else {
				// do something for error
				$('#publish-post').html('Retry');
			}
			$("#publish-now").html('&nbsp;Publish to your blog!&nbsp;');
			var cl = $('#zemanta-overlay-content h2 a.close');
			$('#zemanta-overlay-content h2').get(0).innerHTML = ''; // don't do .html('') or .remove() as that removes event handlers from cl
			$('#zemanta-overlay-content h2').removeClass('loading').html($('#zemanta-overlay-content p.sorry').remove().html()).append(cl);
			$("#message").removeClass('noshow');
			setTimeout(resizeOverlay, 10);
		}
		ev.preventDefault();
		if ($("#publish-now").html().indexOf('Publish to your blog!') < 0) {
			return;
		}
		// hide possible error message
		$("#message").slideUp("normal");
		// set up loading
		$("#publish-now").html('Publishing...');
		// overlay
		var d = openOverlay('<div id="overlay-message"><h2>Publish directly to your blog</h2><div id="message" class="noshow"></div><form id="reblog-form" action="/publish/" method="post" class="publish"><fieldset class="data"><input type="hidden" id="blogtitle" name="title" value="" /><input type="hidden" id="blogpost" name="content" value="" /><input type="hidden" id="blogtags" name="tags" value="" /><ul><li><label for="blog_url"><span>Blog address:</span></label><input type="text" id="blog_url" name="blog_url" /><p id="publish_disclaimer" class="disclaimer">Example: yourblog.blogspot.com</p></li><li><label for="username"><span>Blog username:</span></label><input type="text" id="username" name="username"/></li><li><label for="password"><span>Blog password:</span></label><input type="password" id="password" name="password" /><p class="disclaimer">We will not store your username or password &#8212; ever.</p></li></ul></fieldset><fieldset class="submit"><button id="publish-post">Publish!</button><span> or </span><a id="close-overlay" class="secondary">Close</a></fieldset></form><div id="promotion"><h3>You can get Zemanta recommendations for your blog for <em>free</em>! <a href="http://www.zemanta.com/download/" rel="external">Download here.</a></h3><p>We support all the popular blogging platforms<br /><img src="/smedia/reblog/platforms.gif" alt="All the popular blogging platforms" /></div><iframe src="/stats/publishnow/" style="height:1px;width:1px;border:0;overflow:hidden;visibility:hidden;"></iframe></div>'),
			v = getValues();
		d
			.find("#blog_url").unbind("blur").blur(function() {
				$.post("/ajax/", {method: "check_blog", blog_url: $("#blog_url").val()}, function(data, textStatus) {
					$("#blog_url_error").remove();
					if (data && data.message) {
						$("#blog_url").after('<div id="blog_url_error" class="disclaimer formerror">' + data.message + '</div>');
						$("#blog_url").css("background", "#ffc3c3");
						$("#publish_disclaimer").html('');
					} else {
						$("#blog_url").css("background", "#c3ffc3");
						$("#publish_disclaimer").html('We can publish to your blog!');
					}
				}, "json");
			}).end()
			.find('#blogtitle').val(v.title).end()
			.find('#blogpost').val(v.post).end()
			.find('#close-overlay, a.close').click(function () {
				$("#publish-now").html('&nbsp;Publish to your blog!&nbsp;');
			}).end()
			.find('#publish-post').click(function (ev) {
				ev.preventDefault();
				$(this).html('Publishing ...');

				// check form validity
				if ($('#blogpost').val() === '') {
					setTimeout(function () {
						cmpl('<p class="sorry">You didn&#146;t write anything!</p><p>We cannot publish an empty post. Close this window, pick a quote and write a post about it. Than try publishing again.</p>', 'success');
					}, 50);
					return;
				}
				if ($('#blog_url').val() === '' || $('#username').val() === '') {
					setTimeout(function () {
						cmpl('<p class="sorry">You didn&#146;t specify blog data!</p><p>We cannot publish the post to your blog if you do not specify the address, username and password. You can also copy the HTML to your blog publishing platform by hand.</p>', 'success');
					}, 50);
					return;
				}
				// get fields and serialize
				var fields = $("#reblog-form :input").serializeArray();
				// post
				$.ajax({
					type: 'post',
					url: $('#reblog-form').attr('action'),
					data: fields,
					success: cmpl,
					error: cmpl
				});
			});	
	}
	// overlay
	var resizeOverlay = null;
	// open overlay
	function openOverlay(content) {
		var setupTimer,
			contentDiv = null,
			overlay = null;
		function resize() {
			var h = $("#overlay-message").height(),
				bh = $("body").height(),
				t = 0, p = {};
			t = Math.floor((bh - h) / 2);
			p = {
				top: '50%',
				marginTop: '-' + Math.ceil(h / 2) + 'px',
				height: h + 'px'
			};
			overlay.css({
				height: Math.max($("html").innerHeight(), $("body").innerHeight()) + 'px'
			});
			contentDiv.animate(
				p,
				300,
				function () {
					$("#close-overlay").unbind('click').bind('click', closeOverlay);
				}
			);
		}
		resizeOverlay = resize;
		function closeOverlay(ev) {
			if (ev) {
				ev.preventDefault();
			}
			$("#publish-now").html('&nbsp;Publish to your blog!&nbsp;');
			clearTimeout(setupTimer);
			contentDiv.add(overlay).fadeOut(300, function () {
				contentDiv.add(overlay).remove();
			});
		}
		function insertContent(data) {
			// set content and resize
			var c = contentDiv.empty().css({top: '0%'}),
				d = $(data)
						.find('h2:first')
							.append(
								$('<a href="#close" class="close">x</a>').click(function (ev) {
									ev.preventDefault();
									closeOverlay();
								})
							)
							.end()
						.find('a[rel=external]').click(function (ev) {
							window.open(this.href);
							ev.preventDefault();
						}).end()
						.appendTo(c);
			resize();
			return d;
		}
		// setup the overlay
		function setup() {
			overlay = $('<div id="zemanta-overlay"></div>');
			contentDiv = $('<div id="zemanta-overlay-content"><h2>Loading...</h2></div>');
			overlay.css({
				height: Math.max($("html").innerHeight(), $("body").innerHeight()) + 'px',
				opacity: 0.6
			});
			$("body")
				.append(overlay)
				.append(contentDiv);
		}
		setup();
		return insertContent(content);
	}

	$(function () {
		// external links
		$('a[rel=external]').click(function (ev) {
			window.open(this.href);
			ev.preventDefault();
		});
	
		// hide alert
		$("#reblog-alert").addClass("noshow");
	
		// attach events to the content
		$("#reblog-edit")
			.find("#reblog-post-content > P, #reblog-post-content > UL, #reblog-post-content > OL, #reblog-post-content > PRE, #reblog-post-content > BLOCKQUOTE, #reblog-post-content > DL")
				.bind('mouseout', function (ev) {
					var t = this;
					ev.preventDefault();
					$(this).data('timer', setTimeout(function () {
						onContentOut.call(t);
					}, 10));
				})
				.bind('mouseover', function (ev) {
					clearTimeout($(this).data('timer'));
					onContentOver.call(this, ev);
				})
				.click(onContentClick)
				.find("a").click(function (ev) {
					ev.preventDefault();
				});
	
		// attach to action buttons
		$('#publisher fieldset.submit')
			.addClass('disabled')
			.find('#publish-now, #copy-html').attr('title', 'You must select a paragraph before you can post it to your blog...').addClass('disabled').end()
			.find("#publish-now").attr('disabled', 'disabled').click(postData).end()
			.find("#copy-html").click(copyHTML).end();

		// extend
		/*$('#addcomment').click(function () {
			animateOpen();
			//$('body').addClass('extended');
		});*/
		// closed
		$('#pickanother a').click(function () {
			animateClose();
		});
		
		// set default text if empty
		(function () {
			var c = '', l = 0;
			if (tinyMCE.activeEditor) {
				c = tinyMCE.activeEditor.getContent();
				l = c.length === 0? 0 : $(c).text().length;
				if (l < 50) {
					updateEditor($("<p>[ Add suggested images and related articles from the right and links and tags from bellow. ]</p>").get(0), true);
				}
			} else {
				setTimeout(arguments.callee, 10);
			}
		})();
		
		// load zemanta
		experience();
		
		// check if only one paragraph - click directly
		// have to be sure everything is present...
		var tries = 0;
		setTimeout(function () {
			try {
				if ($('#reblog-post-content').children(':not(span)').size() === 1 && window.tinyMCE && window.tinymce) {
					var e = $('#reblog-post-content').children(':not(span)').get(0);
					onContentOver.call(e);
					onContentClick.call(e);
					onContentOut.call(e);
					$('#pickanother').html('&nbsp;').unbind('click');
				}
			} catch (er) {
				tries += 1;
				if (tries < 10) {
					setTimeout(arguments.callee, 100);
				}
			}
		}, 100);
		
		// trigger resize	
		//window.onresize();
		
		// set resizing interval
		/*setInterval(function () {
			var h = $("#reblog-editor form").height();
			if (window.setheight != h) {
				window.setheight = h;
				window.onresize();
			}
		}, 500);*/
	});
	
	// set onresize handler
	/*window.onresize = function () {
		clearTimeout(window.resizeTimer);
		window.resizeTimer = setTimeout(function () {
				window.zQuery("#reblog-post").css("height", Math.min($(window).height() - 20, window.setheight - 2));
			}, 500);
	};*/
})();
