$(function () {
	//preload any stored code
    $('#editor').val($.cookie('justTyped'));
    $('#printOut').text($.cookie('justTyped'));
    //fire off our editor
    $('#editor').wysiwyg();
    
	//store code on closing the window
	$(window).unload( function () { 
		// assign it to a name
		var code = $('textarea#editor').val();
		$.cookie('justTyped', code, { path: '/', expires: 1 });	 
	});

	//store the iframes location
    var iframe = $('#editorIFrame')[0];
    // wait for frame load event
    iframe.attachEvent ? iframe.attachEvent('onload', cb) :
	iframe.addEventListener('load', cb, false); 
	
	// onload callback for iframe
	function cb() {
		// get iframe's document
		var doc = iframe.contentWindow ? iframe.contentWindow.document :
		iframe.contentDocument ? iframe.contentDocument : iframe.document;
		var $frameDiv = $('body',doc);
		$('#printOut').text($frameDiv.html());
	};
	
	function emptyEditor() {
		// get iframe's document
		var doc = iframe.contentWindow ? iframe.contentWindow.document :
		iframe.contentDocument ? iframe.contentDocument : iframe.document;
		var $frameDiv = $('body',doc);
		$('#printOut').empty();
	};
	
	//grab the code	
	$('#getCode').click(function() {
		cb();
	});
	//clear the code
	$('#clearCode').click(function() {
		emptyEditor();
	    $('#printOut').text('');
	    //finally delete the cookie
	    $.cookie('justTyped', null);
	});
});

