var valueSpan;
var hasTitle = false;
var titleSpan;
var titleId;
var formContents;
var titleContents;
var changeSaved = false;
var blurbContext = "";
var isUserCreatedPage = false;
var wymoptions;
var wymtitleoptions;
var inlineoptions;

$(document).ready(function() {

	if ($("#usercreatedtitle").size() > 0)
		isUserCreatedPage = true;

	if ($("#hiddenContext").size() > 0) {
		blurbContext = $("#hiddenContext").html();
	}

	wymoptions = {
		logoHtml: '',
		boxHtml: "<div class='wym_box'>"
			+ "<div class='wym_area_top'>" 
			+ WYMeditor.TOOLS
			+ WYMeditor.CONTAINERS
			+ WYMeditor.CLASSES
			+ "</div>"
			+ "<div class='wym_area_main'>"
			+ WYMeditor.HTML
			+ WYMeditor.IFRAME
			+ WYMeditor.STATUS
			+ "</div>"
			+ "</div>",
		containersHtml: "<div class='wym_containers wym_section'>"
			+ "<h2>Format</h2>"
			+ "<ul>"
			+ WYMeditor.CONTAINERS_ITEMS
			+ "</ul>"
			+ "</div>",
		classesHtml: "<div class='wym_classes wym_section wym_dropdown'>"
			+ "<h2>Custom styles <span>&nbsp;></span></h2><ul>"
			+ WYMeditor.CLASSES_ITEMS
			+ "</ul></div>",
		classesItems: [
			{'name': 'circle', 'title': 'Bullet:circle', 'expr': 'ul'},
			{'name': 'square', 'title': 'Bullet:square', 'expr': 'ul'}
		]											            					
	};

	inlineoptions = {
		logoHtml: '',
		inline: true,
		boxHtml: "<div class='wym_box'>"
			+ "<div class='wym_area_top'>" 
			+ WYMeditor.TOOLS
			+ "</div>"
			+ "<div class='wym_area_main'>"
			+ WYMeditor.HTML
			+ WYMeditor.IFRAME
			+ WYMeditor.STATUS
			+ "</div>"
			+ "</div>",
		toolsItems: [
		    {'name': 'Bold', 'title': 'Strong', 'css': 'wym_tools_strong'}, 
			{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
			{'name': 'Superscript', 'title': 'Superscript', 'css': 'wym_tools_superscript'},
			{'name': 'Subscript', 'title': 'Subscript', 'css': 'wym_tools_subscript'},
			{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
			{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'},
	        {'name': 'CreateLink', 'title': 'Link', 'css': 'wym_tools_link'},
	        {'name': 'Unlink', 'title': 'Unlink', 'css': 'wym_tools_unlink'},
	        {'name': 'InsertImage', 'title': 'Image', 'css': 'wym_tools_image'},
 		    {'name': 'ToggleHtml', 'title': 'HTML', 'css': 'wym_tools_html'},
 			{'name': 'Preview', 'title': 'Preview', 'css': 'wym_tools_preview'}
		]
	};
	
	if (isUserCreatedPage){
	
		wymtitleoptions = {
			logoHtml: '',
			inline: true,
			boxHtml: "<div class='wym_box'>"
				+ "<div class='wym_area_top'>" 
				+ WYMeditor.TOOLS
				+ "</div>"
				+ "<div class='wym_area_main'>"
				+ WYMeditor.HTML
				+ WYMeditor.IFRAME
				+ WYMeditor.STATUS
				+ "</div>"
				+ "</div>",
			toolsItems: [
				{'name': 'Italic', 'title': 'Emphasis', 'css': 'wym_tools_emphasis'},
				{'name': 'Superscript', 'title': 'Superscript', 'css': 'wym_tools_superscript'},
				{'name': 'Subscript', 'title': 'Subscript', 'css': 'wym_tools_subscript'},
				{'name': 'Undo', 'title': 'Undo', 'css': 'wym_tools_undo'},
				{'name': 'Redo', 'title': 'Redo', 'css': 'wym_tools_redo'}
			]
		};
	}
	

	//Change the cursor over the edit spans so they behave more like links
	$(".blurb-editor").css({"cursor":"pointer"});
	
	if ($("#removePage").size() == 1)
		$("#removePage span").css({"cursor":"pointer"});
	
	//Add divs to the page body that will be used for the popup, preview bar and edit confirmation bar.
	$("body").append("<div id=\"blurbeditpopup\"></div>");
	$("body").prepend("<div id=\"blurbeditpreview\"><div><span><button type=\"button\" class=\"ui-state-default ui-corner-all\" id=\"previewpublish\">Publish</button> <button type=\"button\" class=\"ui-state-default ui-corner-all\" id=\"previewedit\">Edit</button> <button type=\"button\" class=\"ui-state-default ui-corner-all\" id=\"previewcancel\">Cancel</button></span><p>PREVIEW</p></div></div><div id=\"blurbeditconfirm\"><div><span><button type=\"button\" class=\"ui-state-default ui-corner-all\" id=\"publishedok\">OK</button></span><p>Your changes have been published</p></div></div><div id=\"blurbremoveconfirm\"><div><span><button type=\"button\" class=\"ui-state-default ui-corner-all\" id=\"removedok\">Home</button></span><p>This page has been removed</p></div></div><div id=\"blurbeditspacer\"> </div>");

//	$(".blurb-editor").hover(
//		function () {
//			$(this).parent("span").addClass("blurbhighlight");
//		}, 
//		function () {
//			$(this).parent("span").removeClass("blurbhighlight");
//		}
//	);
	
	
	//Define the behaviour associated with clicking an edit link
	$(".blurb-editor").click(function() {
		valueSpan = $(this).prev("span");
		var valueId = $(valueSpan).attr("id");
		var valueId_split = valueId.split(".");
		var page="";
		for (var i=2; i<valueId_split.length-2; i++){
			if (page != "")
				page = page + ".";
			page = page + valueId_split[i];			
		}
		var key = valueId_split[valueId_split.length-2];
		var locale = valueId_split[valueId_split.length-1];
		var text = $(valueSpan).html();
		
		titleSpan = $(this).prevAll("span.blurb-title");
		titleId = $(this).prevAll("span.blurb-title-id").text();
		hasTitle = (titleSpan.size() > 0);
        var title = titleSpan.html();
		
		var data = {'content.namespace': page, 'content.key': key, 'content.locale': locale, 'content.text': text, 'content.title': title, hasTitle: hasTitle};

 		var blurburl = blurbContext + "/blurb";
		$.post(blurburl, data, function(resp) {	
			try{
				//alert(resp);
				$("#blurbeditpopup").html(resp);
				fmt = $("#editform_content_format").val();
				var bodyoptions = wymoptions;
				if (fmt == "plain")
				{
					$("#blurbeditpopup .textarea-wrap .wymeditor").val($(valueSpan).text());
					if (hasTitle)								
						$("#blurbeditpopup .title-wrap .wymeditor").val(title);
				}
				else {
					if (fmt == "inline")
						bodyoptions = inlineoptions;
					
					$("#blurbeditpopup .textarea-wrap .wymeditor").wymeditor(bodyoptions);
					if (isUserCreatedPage)								
						$("#blurbeditpopup .title-wrap .wymeditor").wymeditor(wymtitleoptions);
				}
			    $("#blurbeditpopup").dialog("open");
					
			} catch(e) {
				alert("Edit request failed: " + e );
			}
		});
		return false;		
	});
	
	$("#removePage span").click(function() {
		if (confirm("Remove this page?")) {
			f = $("#removePage");
			$.post(f.attr("action"), f.serialize(), function(data) {
				$("#blurbeditspacer").slideDown();
				$("#blurbremoveconfirm").slideDown();
			});
		}		
	});
		
	$("#previewcancel").click(function() {
		blurb_restore(this, false);
	});
	
	$("#previewedit").click(function() {
		blurb_restore(this, true);
	});
	
	$("#previewpublish").click(function() {
		blurb_publish();
	});
	
	$("#publishedok").click(function() {
		$("#blurbeditconfirm").slideUp();
		$("#blurbeditspacer").slideUp();
		location.reload(true);	
	});
		
	$("#removedok").click(function() {
		$("#blurbremoveconfirm").slideUp();
		$("#blurbeditspacer").slideUp();
		document.location = blurbContext + "/";		
	});

	//Initialise the popup for the edit	form
	$("#blurbeditpopup").dialog({
		autoOpen:false,
		height:400,
		width:700,
		modal: true,
		title: 'Edit this text',
		buttons: {
			'Cancel': function() {
				$(this).dialog('close');
			},
			'Preview': function() {
				blurb_preview(this, true);
			},
			'Publish': function() {
				blurb_publish(this);
			}
		}
	});
	
   $("#locale_change").click(function() {
      var f = $(this).parent();
      var data = {locale: $("#locale_form select[name=locale] option:selected").attr("name")};
      
      $.post(f.attr("action"), data, function(resp) {
         window.location.href = window.location.href;
      });
      return false;
   });
});

var removeEndingBr = function(element){
	if (element.length > 5) {
		if (element.substring(element.length-6, element.length) == "<br />")
			return element.substring(0, element.length-6);
		else
			return element;
	}
}

function blurb_preview(src, showBanner) {
	if (showBanner) {
		$("#blurbeditspacer").slideDown();
		$("#blurbeditpreview").slideDown();
	}
	
	fmt = $("#editform_content_format").val();
	$(".wymupdate").click();
	if (fmt != "pageFragment")				
		$('.wymeditor').each(function() {$(this).val(removeEndingBr($(this).val()))});		
	//$('.wymeditor').each(function() {if($(this).val() == "<br />")$(this).val("");});				
	formContents = $("#editform").find(".textarea-wrap").find("textarea").val();
	titleContents = $("#editform").find(".title-wrap").find("textarea").val();
	//alert(formContents)
	$("#editform .textarea-wrap .wym_box").remove();
	
	if (fmt == "plain") {
	   $(valueSpan).parent("span").append("<div class=\"blurbhidden\">" + $(valueSpan).text() + "</div>");
	   $(valueSpan).text(formContents);
	}
	else {
	   $(valueSpan).parent("span").append("<div class=\"blurbhidden\">" + $(valueSpan).html() + "</div>");
	   $(valueSpan).html(formContents);
	}
	
	if (hasTitle && (titleId != null)) {
		t = $("#" + titleId);
		$(valueSpan).parent("span").append("<div class=\"titlehidden\">" + t.html() + "</div>");
		t.html(titleContents);
	}
	
	$(".blurb-editor").hide();
	
	//For user created pages
	if (isUserCreatedPage) {
		$("#editform .title-wrap .wym_box").remove();
		$(valueSpan).parent("span").append("<div class=\"titlehidden\">" + $("title").html() + "</div>");
		//$("title").html(titleContents);
		if ($("#pagetitle").size() > 0)
			$("#pagetitle").html(titleContents);
		else
			$("#usercreatedtitle").before("<h2 id='pagetitle'>" + titleContents + "</h2>");
		$("#removePage span").hide()
	}
	$(src).dialog('close');
}

function blurb_restore(src, invokeEditor) {
	$("#blurbeditpreview").slideUp();
	$("#blurbeditspacer").slideUp();
	//alert(formContents);
	$("#editform").find(".textarea-wrap").find("textarea").val(formContents);
	$("#blurbeditpopup .textarea-wrap .wymeditor").unbind('wymeditor');
	var bodyoptions = wymoptions;
	fmt = $("#editform_content_format").val();
	if (fmt == "plain")
	{
		$("#blurbeditpopup .textarea-wrap .wymeditor").val($(valueSpan).text());
		if (hasTitle) {
			$("#blurbeditpopup .title-wrap .wymeditor").val($(titleSpan).text());
			if (titleId != null) {
				t = $("#" + titleId);
				h = $(".titlehidden");
				t.html(h.html());
				h.remove();
			}
		}
	    $(valueSpan).text($(".blurbhidden").text());
	}
	else {
		if (fmt == "inline")
			bodyoptions = inlineoptions;
		
		$("#blurbeditpopup .textarea-wrap .wymeditor").wymeditor(bodyoptions);				
		if (isUserCreatedPage) {
			$("#blurbeditpopup .title-wrap .wymeditor").unbind('wymeditor');
			$("#blurbeditpopup .title-wrap .wymeditor").wymeditor(wymtitleoptions);
			$("#editform").find(".title-wrap").find("textarea").val(titleContents);
			$("#pagetitle").html($("#usercreatedtitle").html());
			$("#removePage span").show();
		}
	    $(valueSpan).html($(".blurbhidden").html());
	}
	$("#editform").find(".title-wrap").find("textarea").val(titleContents);
    $(".blurbhidden").remove();	    
	$(".blurb-editor").show();
	
	if (invokeEditor)
       $("#blurbeditpopup").dialog("open");
}

function blurb_publish(src) {
	blurb_preview(src, false);
	$("#blurbeditpreview").slideUp();
	$("#blurbeditspacer").slideUp();
	
	fmt = $("#editform_content_format").val();
	$(".wymupdate").click();
	if (fmt != "pageFragment")
		$('.wymeditor').each(function() {$(this).val(removeEndingBr($(this).val()))});
	//$('.wymeditor').each(function() {if($(this).val() == "<br />")$(this).val("");});				
	blurbpublishurl = $("#editform").attr("action");
	data = $("#editform").serializeArray();
	formContents = $("#editform").find(".textarea-wrap").find("textarea").val();
	titleContents = $("#editform").find(".title-wrap").find("textarea").val();
	
	$.post(blurbpublishurl, data, function(resp) {	
		try{
			$("#blurbeditspacer").slideDown();
			$("#blurbeditconfirm").slideDown();
			$("#editform .textarea-wrap .wym_box").remove();
			
			if (fmt == "plain")
			   $(valueSpan).text(formContents);
			else
			   $(valueSpan).html(formContents);
			
			if (hasTitle && (titleId != null))
				$(titleId).html(titleContents);
			
			if (isUserCreatedPage) {

				if ($("#pagetitle").size() > 0)
					$("#pagetitle").html(titleContents);
				else
					$("#usercreatedtitle").before("<h2 id='pagetitle'>" + titleContents + "</h2>");							
			}
			
			if (src)
			   $(src).dialog('close');
			
		} catch(e) {
			alert("Publish request failed: " + e );
		}
	});
}

