/* Script for TK Content Management Lite *
 * Jeff Nadeau - 2008 - jeff at typekastdesign dot com */
 
	
	// String functions for trimming, thanks to 
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g,"");
	}
	String.prototype.ltrim = function() {
		return this.replace(/^\s+/,"");
	}
	String.prototype.rtrim = function() {
		return this.replace(/\s+$/,"");
	}
 
 
var editingActive = false;
var isAdmin = false;
var state_commands = [ "bold","italic","underline" ];

$(document).ready(function(){
	if(isAdmin){
		$('#c_main').dblclick(startEditing);
	}
});

$(window).resize(function(){
	alignAdminLogin();
	alignDrop();
	alignCenterWrapper();
	vertCenter(".vert_center");
});

$(window).scroll(function(){
	alignAdminLogin();
	alignDrop();
	alignCenterWrapper();
	vertCenter(".vert_center");
});


/********************************************************************
                       Rich Text Editor
**********************************************************************/

function startEditing(){
	if(!editingActive){
		editingActive = true;
				
		$('#c_main').slideUp("normal",function(){
			$('#c_editor').slideDown("normal", function(){
				$('#editor').contents().find("body").html($('#c_main').html());
			});
		});
		
		$('#editor').designMode();
		$('#editor').contents().keydown(editorKeyListener);
		$('#editor').focus();
		$('#editor').contents().select();

		initEditorTools();
	}
}

function initEditorTools(){
	$('#editor').contents().find("body").click(checkEditTools);
	// the editorkeylistener has a line for this check
	
	$('#edittools').css("opacity","0");
	$('#edittools').css("display","block");
	$('#edittools').fadeTo("slow",0.95);
	$('#edittools').draggable({opacity:0.85, handle:"#edittools_dragbar", containment: "document"});
	$('.etool').click(useEditTool);
}

function submitEdit(){
	var scriptURL = $('#sitePath').val() + "/rte/page_edit.php";
	var pageId = $('#pageId').val();
	var contents = $('#editor').contents().find("body").html();
	$.post(scriptURL, { pageId: pageId, pageContent: contents }, function(data){
		switch(data){
			case "success":
				contents = contents.replace('../uploads/',$('#sitePath').val()+'/uploads/');
				
				$('#c_main').html(contents);
				$('#c_editor').slideUp("normal",function(){
					$('#c_main').slideDown("normal");
				});
				$('#edittools').fadeOut("slow");				
				
				editingActive = false;
				
				$("<div id='page_updated'></div>").appendTo("body");
				$("#page_updated").animate({top:"20px"}, 750, "linear", function(){
					setTimeout('$("#page_updated").fadeOut(750, function(){ $("#page_updated").remove();})', 1500);
				});
				
			break;
			case "unauthorized":
				alert("ERROR: You are not authorized to make edits. Please make sure you are logged in.");
			break;
			default: //this encompasses "failure" or any other problem.
				alert("There was an error submitting the page edit. Try again soon - if the problem persists, contact jnadeau.");
			break;
		}
	});
}

function revertEdit(){
	if(confirm("Are you sure you want to revert this page? Changes since you began editing will be lost.")){
		$('#editor').contents().find("body").html($('#c_main').html());
	} else {
		alert("Ok. Don't worry, no action has been taken!");
	}
}

function cancelEdit(){
	if(confirm("Are you sure you want to cancel this edit? Changes since you began editing will be lost.")){
		$('#editor').contents().find("body").html($('#c_main').html());
		$('#c_editor').slideUp("normal",function(){
			$('#c_main').slideDown("normal");
		});
		$('#edittools').fadeOut("slow");
		editingActive = false;
	} else {
		alert("Ok. Don't worry, no action has been taken!");
	}
}

function useEditTool(){
	var highlight = false;
	switch(this.rel){
		case "forecolor":
			var pickedcolor = prompt("What color would you like the text to be? (Can be a color name like 'red' or a color code like '#FF0000')","");
			if(pickedcolor) $('#editor').execCommand(this.rel, pickedcolor); // if they leave it blank nothing happens at all.
		break;
		case "heading":
			$('#editor').execCommand(this.rel, "<h2>");	
		break;
		case "createlink":
			if(getEditorSelection().length > 0){
				var myurl = prompt("Where do you want to link to?","http://");
				$('#editor').execCommand(this.rel, myurl);	
			} else {
				alert("Please select some text to turn into a link first.");
			}
		break;
		case "insertimage":
			setupInsertImage();
		break;
		case "inserthtml":
			setupInsertHTML();
		break;
		default: //"bold", "italic", "underline", "unlink", "insertparagraph", "insertorderedlist", "insertunorderedlist", "increasefontsize", "decreasefontsize":
			$('#editor').execCommand(this.rel);
		break;
	}
	
	if($.inArray(this.rel, state_commands) >= 0){ //wont test this unless it's a command we want to query state on.
		if($('#editor').contentDocument().queryCommandState(this.rel)){
			$(this).addClass('etool_active');
		} else {
			$(this).removeClass('etool_active');
		}
	}
	return false;
}

function checkEditTools(e){
	var doc = $('#editor').contentDocument();
	$.each(state_commands, function(){
		if(doc.queryCommandState(this)){
			$('#edittools .' + this).addClass("etool_active");
		} else {
			$('#edittools .' + this).removeClass("etool_active");
		}
	});
}

function editorKeyListener(e){
	checkEditTools();
 	var key;
	var ctrl;
	if(window.event){
		key = window.event.keyCode; //IE, lol
		ctrl = (window.event.ctrlKey == true)
		shift = (window.event.shiftKey == true)
	} else {
		key = e.which; //Netscape, FF, etc
		ctrl = (e.ctrlKey == true);
		shift = (e.shiftKey == true);
	}
		
	if(key == 9){ // So far indent/outdent sucks in this spec.
		//if(shift){
		//	$('#editor').execCommand("outdent"); return false;
		//} else {
			$('#editor').execCommand("insertparagraph"); return false;
		//}
	}
	
	key = String.fromCharCode(key).toLowerCase();
	if(ctrl){
		switch(key){
			case "b": $('#editor').execCommand("bold"); return false; break;
			case "i": $('#editor').execCommand("italic"); return false; break;
			case "u": $('#editor').execCommand("underline"); return false; break;
		}
	}
}

function getEditorSelection(){
	var userSelection;		// taken straight from quirksmode.org, bless that man
	var doc = $('#editor').contentDocument();
	if(doc.getSelection){
		userSelection = doc.getSelection();
	} else if (doc.selection) { // should come last; Opera!
		userSelection = doc.selection.createRange();
	}

	var selectedText = userSelection;
	if(userSelection.text) selectedText = userSelection.text;
	
	return selectedText;
}

/********************************************************************
                        Image Insert/Upload
**********************************************************************/

function setupInsertImage(){
	alignDrop();
	alignCenterWrapper();
	$("#center_wrapper").show();
	$("#center_wrapper").append("<div id=\"insertImage\" class=\"generic_infobox vert_center\"></div>");
	
	$.get( $('#sitePath').val() + "/rte/insertImageForm.html", {}, function(data){
		$("#insertImage").html(data);
		$.get($("#sitePath").val() + "/rte/cookieData.php", {}, function(data, status){
			cookieinfo = data.split("~~~");
			swfobject.embedSWF($('#sitePath').val() + "/fl/imageupload.swf", "imageUploadFlash", "232", "20", "9.0.0", false, {user_id : cookieinfo[0], user_passhash : cookieinfo[1]}, {allowscriptaccess:"always"});
		});
		
		vertCenter("#insertImage");	
		
		$('#drop').css("opacity","0");
		$('#drop').css("display","block");
		$('#drop').fadeTo("slow",0.8);
		
		$("#insertImage").fadeIn("slow", function(){
			vertCenter("#insertImage");
		});	
	});
}

function cancelInsertImage(){
	$('#drop').fadeOut("slow");
	$("#insertImage").fadeOut("slow", function(){
		$("#insertImage").remove();
		$("#center_wrapper").hide();
	});
}

function insertImageFromURL(){
	var url = $('#insertImageForm #image-url-field').val(); // required
	var title = $('#insertImageForm #image-title-field').val(); //optional
	var align = $('#insertImageForm #image-alignment').val(); // will have a value but defaults to inline just in case
	
	if(!url){
		alert("You must enter the URL (address) to the image you want to insert!");
		return false;
	}
	
	var style = "";	
	switch(align){
		case "left": style = "float:left;"; break;
		case "right": style = "float:right;"; break;
		default: style = ""; break;
	}	
	style += "padding:5px;";
	
	var tag = "<img src='"+url+"' title='"+title+"' alt='"+title+"' style='"+style+"'/>";
	
	$('#editor').execCommand("inserthtml",tag);	
	cancelInsertImage(); // to get rid of box;
}

function afterImageUpload(url){
	$('#insertImageForm #image-url-field').val(url);
	insertImageFromURL();
}

/********************************************************************
                            Embed HTML
**********************************************************************/

function setupInsertHTML(){
	alignDrop();
	alignCenterWrapper();
	$("#center_wrapper").show();
	$("#center_wrapper").append("<div id=\"insertHTML\" class=\"generic_infobox vert_center\"></div>");
	
	$.get($('#sitePath').val() + "/rte/insertHTMLForm.html", {}, function(data){
		$("#insertHTML").html(data);
		vertCenter("#insertHTML");	
		
		$('#drop').css("opacity","0");
		$('#drop').css("display","block");
		$('#drop').fadeTo("slow",0.8);
		
		$("#insertHTML").fadeIn("slow", function(){
			vertCenter("#insertHTML");
		});	
	});
}

function embedHTML(){
	$('#editor').execCommand("inserthtml", $("#embedHTMLTextarea").val());
	cancelEmbedHTML();
}

function cancelEmbedHTML(){  // lol DNR as if
	$('#drop').fadeOut("slow");
	$("#insertHTML").fadeOut("slow", function(){
		$("#insertHTML").remove();
		$("#center_wrapper").hide();
	});
}

/********************************************************************
                           Admin Login
**********************************************************************/

function showAdminLogin(){
	alignDrop();
	alignAdminLogin();
	
	$('#adminlogin').fadeIn("slow");
	$('#drop').css("opacity","0");
	$('#drop').css("display","block");
	$('#drop').fadeTo("slow",0.8);
	
	$('#drop').click(hideAdminLogin);
}

function hideAdminLogin(){
	$('#adminlogin').fadeOut("slow");
	$('#drop').fadeOut("slow");
	$('#drop').click(function(){void(0)});
}

function alignAdminLogin(){
	$('#adminlogin').css("left", ($(document).width() - 344)/2);
	$('#adminlogin').css("top", $(document).scrollTop() + 100);
}

/********************************************************************
                       Presentation Utilities
**********************************************************************/

function alignDrop(){
	if($.browser.msie && ($.browser.version < 7)){ // Internet Exploder		
		$('#drop').css("top", $(document).scrollTop());
		$('#drop').css("height", $(document).height());
	}   
}

function alignCenterWrapper(){
	$("#center_wrapper").css("height",$(document).height());
	if($.browser.msie && ($.browser.version < 7)){
		$('#center_wrapper').css("top", $(document).scrollTop());
	}  
}

function vertCenter(selector){
	var calcHeight = $(selector).height() + parseInt($(selector).css("padding-top")) + parseInt($(selector).css("padding-bottom"));
	$(selector).css("margin-top", (($(window).height() - calcHeight) / 2));
}
